diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..daeab9e7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + + # Maintain GitHub Actions workflows + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + time: "06:00" + timezone: "America/New_York" + groups: + actions: + patterns: + - "*" + commit-message: + prefix: "ci(deps)" diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 32b4a1ea..691cee24 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -27,6 +27,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml new file mode 100644 index 00000000..6af14859 --- /dev/null +++ b/.github/workflows/platforms.yml @@ -0,0 +1,62 @@ +# The gate on macOS and Windows (ADR 0067): build, test and clippy the whole workspace on the +# latest macOS (arm64) and Windows (x64) runners, so `cfg(target_os = "macos")` and +# `cfg(windows)` code (the platform layer, Apple Events, Increase Contrast, contrast themes, +# the Windows resource build) is compiled and linted on every pull request that changes code. +# The Linux gate is ci.yml; this file only calls the suite's shared gate with other runners. +name: CI (macOS, Windows) + +# A change that touches only documentation or other workflows skips both legs. Later patterns +# win: everything, then not docs, Markdown or .github, then this file again. Kept in step in +# both lists (no YAML anchors: not every workflow tool reads them). +on: + push: + branches: [main] + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "!.github/**" + - ".github/workflows/platforms.yml" + pull_request: + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "!.github/**" + - ".github/workflows/platforms.yml" + workflow_dispatch: + +permissions: + contents: read + +# Its own group, so these legs never cancel the Linux gate. A newer push to a PR branch cancels +# its older run (macOS runners are scarce); every push to main runs to the end. +concurrency: + group: ci-platforms-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + gate: + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. The + # shared gate pins every action by SHA, runs Harden-Runner first in each leg, and keys + # rust-cache per OS and architecture (written by pushes to main, read by pull requests). + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["macos-latest", "windows-latest"]' + # Same craft-fonts commit as ci.yml, release.yml and freebsd.yml. + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # Nothing extra: the wasm build is web.yml's, and plain cargo test needs no nextest. + targets: "" + tools: "" + # Cargo.toml's dev profile already keeps line tables only (and Windows PDBs small). + dev-debug: "" + timeout-minutes: 90 + gate-timeout-minutes: 85 + # All three steps run, so one run reports every failure; GPU tests skip themselves when + # the runner has no usable adapter (crates/gpu/src/tests.rs). + command: | + status=0 + cargo build --workspace --locked || status=1 + cargo test --workspace --locked --no-fail-fast || status=1 + cargo clippy --workspace --all-targets --locked -- -D warnings || status=1 + exit "$status" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d99e4a98..304f6cbd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,6 +8,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "0 1 * * *" push: branches: [release] workflow_dispatch: @@ -26,10 +30,12 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: anicraft app-title: AniCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - # No WebAssembly build of the editor yet (roadmap M8). + # The web editor builds (ADR 0036) and packaging/web/package.sh makes its zip (#210), but + # releases don't carry it until the team decides where it is hosted: off for now. has-web: false secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 4c02bdcd..bbf2a232 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -1,7 +1,7 @@ # The web build (ADR 0036, docs/web.md), so it never regresses: every crate of the workspace # builds for wasm32-unknown-unknown, the engine's tests/wasm.rs runs inside WebAssembly in Node # (what a build can't catch: clock, thread and file calls that compile but trap), and -# scripts/build-web.sh produces the web/ bundle. Nothing is deployed. +# packaging/web/package.sh produces the web/ bundle and its release zip. Nothing is deployed. name: Web on: @@ -26,6 +26,10 @@ jobs: env: CARGO_TERM_COLOR: always steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -48,7 +52,8 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner run: cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm --locked - - name: The web editor bundle + # The release download too (#210): what the release workflow's web job runs. + - name: The web editor bundle and its release zip run: | - scripts/build-web.sh - ls -l web + packaging/web/package.sh + ls -l web dist/release diff --git a/AGENTS.md b/AGENTS.md index 2132c555..ac0f5b17 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,7 @@ crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits, registry (ADR 0017) crates/audio L0 Sound decoding (WAV, Ogg Vorbis, MP3), pure mixing and resampling, WAV, peaks (ADR 0020) crates/actions L0 Timeline action IR: stop/play/goto, targets, button events, frame scripts (ADR 0024) +crates/guide L0 The user guide (docs/guide) as a bundled static HTML book, with its link checks (ADR 0069) crates/doc L1 Document model, easing, timeline evaluation, the interactive player, sample scene crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012) crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG) @@ -19,7 +20,7 @@ crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 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, 0029, 0032) -crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp +crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/guide/serve/mcp src/ L5 egui shell (app, menus, stage, timeline, panels, theme) ``` diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc10202..6d2d2567 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,15 +19,18 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | 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 | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `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 | +| `assets/icons/anicraft-*.svg` (28 files: align, distribute, layer, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, asset warp, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage) | Align panel, layer-type, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone, Bind and Asset Warp tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage | 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) | (`icons/.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) | +| `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | 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)) | | `packaging/macos/dmg/` (`background.tiff`, `dmg-layout.DS_Store`) | macOS DMG window background and Finder layout | AniCraft contributors | Original work drawn by `packaging/macos/dmg/generate.py` in the app icon's colours; layout approach as in the PhotoCraft sibling project | MIT OR Apache-2.0 | +| `docs/guide/images/` (8 screenshots) | User guide (Help › User Guide) | AniCraft contributors | Original work: AniCraft's own screenshots, taken by `scripts/guide-shots.sh` | MIT OR Apache-2.0 | | `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 | | Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 | | Sample animation (ball, star, sun, hills, sky) | First launch, tests, CLI `--sample` | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`) | MIT OR Apache-2.0 | | Interactive sample (menu, Play button, spinner) | File › New from Sample (`which: interactive`), Test Movie tests and screenshots | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`, `interactive`) | MIT OR Apache-2.0 | +| Built-in templates (Leaderboard and Rectangle banners, Social square, Storyboard 16:9, Character turnaround, Lip-sync mouth chart: guides, layers, labels and placeholder mouth shapes) | File › New from Template and the start screen (ADR 0065) | AniCraft contributors | Original work, generated in code (`crates/doc/src/templates.rs`); sizes and safe areas follow public conventions (the IAB's 728 × 90 and 300 × 250 ad units, EBU R 95's 93 % action-safe and 90 % title-safe areas), the mouth set the common phoneme groups animators use | MIT OR Apache-2.0 | | Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 | | `docs/brand/artcraft-logo-white.png` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source | | `docs/brand/artcraft-logo-white.svg` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source | @@ -82,23 +85,29 @@ OR Apache-2.0) is noted in the table. | Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). | | Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). | | Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), , Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. | +| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. | +| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. | | 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. | | Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. | +| Colour effects (per-channel multiply and offset; brightness and tint as such transforms) | `crates/doc/src/color_effect.rs`, `crates/gpu/src/fine.wgsl`, `crates/render/src/svg.rs` | Adobe, *ActionScript 3.0 Reference: flash.geom.ColorTransform* (public documentation); W3C *Filter Effects Module Level 1*, `feColorMatrix` | Behaviour learned from the public descriptions; no code or assets used (ADR 0056). | | Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. | | 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. | +| Seeded `Math.random()` for the player (xorshift128) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | G. Marsaglia, "Xorshift RNGs", *Journal of Statistical Software* 8(14), 2003 (public paper); 53-bit doubles from two 32-bit outputs as the common construction | Our own implementation of a published algorithm. | +| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the script IR, the evaluator (types, coercions, operators, `Math`, listeners for enter-frame and keys) | `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`, `Event`, `KeyboardEvent`, `flash.ui.Keyboard`, `Math`, `EventDispatcher.addEventListener` and `removeEventListener`, `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. | | Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. | | ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). | +| ZIP archive writing (web Publish) | `crates/engine/src/publish.rs` (`zip`) | PKWARE APPNOTE.TXT 6.3; the CRC-32 above | Stored entries with UTF-8 names, read back by the reader above in the tests (ADR 0060). | | JPEG decoding (imported images) | `crates/engine/src/cmds_file.rs` | `zune-jpeg` (MIT OR Apache-2.0 OR Zlib), already in the dependency tree | Decoded to RGBA, kept as PNG. | | XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). | +| Button sounds by state transition (Up→Over, Over→Up, Over→Down, Down→Over) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | Adobe, *SWF File Format Specification* (version 19), `DefineButtonSound` (published open specification) | Only the mapping of transitions to the four state frames is taken; no code or data (ADR 0057). | | Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. | | SVG document import: shapes, styling and inheritance, transforms, viewBox and preserveAspectRatio, paint servers (gradients), `use` | `crates/svg` | W3C SVG 1.1 (§5, §6, §7, §9, §13) and SVG 2; CSS Color Module Level 3 (colour syntax and names) | W3C Royalty-Free Patent Policy. | | SVG clip paths, masks and text: `clipPath`, `mask`, `text`/`tspan` positioning and text chunks, white-space handling | `crates/svg/src/clip.rs`, `crates/svg/src/text.rs` | W3C SVG 1.1 (§10, §14) and SVG 2 (§11 Text); W3C CSS Masking Module Level 1; CSS Fonts Level 3 (`font-family`, `font-weight`, `font-size` keywords) | W3C Royalty-Free Patent Policy. | @@ -108,17 +117,23 @@ OR Apache-2.0) is noted in the table. | 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`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.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. | +| Soft masks (alpha and luminance masks, `luminanceToAlpha` coefficients, `mask-type`) and text on a path (`textPath`, `startOffset`, `side`, glyph midpoints on the path, per-character `x`/`y`/`dx`/`dy`/`rotate`) | `crates/render`, `crates/gpu`, `crates/text`, `crates/svg` | W3C CSS Masking Module Level 1 (§7 mask types); W3C SVG 1.1 §10.13 and §14.4, SVG 2 §11.8 (text on a path); W3C Filter Effects (`luminanceToAlpha`); the public Lottie JSON schema (track mattes `td`/`tt`); WHATWG HTML canvas compositing | W3C Royalty-Free Patent Policy; open specifications. Own implementation (ADR 0070). | | 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. | +| Pressure curves (monotone cubic through the curve's points: Fritsch–Butland tangents with the Fritsch–Carlson limits), Paint Brush width profiles simplified by Ramer–Douglas–Peucker, the Chalk brush's worn edge (two-octave value noise from SplitMix64's finaliser, subtracted from the brush's distance field) | `crates/geom/src/pressure.rs`, `crates/geom/src/brush.rs`, `crates/engine/src/cmds_brush.rs` | F. N. Fritsch & R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. (1980); F. N. Fritsch & J. Butland (1984); Ramer (1972) and Douglas & Peucker (1973); S. Vigna's SplitMix64 (public domain); value noise from the public graphics literature; brush library behaviour learned from Adobe's public help and observation | Own implementation (ADR 0068); the built-in brushes are AniCraft's own parameter sets, no Adobe 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). | +| Asset Warp: rigid moving-least-squares deformation of a warp mesh's vertices by pins (weights `1 / d²`, the best rotation from the weighted dot and cross of the centred pins), piecewise affine between them | `crates/doc/src/warp.rs`, `crates/render/src/warp.rs` | S. Schaefer, T. McPhail and J. Warren, *Image deformation using moving least squares*, SIGGRAPH 2006, §2.3 | Published method; own implementation (ADR 0079). | +| Linear blend skinning of a shape's outline by its bones (shape armatures: anchors blended by bone weights, handles with their anchors), with weights from the inverse fourth power of the distance to each bone | `crates/doc/src/skin.rs` | N. Magnenat-Thalmann, R. Laperrière and D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*, Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*, SIGGRAPH 2000, §2 | Published method; own implementation (ADR 0071). | +| Envelope: bicubic Bézier patch warp, inner points from a bicubic Coons patch (ADR 0080) | `crates/geom/src/envelope.rs` | S. A. Coons, *Surfaces for Computer-Aided Design of Space Forms*, MIT Project MAC TR-41, 1967; G. Farin, *Curves and Surfaces for CAGD*, 5th ed., Morgan Kaufmann, 2002 (tensor-product Bézier patches) | Published mathematics; own implementation. | | 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. | | Ogg Vorbis decoding | `crates/audio/src/vorbis.rs` | `lewton` (MIT OR Apache-2.0) with `ogg` (BSD-3-Clause); Xiph.Org's open, royalty-free Vorbis I specification | Used as a library, not copied. | | MP3 (MPEG-1/2 audio layers I–III) decoding | `crates/audio/src/mp3.rs` | `nanomp3` (MIT OR Apache-2.0), a port of minimp3 (CC0) | Used as a library. The MP3 patents have expired; decoding only, no encoder. | +| Animated PNG and animated WebP files: APNG chunks (`acTL`, `fcTL`, `fdAT`), frame regions, blend and dispose ops; the WebP RIFF container (`VP8X`, `ANIM`, `ANMF`) | `crates/engine/src/anim.rs` | The APNG specification (Mozilla; part of W3C *Portable Network Graphics (PNG) Specification*, Third Edition); Google's public *WebP Container Specification* and *WebP Lossless Bitstream Specification*; PNG frame data by the `png` crate (MIT OR Apache-2.0), lossless WebP frames by `image-webp` (MIT OR Apache-2.0) | Open, royalty-free specifications; the chunks are written by our own code (ADR 0063). | ## Rust dependencies diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f4393c8..fe77a165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,508 @@ ## Unreleased +* **Drawing parity leftovers** (ADR 0080, M1). + * **PolyStar options**: Shape (**Polygon** or **Star**), **Sides**/**Points** (3 to 32) and + **Point size** (0 to 1; at 1 a star is the polygon through its tips) in the tool's options. + It merges or draws objects like the other shape tools. + * **Paint Selection** and **Paint Inside** brush modes: the paint is clipped exactly to the + selected fills, or to the fill (or the empty area closed off) where the stroke starts, and + never covers lines. Paint Selection keeps the selection for the next stroke. + * **Double-click a drawing object** (or Ctrl+E) to edit it in place, as groups and symbols + open: inside, its raw shapes merge only with each other. It closes as one drawing object + again; opening and closing it without an edit changes nothing. + * **Modify › Transform › Envelope**: corner and tangent handles bend the selected shapes and + drawing objects through a Bézier patch, one undo step per drag. Like Animate, the bend is + baked into the shapes, so there is no Delete Envelope. + * Headless: `shape`, `sides`, `point_size` on `draw.star`; `selection` and `inside` modes on + `draw.brush`; drawing objects on `symbol.edit`; `modify.envelope`, + `modify.envelope_move`, `modify.envelope_close`. + +* **Asset Warp** (M7, ADR 0079; refs #213). + * **Added**: the **Asset Warp** tool (**Shift+Q**). Click a shape or a bitmap to pin it (the + first pin covers it with a warp mesh), drag a pin to bend the artwork around the others, + live, one undo step per drag; Delete removes the picked pin. Bending is rigid moving least + squares, so the artwork stays as rigid as it can near the pins. + * **Added**: pin poses per keyframe, tweened with classic tweens and their easing; a pin added + later lands on every keyframe of the artwork. Properties › Asset Warp sets the mesh's + resolution and removes pins or the whole warp (also in Modify › Asset Warp). + * **Added**: bitmaps bend in the renderer and on the GPU stage (the same prepared image, so + they match exactly) and in every raster export; SVG writes a bent bitmap as an image; HTML + and Lottie report it. Warped shapes are bent outlines everywhere. + * **Added**: commands `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, + `warp.remove` and `warp.info`, for scripts, plug-ins, the CLI and MCP. +* **Swatches panel** (M1, ADR 0078). + * **Added**: **Window › Swatches**, the document's saved colours and gradients, saved in the + document (new documents and older files start with a default set). Click a swatch to apply + it to the selection and the tool colour, to the stroke or the fill, whichever is active + (the Tools panel's and Colour panel's squares choose, or the panel's own toggle); gradients + go to the fill. Add the current colour or gradient, Duplicate, Delete, drag to reorder + (Alt+arrows from the keyboard), names on hover, Clear and Load Default Swatches. Every + change is one undo step. + * **Added**: Import and Export Swatches as a small JSON swatch file, and import of GIMP `.gpl` + palettes. Adobe's `.aco`, `.ase` and `.clr` are proprietary and not read. + * **Added**: the colour picker shows the document's swatches, and the fill picker its gradient + swatches. + * **Added**: commands `swatch.list`, `swatch.add`, `swatch.remove`, `swatch.move`, + `swatch.duplicate`, `swatch.rename`, `swatch.apply`, `swatch.clear`, `swatch.reset`, + `swatch.import` and `swatch.export`, for scripts, the CLI and MCP (plug-ins may edit swatches + but not read or write swatch files). + * **Fixed**: the timeline's layer footer cut **Delete** to "Del…" at the default window size + since docking. Its buttons are now icon buttons (New Layer, Delete, New Folder, Up, Down), + named for screen readers, that fit at any size and in any language. +* **Rulers, grid and guides** (ADR 0076, M1). + * **View › Rulers** (**Ctrl+Alt+Shift+R**): rulers along the top and left of the stage, in + pixels from its corner, following zoom and pan and marking the pointer. + * **Guides**: drag one out of a ruler; drag it with the Selection tool to move it, or back + onto a ruler to delete it. Each scene keeps its guides in the document. **View › Guides**: + Show (**Ctrl+;**), Lock (**Ctrl+Alt+;**), Snap to Guides (**Ctrl+Shift+;**), Edit Guides + (**Ctrl+Alt+Shift+G**: colour, accuracy, and every guide by position, so the keyboard can + add, move and delete them), Add Guide and Clear Guides. + * **Grid**: **View › Grid** › Show Grid (**Ctrl+'**), Snap to Grid (**Ctrl+Shift+'**), Edit + Grid (**Ctrl+Alt+G**: spacing, colour, show over objects, accuracy up to Always snap). + * **Snap to Pixels** in View › Snapping, next to Snap to Objects, Grid and Guides. + * One snap engine for every drawing tool, the Selection tool's moves (symbols, text and + bitmaps now snap by their box's corners and centre) and Free Transform's handles, in a + fixed order: point, guide, line, grid, pixel. + * Shown on the stage only, never in Test Movie or exports. + * Headless: `view.*` commands (`view.guide_add`, `view.grid_set`, `view.guides_clear`, …) + and `view.aids`. + +* **A light theme** (ADR 0077, M8). Fixes #227. + * **Preferences › Appearance › Theme** offers **Light** beside **Dark (Graphite)** and **High + contrast**: light grey panels, near-black text, hairline-edged buttons and fields, soft + shadows, and the timeline's mint, violet, amber and sky blocks in deeper tones made for a light + background. Applied as you click, no restart. + * **Follow system** now follows your system's light or dark mode as well as its + contrast setting: Windows' app mode, macOS' Appearance, the Linux desktop's colour scheme and + the browser's `prefers-color-scheme`. The window's title bar follows too. + * `anicraft --theme light` (also `dark`, `high-contrast`) previews a theme for one run. + * Every palette is checked by the contrast test (WCAG AA text, 3:1 controls and focus). + +* **Gradient editor, the Gradient Transform tool and Lock Fill** (M1, ADR 0074; #208, #203). + * **Added**: gradients in the colour picker. The fill's picker (the Tools panel's Fill square, + and every Fill swatch in Properties) starts with the fill's type: None, Solid, Linear, + Radial or Bitmap. A gradient shows a bar of colour stops (click to add, drag to move, drag + off to remove; arrow keys and Delete on a focused stop), overflow (Extend, Reflect, Repeat), + Linear RGB and a radial gradient's focal point, above the same swatches, mixer and hex + field, which then set the picked stop's colour and opacity. A gradient's swatch in + Properties shows its ramp. One picker, as Animate has one Color panel; the fill's No Colour + is its type None. + * **Added**: the **Gradient Transform** tool (**F**): move, turn, stretch and resize a gradient, + move a radial gradient's focal point, and scale, turn and skew a bitmap fill. Each drag is + one undo step. + * **Added**: **Lock Fill** for the Paint Bucket and the Brush. Without it, gradients and bitmaps + are fitted to each shape, as in Animate; the Eyedropper turns it on for what it picks. + * **Added**: commands `paint.set_fill`, `paint.transform_fill` and `paint.lock_fill`, for + scripts, the CLI and MCP. + * **Improved**: gradients keep their overflow, Linear RGB, focal point and elliptical shape + from Animate files and SVG drawings, on the GPU stage and in SVG export (HTML canvas draws + them as near as canvas can). Radial gradients on skewed shapes are now drawn exactly. +* **Dockable panels and workspaces** (M8, ADR 0075, fixes #249). + * Drag any panel's tab to dock it on any side of the stage (the timeline above the stage, for + example), stack it with other panels as a tab, or float it in a window of its own (inside + the editor where a system can't open one). Docks and the lines between panel groups resize, + groups fold, and every panel has a menu (☰, or right-click its tab) to dock, float or close + it from the keyboard. + * **Window** lists every panel; choosing one brings it forward, reopening it where it was. + * **Window › Workspace**: Essentials (the layout so far), Animator and Designer, your own with + **Save Workspace…**, and **Reset**. Where everything is is kept in your preferences. + * New **Colour** (stroke and fill, Swap, Black and White) and **Output** (Test Movie's lines, + kept after it closes) panels. Ctrl+F6 visits every docked panel in the order they are docked. +* **Groups and Combine Objects** (ADR 0073, M1; issues #206, #229). + * **Modify › Group** (**Ctrl+G**) and **Ungroup** (**Ctrl+Shift+G**): keep artwork together + without a Library symbol. Double-click a group to edit it in place (the rest dims, the edit + bar says `Scene 1 › Group`); groups nest; merged drawing inside a group only cuts and joins + the shapes in that group. Ungroup puts everything back exactly where it showed. Break Apart + on a group ungroups it. + * **Modify › Combine Objects › Union, Intersect, Punch, Crop** on two or more selected shapes, + with the exact geometry of merge drawing. + * **Selection tool**: **Alt-drag** (Option-drag) to drag a copy away; **Shift** keeps a move + horizontal, vertical or at 45°. + * **Break Apart** on a group ungroups it; its merged drawing merges with the drawing below. + * Animate files keep their groups (`DOMGroup` used to be flattened). + * Headless: `modify.group`, `modify.ungroup`, `modify.combine {op}`, `symbol.edit {id}` on a + group. + +* **Fixed: start-up, files and display, from user reports** (M8). + * Fixed: Flash files that opened in 0.1 no longer opening (#226). One damaged or unreadable + part of a `.fla` (a bitmap, a sound, a library symbol) no longer stops the whole file from + opening: the rest opens and the report says what was left out. A file double-clicked or + opened with **Open With** that can't be opened now says why in the status bar instead of + quietly showing the sample, and `anicraft-cli info`, `render` and the export commands open + `.fla` and `.xfl` files too. + * Fixed: Animate documents opening on a black stage instead of white (#163). + * Fixed: AniCraft not opening at all on some laptops with two graphics chips, such as the + Surface Book 2 (#207). If a way of drawing the window fails, AniCraft now tries the next one + (on Windows: DirectX 12 on the built-in chip, then OpenGL) instead of exiting, and a start that + crashed inside a graphics driver tries that way last next time. If nothing works, a message + says so. A start-up log in the settings folder (`Logs/anicraft.log`) records what was tried, + to attach to a bug report. + * New: **Preferences › Stage › Window graphics** chooses how the window is drawn (Automatic, + DirectX 12, Vulkan, Metal or OpenGL), for windows that flicker or flash black (#255). + `--renderer dx12`, `vulkan` and `metal` now pick that interface; before, they all meant the + default. + * Fixed: the selection shading on shapes stopping part way down when zoomed in or on a big + shape (#204). The dot pattern now covers the whole shape and its outline at any zoom, and + costs the same however much of the screen it covers. + * The web version's download is now built by `packaging/web/package.sh` and checked in CI; the + README no longer suggests releases carry it yet (#210). +* **Drawing tools and colour fixes from user reports** (M1). + * **Fixed**: the Fill and Stroke colour squares in the Tools panel did nothing when clicked. + They open the colour picker now, with No Colour, and recolour selected shapes (#246). + * **Fixed**: the colour picker had no hex field. Every colour swatch's picker shows the colour + as `#rrggbb` and takes one you type (#201). + * **Fixed**: the colour picker had no web-safe palette. It opens on Animate's 216 web-safe + swatches, with greys and primaries beside them and the colours you mix or type in a row + below; **Mixer** has the full picker (#248). + * **Fixed**: the Pencil's Properties showed a Fill swatch, though the Pencil only draws lines. + The Pencil and the Line tool show only the stroke now (#252). + * **Fixed**: a squiggle drawn with Object Drawing on was trapped in its object. **Modify › + Break Apart** (Ctrl+B) now turns a drawing object into merged drawing you can edit (#253). + * **Fixed**: the Width tool didn't thicken a line when you dragged on it, the pointer didn't + change, and the marker was a tiny dark box. A drag on the line widens it there, the pointer + is a crosshair (an add pointer over a line), and the marker is a white box with handles + (#250). + * **Fixed**: every new line segment came with a scale gizmo whose handles couldn't be dragged, + and a box appeared after every brush or pencil stroke. As in Animate, what you draw isn't + left selected, and the Selection tool's box no longer shows handles that do nothing (#205, + #243). + * **Fixed**: Ctrl-dragging a shape's edge made a smooth curve. It adds a corner point where you + pressed, with straight sides on a straight edge (#200). +* **Filters, Subtract and Invert in HTML canvas export** (ADR 0072, M6). Exported web pages now + show every filter (Drop Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel and Adjust + Color, with inner, knockout, hide object and Inner/Outer/Full) and the Subtract and Invert blend + modes as AniCraft draws them, in every browser: the page runs a port of AniCraft's own filters + over the symbol's pixels instead of the browser's effects, and shadows and glows reach onto the + stage from symbols beside it. A filtered symbol that doesn't change is filtered once. Tested + against AniCraft's renderer pixel by pixel (35 filter set-ups at three view scales, within + 1/1000) and checked in a browser. At 1080p the demo's filtered symbols cost 3.4 ms a frame while + they change; one covering the whole frame 50 to 150 ms. The export report no longer lists them. +* **Timeline, bones, menus and stage fixes from user reports** (M1). + * **Fixed**: F5 with no frames selected only extended the active layer. It now extends every + layer that has frames at or after the playhead, as in Animate, and leaves the layers that end + before it alone (#242). + * **Fixed**: after F5, F6 or F7 you had to select the next frame by hand. F5 now moves onto the + frame it adds, and F6 or F7 on a keyframe makes the new keyframe on the next frame and moves + there, so draw, F6, draw keeps going (#254). F7 on a keyframe no longer clears its drawing. + * **Fixed**: the timeline's Frame, Keyframe and Blank buttons took a lot of room. They are icons + now (a frame, a filled dot and a hollow dot, each with a plus), named in their tooltips (#240). + * **Fixed**: bone chains looked broken and jumped while posing. A bone started anywhere on an + instance now starts at the end of the bone before it, so the chain stays joined, and dragging + a bone along its length moves it from where you grabbed it instead of snapping its end to the + pointer (#239). + * **Fixed**: on macOS there were no menus (no File, no Save). The title bar covered the menu + row; it is see-through now, as designed (#247). + * **Fixed**: you couldn't draw outside the stage; anything past its edge was hidden. The + pasteboard now shows your artwork, as in Animate, and **Clip content outside the stage** + (beside the zoom menu, and in the View menu) hides it again when you want (#245, #251). +* **Soft masks and text on a path** (ADR 0070, M4). + * **Soft masks**: Layer Properties › **Mask type** on a mask layer: *Shape* (as in Animate), + *Alpha* (the mask's opacity reveals: a gradient to transparent fades the artwork out) or + *Luminance* (the mask's brightness reveals: white shows, black hides). On the stage, on the + GPU stage, in Test Movie and in every export: SVG writes a `mask`, Lottie a track matte, the + HTML canvas composites it. `layer.set_mask` does it headless. + * **Text on a path**: Properties › Path › **Attach to Path**, then click a shape: static text + follows its outline (a copy of it; the shape stays). Move it along with **Offset**, put it on + the other side with **Flip**, and **Release** it back to lines of text. The alignment says + whether the text starts, is centred or ends at the offset. Editing the words, the font or + the size keeps it on its path. Also Modify › Text › Attach Text to Path. + * **SVG import**: soft masks come in as soft mask layers (luminance, or alpha with + `mask-type: alpha`) instead of being drawn unmasked; `textPath` comes in as text on a path; + per-character `x`, `y`, `dx`, `dy` and `rotate` are kept where they are simple. +* **Bones inside shapes** (ADR 0071, M7). + * The **Bone** tool now also draws bones inside a shape, so the shape itself bends like a tail + or a tentacle. Its points follow the nearest bones, and the bend stays smooth through the + joints. Lines keep their width, and the shape as drawn comes back exactly at rest. + * Pose by dragging bones with the Selection tool. Poses key per frame and tween with easing, + as symbol armatures do, and every export, Test Movie and the stage show the bend. + * The new **Bind** tool (**Shift+M**) shows which points follow which bone, and changes it by + click, Shift-click, Ctrl-click or a box. **Properties › Bone** counts the bone's points and + has **Rebind All**. + * Headless: `bone.add_in_shape`, `bone.bind`, and `bone.info` with `points`. +* **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds, + tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so + macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip + them, and a newer push cancels the older run. Their first run + found one macOS-only failure: the screen-reader translation tests treated the macOS app + menu's title, the product name, as untranslated. +* **The user guide** (ADR 0069, M8). + * **Help › User Guide** opens AniCraft's guide in your browser. It comes with the app, so it + works offline; the web editor serves it beside the editor. It is also in the command palette. + * Eighteen chapters written for artists, from getting started, drawing, symbols, the timeline and + tweens to masks, the camera and bones, text, images and sound, interactivity, exporting and + Publish, opening Animate files, preferences and accessibility, plug-ins, working headless, and + troubleshooting, plus **Coming from Animate**, which maps Animate's panels, tools and shortcuts + to AniCraft's. + * A **command reference** and a **shortcut reference** (with the macOS keys beside the others), + generated from AniCraft itself, so they always match the version you have. + * `anicraft-cli guide --out ` writes the guide as HTML pages. + * On macOS, the fixed keys that hold a key while dragging ("Space+Drag") keep that key in their + label. +* **Brush library, pressure curves and the Paint Brush** (ADR 0068, M7). + * **Window › Brush Library**: seven built-in brushes, each with a stroke preview drawn by the + renderer: Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk (a ragged edge that + is the same every time) and Dotted. They are all made of parameters, with no bitmaps. A click + sets the brush in hand. + * **Your own brushes**: Save Brush keeps the brush in hand under a name, in your preferences. + Right-click to rename or delete one (deleting asks first). Import… and Export… move a brush + set between computers as a small JSON file. + * **Pressure curves**: an editor in Properties maps pen pressure to the size and, optionally, + to the stroke's opacity. It has Linear, Soft and Firm presets, or your own points. + * **Shaping**: tapers at the start and end, dab spacing and a rough edge, in Properties. + * **Velocity**: without a pen, drawing faster draws thinner (off by default). + * **Paint Brush (Y)**: draws a line in the stroke colour whose width follows the pressure and + tapers, as a width profile you can reshape with the Width tool. + * Headless: `brush.preset_list`, `brush.preset_save`, `brush.preset_rename`, + `brush.preset_delete`, `brush.preset_export`, `brush.preset_import`; `preset`, `curve`, + `pressure_size`, `pressure_opacity`, `taper_start`, `taper_end`, `spacing`, `jitter` and + `as_stroke` on `draw.brush`. + * Pen tilt isn't read yet: egui doesn't report it. + +* **Dynamic and input text fields** (ADR 0066, M5). + * **Properties › Text type**: Static, Dynamic or Input text, as in Animate. Dynamic and input + fields have an **instance name**, a **line type** (single line, multiline, multiline no wrap, + password), a fixed **box**, **Show border**, **Selectable** and **Max characters**. + * **Scripts** set and read fields: `score_txt.text = "Score: " + n`, `appendText`, `.length`. + * **Test Movie**: click an input field and type. Caret, selection with Shift and the pointer, + Backspace, Delete, the arrows, Home, End, Enter in multiline fields, Tab to the next field, + Select All, Copy, paste and input methods. Screen readers find fields as text inputs. + * **HTML canvas export**: input fields are real text inputs over the movie (input methods, the + on-screen keyboard and the clipboard work), and text that scripts set is drawn in the + browser. Authored text is drawn exactly as in AniCraft. + * **Animate files**: dynamic and input fields come across as fields, with their names, boxes, + borders and line types (they used to become static text). + * Every other export and the stage draw fields with their authored text, box and border. + * `text.field`, `text.create {type}` and `control.test_movie` `text` and `select_all` events + for agents and the CLI. +* **Templates, SVG into the Library, and drops on the timeline** (ADR 0065, M8). + * **File › New from Template** and the start screen's new **Templates** row: Leaderboard banner + 728 × 90, Rectangle banner 300 × 250, Social square 1080 × 1080 at 30 fps, Storyboard 16:9 (six + labelled panels), Character turnaround and a Lip-sync mouth chart. Each has named layers and + guides on a locked guide layer (they show while drawing and never export). They open as new, + untitled documents with a drawing layer active. + * **File › Save as Template** keeps the open document, with a picture, under a name and a + category in your settings folder. It shows under "My templates" on the start screen, with + Delete. Replacing or deleting a template asks first. + * **SVG into the Library**: dropping an SVG on the Library, or File › Import › Import to Library, + makes one graphic symbol named after the file, in the folder under the pointer. + * **Drops on the timeline**: a sound dropped on a layer's frame goes onto that keyframe. An image + or SVG goes onto that layer at that frame, in a new keyframe if needed. Either way it is one undo + step, and a highlight shows the cell. Locked layers, folders and the camera say why they won't + take it. + * The timeline's layer footer keeps its Move Down button in every language. + * Headless: `file.new_from_template`, `file.templates`, `file.save_as_template`, + `file.delete_template`, and `file.drop` with `to: "timeline"`. + * Exact drop positions from the desktop still wait for winit 0.31 (eframe 0.37 is still on 0.30). +* **Accessibility, second pass** (ADR 0064, M8). + * **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to + its elements, and a ring shows the focused one on the artwork. + * Tab, Shift+Tab and the arrows move between elements. + * Enter or Space selects one; Shift+Enter or Shift+Space adds it to the selection or + takes it out. + * Esc goes back to the stage. + * **Screen readers hear what is on the stage.** While the stage has focus, its elements are + a list ("Rectangle", "Text: Hello", "ball · Graphic: Ball"), each with its layer, place, + size, on-screen bounds and whether it is selected. + * **The active layer's frames are a list too.** Each item reads "Frames 1–24: keyframe · + motion tween · label “walk”", and activating one moves the playhead there. + * **The timeline from the keyboard.** On the focused timeline, the arrows move the playhead + and the active layer, and each move is announced. + * **The menu bar from the keyboard** on Windows and Linux. + * Press and let go of Alt, or press F10. Then the arrows, Enter and Esc work as in other + applications. + * Alt+F, Alt+E and the rest open a menu directly. While Alt is held, each title shows its + letter underlined. + * **Follow system** is the new default theme. AniCraft switches to high contrast while + Windows uses a contrast theme, macOS has Increase Contrast on, the Linux desktop asks for + high contrast, or the browser prefers more contrast. Choosing Graphite or High contrast + keeps that palette. + * Headless: `element.select` takes `toggle`. + +* **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8). + * **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop, + as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the + screen), titled with the document's name, and opens where it was last. It takes the + keyboard when it opens. **Esc** or **Ctrl+W (⌘W)** closes it, Ctrl+Enter restarts it in + place, and the editor's Ctrl and Alt shortcuts still work from it. + * In the web build, and wherever the system can't open another window, it floats inside the + editor as before and says why. **Preferences › Test Movie** keeps it inside the editor if + you prefer. On Wayland the desktop places the window, so it can't come back where it was + (Preferences says so). + * **macOS:** double-clicking a `.anicraft`, `.fla` or `.xfl` in Finder, dropping it on the + Dock icon, or choosing Open With › AniCraft opens it, whether AniCraft is running or + not. If there are unsaved changes it asks first, and the Dock's Quit asks to save too. + This uses the small `fmv-macos-events` crate (MIT OR Apache-2.0), so AniCraft's own code + stays free of `unsafe`. Still to be checked on a Mac (the list is in ADR 0062). + * Windows and Linux already open a double-clicked document from the command line; a test + now covers it. + +* **Timeline polish** (ADR 0061, M1). + * A **per-layer onion skin toggle** in each layer row (Alt-click: this layer only, again: + every layer). Layers left out show only their playhead frame; Edit Multiple Frames still + edits them. + * **View as Outlines** draws a layer's artwork as hairlines in its colour **on the stage + only**. Exports, Test Movie and the player draw it as it is (before, an outlined layer + exported as outlines). The **colour chip** on the row's edge opens the layer colour. + * **Onion skin inside a symbol edited in place** now also shows the parent timeline's frames + around it, dimmed. + * **Layer Height** 100 / 200 / 300 % (right-click menu), **Layer Properties** (double-click a + layer's icon, Properties… or Modify › Timeline), and a **Frame View** menu with frame widths + Tiny to Large and **Short** rows. Frame zoom and Frame View sit at the right end of the + timeline's bottom bar, as in Animate, so the header fits at the default window size again + (the tween-kind menu was cut off). + * Headless: `layer.set_onion`, `layer.set_color`, `layer.set_height`, `layer.set_properties`, + `layer.properties`. Saved in the document with defaults left out, so older files open as + before. XFL import reads a layer's height. +* **Animated PNG and animated WebP export** (ADR 0063, M4). + * **File › Export › Export Animated PNG…** and **Export Animated WebP…** make full-colour + animations with real transparency, for the web and chat apps, where a GIF has 256 colours + and hard edges. WebP is lossless. Both are transparent by default; turn on the stage colour + as background if you want it. Loop forever, play once, or play a set number of times. + * Every frame is exactly what AniCraft renders. Frames that repeat the one before are stored + once and shown longer, and each later frame stores only the rectangle that changed, so + holds and small motions cost little. + * Timing is exact: APNG delays are fractions of the frame rate (29.97 fps stays 29.97), and + WebP's milliseconds never drift. + * Both are in **Publish Settings** (Animated PNG, Animated WebP) with frames, scale, loop and + background; in a browser they download. Headless: `file.export_apng`, `file.export_webp` + and `anicraft-cli apng` / `webp`. + * On the sample (48 frames, 1280 × 720) the APNG is 2.0 MB and the WebP 1.8 MB, against the + GIF's 1.4 MB, which has only 256 colours; both take less time to make than the GIF. + +* **Publish Settings and Publish** (ADR 0060, M8). + * **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work. + It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite + sheet, PNG sequence, PNG, SVG, audio), each with a checkbox. The selected format shows + its output name and the same options its File › Export command has. The settings are + saved **in the document** and every change can be undone. Older files open with the HTML + page on. + * Output names are relative to the document's folder, and `{name}` stands for the + document's name (`web/{name}.html`). Each name is checked as you type and the full path + is shown below it. A name can't point outside the document's folder, and two formats + can't write the same file. + * **File › Publish** (Shift+F12) writes every format that is on, in the background. A + window shows each format's progress and has a Cancel button. A single report then lists + what each format wrote, skipped (video in a browser, audio with no sounds), left out + (Lottie's and the HTML page's notes) or why it failed. One failing format doesn't stop + the others. + * Publishing over files that are already there asks once. After that, the files this + session published are replaced without asking. + * **Presets**: save the settings under a name, apply them to any document, or delete them. + Presets are kept in your preferences. + * In a browser, the files go to your downloads, as one ZIP when there are several. + * Headless: `publish.settings_get`, `publish.settings_set` and `file.publish`, which returns + the report. Publishing the sample in six formats takes 0.64 s. +* **Files from the desktop, recent files and a start screen** (ADR 0059, M8). + * **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over + unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the + **stage** go onto the active layer at the playhead, centred where they were dropped, and + dropped on the **Library** go into the folder under the pointer. One undo step per drop. + A highlight shows where they will land; anything AniCraft can't take gets one clear + status line. In the web editor too. + * **File › Open Recent**: the last 10 documents opened or saved, with pinned favourites on + top, missing files greyed out with Remove, and Clear Recent Files. Kept in the + preferences (browser storage on the web). + * **Start screen** when AniCraft starts without a document: New with HD, Full HD, square + and vertical presets or a custom size and frame rate, Open, the sample animation, and the + recent files with a picture of their first frame (captured on save). Esc goes back to the + document; File › Start Screen brings it back; it can be switched off. + * New commands for the CLI and MCP: `file.drop`, `file.open_recent`, `file.recent_list`, + `prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes + `cx`/`cy` and `layer: "active"`. + +* **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5). + * A sound on a button's **Over** or **Down** frame plays when the pointer goes over or + presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format + keeps them, the Up frame's plays on leaving and the Hit frame's on letting go over it. A + stream on a button frame plays as an event. Buttons stay out of the soundtrack: Export Audio + and video are unchanged. + * Editing a button in place, the timeline names its four frames **Up, Over, Down, Hit** (and + widens them to fit while the button is open), and the stage draws the **Hit area** + translucent over the other states. + * Test Movie has a **Show hit areas** checkbox. + * XFL and `.fla` import bring sounds whose file is in the package (WAV, Ogg Vorbis, MP3), with + the sounds on frames that use them, buttons' states included; sounds kept only in Animate's + own format are reported. + * Headless: `control.test_movie` lists the sounds it started. + * 9-slice guides switched off are now kept, and come back where they were when switched on. +* **Find and Replace, and the Movie Explorer** (ADR 0058, M8). + * **Edit › Find and Replace** (Ctrl+F) is a window that stays open while you work. It finds + text in text fields, frame labels, layer names, instance names and frame scripts, with + match case, whole word and regular expressions. It also finds fonts, colours (fills, + gradient stops, strokes, text), symbols, sounds and bitmaps. It searches this scene and + the symbols in it, or the whole document. Results show as you type. + * Click a result, or press **Find Next** (F3) or Find Previous (Shift+F3), to go there: the + scene, the frame and the item selected. A symbol opens in place through the instances + that lead to it. + * **Replace** replaces the current result and goes on to the next. **Replace All** is one + undo step and asks first above 100 places. Replaced text is laid out again, colours keep + their transparency, and a symbol is never put inside itself. + * **Window › Movie Explorer** (Alt+F3) is a tab next to the Library. It shows scenes › + layers › keyframes › instances, text, sounds, bitmaps and scripts, each instance opening + into its symbol, plus the Library's symbol definitions. A Show menu filters it by kind + and a search keeps matching rows. Double-click a row to go there. + * Both lists draw only the rows in view, so movies with 100,000 rows stay smooth. + * Headless: `find.search`, `find.replace`, `find.goto` and `explorer.tree` (paged). + Patterns use a linear-time engine with size limits. +* **Colour effects, complete** (ADR 0056, M2). + * **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced, + Alpha) with each style's controls: brightness −100..100 %, tint colour and amount, + Advanced's multiplier and offset for red, green, blue and alpha. Every row says "mixed" + when the selection differs, and a change sets only that value on all of them. Switching + style keeps the look where it can (Advanced starts as exactly the effect before). + * One exact colour transform behind every style: nested effects compose exactly (a + brightness around a tint shows both), and the CPU renderer, the GPU stage (bitmaps + included, pixel-identical), SVG (`feColorMatrix` on bitmaps), HTML canvas (bitmaps + recoloured, no longer reported) and Lottie (baked into the colours) draw the same. + * Classic tweens interpolate within a style (a brightness tween passes through 0) and across + styles in the Advanced space, as Animate does. + * Motion tweens key **Brightness**, **Tint** colour (red, green, blue) beside its amount, and + the eight **Advanced** values; the Motion Editor lists the styles in use and adds others + with **Add Colour Effect**. A tween has one colour effect style, as in Animate. + * XFL/FLA import brings every `Color` style across (Advanced no longer keeps only its + alpha); a new `colour` corpus package with goldens. + * `element.set_color_effect` for the CLI, MCP and plug-ins; `element.set_alpha` now keeps + the rest of the effect. Older files open unchanged, and None, Alpha and Tint effects are + still written exactly as before. + +* **9-slice scaling for symbols** (ADR 0055, M2). + * **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in + Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way + and its centre both ways. Rounded buttons and panels resize without distorting, strokes + keep their width, and rotation and skew apply after. Nested symbols, text and bitmaps + inside scale normally, as in Animate. When there isn't room for the corners, they shrink + together in proportion. + * While the symbol is open for editing, its four guides are **dashed lines across the + stage**. Drag them with the Selection tool (one undo step per drag), or type their + positions in Properties. + * Every export draws it from the same frames. SVG and Lottie get baked outlines. HTML canvas + export scales such instances as a whole for now and says so in its report. + * XFL and `.fla` import read `scaleGridLeft/Right/Top/Bottom`. Headless: + `symbol.set_scale_grid {symbol?, on?, left?, right?, top?, bottom?}`. +* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0052, M6). + * Typed variables (`var score:int = 0;` as Number, int, uint, Boolean, String or untyped), + kept per timeline instance across its frame scripts as Animate timelines keep them; + expressions (arithmetic, comparison, logic, joining text, `Math.min/max/abs/floor/ceil/ + round/random`, casts); `if`/`else`, `for`, `while` and `do` loops; functions with + parameters and results, callable from any frame of the same timeline. + * Scripts read properties of instances and timelines (`x`, `y`, `alpha`, `visible`, + `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), + remove listeners, and listen for `Event.ENTER_FRAME` and for keys on the stage + (`KeyboardEvent.KEY_DOWN`/`KEY_UP`, `e.keyCode`); `e.target` and `e.currentTarget` work. + * Test Movie sends your keys to the movie (it says so in its bar); `Math.random()` is + seeded, so a headless `control.test_movie` with the same `seed` and events always plays the + same; key events and `seed` there too. + * An endless loop or an error stops only its script, with a line in Output, and the movie + plays on. A script that uses a name no frame of its timeline declares doesn't run, and the + Actions panel shows the name in place. + * The HTML canvas export runs the same scripts, keys included, checked against Test Movie + step by step. + +* **Repeating bitmap fills on the GL backend** (M3): the GPU stage wrapped a repeating + bitmap with a signed remainder, which GLSL leaves undefined for negative values, so on + OpenGL (llvmpipe in the FreeBSD VM) the texels at the bitmap's left and top edges came out + wrong. It now wraps without one, and a test keeps every shader free of signed remainders. * **Library and Properties polish** (ADR 0053, M2). * **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once. diff --git a/Cargo.lock b/Cargo.lock index a6ed64c8..262e659d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,6 +134,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned-vec" version = "0.6.4" @@ -207,17 +216,20 @@ dependencies = [ [[package]] name = "anicraft" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-audio", "anicraft-doc", "anicraft-engine", "anicraft-geom", "anicraft-gpu", + "anicraft-guide", "anicraft-render", "cpal", + "craft-update", "eframe", "egui", + "fmv-macos-events", "fontdb", "js-sys", "rfd", @@ -228,12 +240,13 @@ dependencies = [ "wasm-bindgen-futures", "web-sys", "web-time", + "winreg", "winresource", ] [[package]] name = "anicraft-actions" -version = "0.1.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -241,7 +254,7 @@ dependencies = [ [[package]] name = "anicraft-audio" -version = "0.1.0" +version = "0.2.1" dependencies = [ "lewton", "nanomp3", @@ -249,18 +262,19 @@ dependencies = [ [[package]] name = "anicraft-cli" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-engine", "anicraft-geom", + "anicraft-guide", "anicraft-render", "serde_json", ] [[package]] name = "anicraft-doc" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-actions", "anicraft-audio", @@ -273,7 +287,7 @@ dependencies = [ [[package]] name = "anicraft-engine" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -283,9 +297,11 @@ dependencies = [ "anicraft-text", "anicraft-xfl", "gif", + "image-webp", "miniz_oxide 0.8.9", "png 0.17.16", "rayon", + "regex", "serde", "serde_json", "thiserror 2.0.21", @@ -296,7 +312,7 @@ dependencies = [ [[package]] name = "anicraft-geom" -version = "0.1.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -304,12 +320,13 @@ dependencies = [ [[package]] name = "anicraft-gpu" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", "anicraft-render", "bytemuck", + "naga", "pollster 1.0.1", "rayon", "thiserror 2.0.21", @@ -317,9 +334,16 @@ dependencies = [ "wgpu", ] +[[package]] +name = "anicraft-guide" +version = "0.2.1" +dependencies = [ + "pulldown-cmark", +] + [[package]] name = "anicraft-plugins" -version = "0.1.0" +version = "0.2.1" dependencies = [ "serde", "serde_json", @@ -330,7 +354,7 @@ dependencies = [ [[package]] name = "anicraft-render" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -343,7 +367,7 @@ dependencies = [ [[package]] name = "anicraft-svg" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -354,7 +378,7 @@ dependencies = [ [[package]] name = "anicraft-text" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-geom", "fontdb", @@ -365,7 +389,7 @@ dependencies = [ [[package]] name = "anicraft-xfl" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -378,7 +402,7 @@ dependencies = [ [[package]] name = "anicraft-xml" -version = "0.1.0" +version = "0.2.1" dependencies = [ "thiserror 2.0.21", ] @@ -604,6 +628,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -631,6 +661,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -934,6 +973,15 @@ dependencies = [ "libc", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -988,6 +1036,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -998,6 +1055,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1011,7 +1078,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -1024,7 +1091,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] @@ -1087,6 +1154,40 @@ dependencies = [ "windows-core", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a#6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" +dependencies = [ + "chrono", + "dunce", + "flate2", + "getrandom 0.3.4", + "log", + "plist", + "rustix 1.1.5", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1127,6 +1228,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1159,6 +1270,16 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1218,6 +1339,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dynify" version = "0.1.2" @@ -1342,6 +1469,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "winit", ] @@ -1536,6 +1664,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1559,6 +1697,17 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -1620,6 +1769,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1697,6 +1855,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1707,6 +1875,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1726,8 +1905,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "wasm-bindgen", ] [[package]] @@ -1939,6 +2120,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "icu_collections" version = "2.0.0" @@ -2028,6 +2225,27 @@ dependencies = [ "zerovec", ] +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -2042,6 +2260,16 @@ dependencies = [ "tiff", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -2442,6 +2670,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2919,6 +3159,12 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -3094,6 +3340,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.17.16" @@ -3224,6 +3483,24 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "pulldown-cmark" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "pulldown-cmark-escape", + "unicase", +] + +[[package]] +name = "pulldown-cmark-escape" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" + [[package]] name = "pxfm" version = "0.1.30" @@ -3245,6 +3522,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3377,6 +3663,35 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "regress" version = "0.10.5" @@ -3420,6 +3735,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3467,6 +3796,80 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3488,6 +3891,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3500,6 +3912,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3511,6 +3946,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -3575,6 +4014,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3768,6 +4218,12 @@ dependencies = [ "serde", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -3836,6 +4292,16 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4077,6 +4543,18 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -4088,6 +4566,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -4118,6 +4602,53 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "utf16_iter" version = "1.1.0" @@ -4127,6 +4658,21 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf_types" version = "1.0.0" @@ -4171,6 +4717,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -4187,6 +4743,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4503,7 +5065,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4539,6 +5101,31 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4953,7 +5540,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -4998,6 +5585,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + [[package]] name = "winresource" version = "0.1.34" @@ -5008,6 +5605,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5259,6 +5862,26 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" @@ -5294,6 +5917,25 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "9.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index 15bb9237..2c6d31cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,13 +6,13 @@ default-members = [".", "crates/*"] [workspace.package] # 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md # and docs/release.md. -version = "0.1.0" +version = "0.2.1" edition = "2024" license = "MIT OR Apache-2.0" # An application, not a library: not published to crates.io. publish = false repository = "https://github.com/storytold/AniCraft" -rust-version = "1.90" +rust-version = "1.95" [workspace.dependencies] anicraft-geom = { path = "crates/geom" } @@ -26,9 +26,12 @@ anicraft-text = { path = "crates/text" } anicraft-plugins = { path = "crates/plugins" } anicraft-audio = { path = "crates/audio" } anicraft-gpu = { path = "crates/gpu" } +anicraft-guide = { path = "crates/guide" } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" +# The WGSL front end wgpu already builds, for checking the shaders in tests. +naga = { version = "30", features = ["wgsl-in"] } pollster = "1" bytemuck = "1" anicraft-actions = { path = "crates/actions" } @@ -40,6 +43,8 @@ png = "0.17" # JPEG decoding for imported images (already in the tree; MIT OR Apache-2.0 OR Zlib). zune-jpeg = { version = "0.5", default-features = false } gif = "0.14" +# Lossless WebP frames for animated WebP export (pure Rust, MIT OR Apache-2.0; ADR 0063). +image-webp = "0.2" # wgpu is the primary renderer; glow (OpenGL) is the fallback for GPUs/VMs where wgpu fails. # Default features off: we skip `links` (opening web links pulls in url/idna/ICU Unicode # tables we don't use) and the web-only screen-reader shim. Same set as PhotoCraft, plus glow. @@ -54,6 +59,9 @@ egui = "0.36" # `Instant` and `SystemTime` that work in the browser too (std's panic on wasm32-unknown-unknown); # on other targets a re-export of std::time (MIT OR Apache-2.0; already in the tree via winit). web-time = "1" +# Find and Replace's pattern matching (ADR 0058): linear time, with size limits on what a +# pattern compiles to (MIT OR Apache-2.0). Unicode case folding and word boundaries only. +regex = { version = "1", default-features = false, features = ["std", "perf", "unicode-case", "unicode-perl"] } [workspace.lints.rust] unsafe_code = "forbid" @@ -102,11 +110,28 @@ web-time.workspace = true sys-locale = "0.3" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -eframe.workspace = true +# The user guide, bundled for Help › User Guide (ADR 0069). The web build serves it as pages instead. +anicraft-guide.workspace = true +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" } + +eframe = { workspace = true, features = ["links"] } rfd.workspace = true # Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs. cpal = { version = "0.18", optional = true } +# macOS hands a double-clicked document to the app as an Apple Event, which winit 0.30 doesn't +# deliver (ADR 0062). This small crate (MIT OR Apache-2.0, ~170 lines, read in full) registers the +# open-documents and quit handlers with AppKit and hands us plain paths, so our code stays free of +# `unsafe`. Pinned exactly: it is young, and a new version is read again before it comes in. Its +# objc2 / objc2-app-kit / objc2-foundation are the versions wgpu already brings on macOS. +[target.'cfg(target_os = "macos")'.dependencies] +fmv-macos-events = "=0.1.0" + +# The system's high-contrast setting (ADR 0064): one registry value. MIT, already in the tree +# through craft-update. +[target.'cfg(windows)'.dependencies] +winreg = "0.55" + # The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current # browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download # smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web @@ -118,7 +143,7 @@ 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"] } +web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] } [build-dependencies] # Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets. diff --git a/README.md b/README.md index 1770b5e9..eb6390d7 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ cargo run --release -p anicraft-cli -- render --sample --frame 12 --out frame12. cargo run --release -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5 cargo run --release -p anicraft-cli -- gif --sample --out animation.gif cargo run --release -p anicraft-cli -- commands # the command registry as JSON +cargo run --release -p anicraft-cli -- guide --out guide # the user guide as HTML pages cargo run --release -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft cargo run --release -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout cargo test # all crates @@ -215,6 +216,11 @@ src/ L5 egui shell (app, menus, stage, timeline, panels, theme) No code below `src/` depends on egui, eframe or windowing libraries. +**New to AniCraft?** The [**user guide**](docs/guide/index.md) is written for artists: getting started, every +workflow, a chapter for people [coming from Animate](docs/guide/coming-from-animate.md), and generated +[command](docs/guide/reference/commands.md) and [shortcut](docs/guide/reference/shortcuts.md) references. It also +opens offline from **Help › User Guide**. + Agent and contributor rules (clean room, the asset policy, no panics in shipped code) are in [`AGENTS.md`](AGENTS.md). [`docs/requirements.md`](docs/requirements.md) has the scope, [`docs/architecture.md`](docs/architecture.md) the design, [`docs/product-principles.md`](docs/product-principles.md) the design and user experience principles, @@ -267,7 +273,7 @@ RISC-V (riscv64): `anicraft--linux-riscv64.tar.gz`, a tarball only. | Build | File | Notes | |---|---|---| -| Static site | `anicraft-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `anicraft-web-.zip` | Not in the releases yet: build it yourself with `packaging/web/package.sh` ([docs/web.md](docs/web.md)), then host it on any static server | ## The Crafting Apps diff --git a/assets/icons/anicraft-bind.svg b/assets/icons/anicraft-bind.svg new file mode 100644 index 00000000..c7842936 --- /dev/null +++ b/assets/icons/anicraft-bind.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/anicraft-clip-stage.svg b/assets/icons/anicraft-clip-stage.svg new file mode 100644 index 00000000..fe7070f0 --- /dev/null +++ b/assets/icons/anicraft-clip-stage.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/assets/icons/anicraft-gradient-transform.svg b/assets/icons/anicraft-gradient-transform.svg new file mode 100644 index 00000000..907d4395 --- /dev/null +++ b/assets/icons/anicraft-gradient-transform.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/anicraft-insert-blank-keyframe.svg b/assets/icons/anicraft-insert-blank-keyframe.svg new file mode 100644 index 00000000..8310bdd3 --- /dev/null +++ b/assets/icons/anicraft-insert-blank-keyframe.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-insert-frame.svg b/assets/icons/anicraft-insert-frame.svg new file mode 100644 index 00000000..cdb94a6c --- /dev/null +++ b/assets/icons/anicraft-insert-frame.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-insert-keyframe.svg b/assets/icons/anicraft-insert-keyframe.svg new file mode 100644 index 00000000..f7bf3e4c --- /dev/null +++ b/assets/icons/anicraft-insert-keyframe.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-layer.svg b/assets/icons/anicraft-layer.svg new file mode 100644 index 00000000..6a8eda2f --- /dev/null +++ b/assets/icons/anicraft-layer.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-paint-brush.svg b/assets/icons/anicraft-paint-brush.svg new file mode 100644 index 00000000..0a82f625 --- /dev/null +++ b/assets/icons/anicraft-paint-brush.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/anicraft-warp.svg b/assets/icons/anicraft-warp.svg new file mode 100644 index 00000000..a9fe693a --- /dev/null +++ b/assets/icons/anicraft-warp.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/icons/copy.svg b/assets/icons/copy.svg new file mode 100644 index 00000000..f62ce99c --- /dev/null +++ b/assets/icons/copy.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/ellipsis.svg b/assets/icons/ellipsis.svg new file mode 100644 index 00000000..68456c39 --- /dev/null +++ b/assets/icons/ellipsis.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/assets/icons/plus.svg b/assets/icons/plus.svg new file mode 100644 index 00000000..41f92bb9 --- /dev/null +++ b/assets/icons/plus.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/trash.svg b/assets/icons/trash.svg new file mode 100644 index 00000000..e8cb0edf --- /dev/null +++ b/assets/icons/trash.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs new file mode 100644 index 00000000..ec3f1978 --- /dev/null +++ b/crates/actions/src/as3/ir.rs @@ -0,0 +1,829 @@ +//! The script IR (ADR 0052): a small, typed form of statements and expressions that a +//! compiled script runs as, evaluated by [`super::run`]. It is data, not code: the player (and +//! the HTML canvas player, which reads the same IR as JSON) walks it with a fuel budget. +//! +//! Names are resolved when the script compiles: a function's own variables are numbered slots, +//! the timeline's variables (`var` at the top of a frame script, shared by every frame script +//! of that timeline, as ActionScript 3.0 timelines keep them per instance) are looked up by +//! name, and instances are name paths from a base (the timeline, the stage, or the event's +//! target). Calls to functions go by name to the timeline's functions, so a frame can call a +//! function another frame of the same timeline declares. + +use crate::{FrameRef, Property, Target}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::sync::Arc; + +/// A variable's type: what values written to it are coerced to (ECMA-262 §9, ActionScript 3.0's +/// `int` and `uint` as ToInt32 and ToUint32). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Ty { + /// Untyped (`*`, `Object`, or no annotation): keeps any value. + #[default] + Any, + Number, + Int, + Uint, + Boolean, + String, +} + +impl Ty { + /// The type an annotation names, when it is one scripts can hold. + pub fn from_name(s: &str) -> Option { + Some(match s { + "*" | "Object" => Ty::Any, + "Number" => Ty::Number, + "int" => Ty::Int, + "uint" => Ty::Uint, + "Boolean" => Ty::Boolean, + "String" => Ty::String, + _ => return None, + }) + } + + /// What a variable of this type holds before anything is written to it. + pub fn default_value(self) -> Value { + match self { + Ty::Any => Value::Undefined, + Ty::Number => Value::Num(f64::NAN), + Ty::Int | Ty::Uint => Value::Num(0.0), + Ty::Boolean => Value::Bool(false), + Ty::String => Value::Null, + } + } + + /// `v` as this type. + pub fn coerce(self, v: Value) -> Value { + match self { + Ty::Any => v, + Ty::Number => Value::Num(v.number()), + Ty::Int => Value::Num(f64::from(to_int32(v.number()))), + Ty::Uint => Value::Num(f64::from(to_uint32(v.number()))), + Ty::Boolean => Value::Bool(v.truthy()), + Ty::String => match v { + Value::Null | Value::Undefined => Value::Null, + Value::Str(_) => v, + other => Value::Str(other.text().into()), + }, + } + } +} + +/// ToInt32 (ECMA-262 §9.5). +pub fn to_int32(n: f64) -> i32 { + let u = to_uint32(n); + u as i32 +} + +/// ToUint32 (ECMA-262 §9.6). +pub fn to_uint32(n: f64) -> u32 { + if !n.is_finite() { + return 0; + } + let m = n.trunc().rem_euclid(4_294_967_296.0); + // In 0 .. 2^32 by construction. + if (0.0..4_294_967_296.0).contains(&m) { m as u32 } else { 0 } +} + +/// A value a script computes with: ActionScript's primitive values. +#[derive(Clone, Debug, Default)] +pub enum Value { + #[default] + Undefined, + Null, + Bool(bool), + Num(f64), + Str(Arc), +} + +impl PartialEq for Value { + /// The same value (NaN is NaN): what state comparisons need, not ActionScript's `==`. + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true, + (Value::Bool(a), Value::Bool(b)) => a == b, + (Value::Num(a), Value::Num(b)) => a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()), + (Value::Str(a), Value::Str(b)) => a == b, + _ => false, + } + } +} + +impl Value { + pub fn str(s: &str) -> Value { + Value::Str(s.into()) + } + + /// ToNumber (ECMA-262 §9.3). + pub fn number(&self) -> f64 { + match self { + Value::Num(n) => *n, + Value::Bool(b) => f64::from(u8::from(*b)), + Value::Null => 0.0, + Value::Undefined => f64::NAN, + Value::Str(s) => string_number(s), + } + } + + /// ToBoolean (§9.2). + pub fn truthy(&self) -> bool { + match self { + Value::Num(n) => *n != 0.0 && !n.is_nan(), + Value::Str(s) => !s.is_empty(), + Value::Bool(b) => *b, + Value::Null | Value::Undefined => false, + } + } + + /// ToString (§9.8). + pub fn text(&self) -> String { + match self { + Value::Num(n) => number_text(*n), + Value::Str(s) => s.to_string(), + Value::Bool(b) => b.to_string(), + Value::Null => "null".into(), + Value::Undefined => "undefined".into(), + } + } + + pub fn is_str(&self) -> bool { + matches!(self, Value::Str(_)) + } +} + +/// The JSON form: `"u"`, `"null"`, `{"b": true}`, `{"n": 1.5}`, `{"s": "text"}`, `"nan"`, +/// `{"inf": false}` (JSON has no NaN or infinities). +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum ValueRepr { + U, + Null, + B(bool), + N(f64), + S(String), + Nan, + /// `true`: negative. + Inf(bool), +} + +impl Serialize for Value { + fn serialize(&self, s: S) -> Result { + match self { + Value::Undefined => ValueRepr::U, + Value::Null => ValueRepr::Null, + Value::Bool(b) => ValueRepr::B(*b), + Value::Num(n) if n.is_nan() => ValueRepr::Nan, + Value::Num(n) if n.is_infinite() => ValueRepr::Inf(*n < 0.0), + Value::Num(n) => ValueRepr::N(*n), + Value::Str(t) => ValueRepr::S(t.to_string()), + } + .serialize(s) + } +} + +impl<'de> Deserialize<'de> for Value { + fn deserialize>(d: D) -> Result { + Ok(match ValueRepr::deserialize(d)? { + ValueRepr::U => Value::Undefined, + ValueRepr::Null => Value::Null, + ValueRepr::B(b) => Value::Bool(b), + ValueRepr::N(n) => Value::Num(n), + ValueRepr::S(t) => Value::Str(t.into()), + ValueRepr::Nan => Value::Num(f64::NAN), + ValueRepr::Inf(neg) => Value::Num(if neg { f64::NEG_INFINITY } else { f64::INFINITY }), + }) + } +} + +/// White space and line terminators as ECMAScript trims them from numbers in text. +fn js_space(c: char) -> bool { + matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}') +} + +/// A number written as text (StringToNumber, ECMA-262 §9.3.1 as browsers read it: decimal, +/// `Infinity`, and `0x`/`0o`/`0b` integers), or NaN. +pub fn string_number(s: &str) -> f64 { + let t = s.trim_matches(js_space); + if t.is_empty() { + return 0.0; + } + let radix = |p: &str, r: u32| -> f64 { + if p.is_empty() || !p.chars().all(|c| c.is_digit(r)) { + return f64::NAN; + } + p.chars().filter_map(|c| c.to_digit(r)).fold(0.0, |v, d| v * f64::from(r) + f64::from(d)) + }; + if let Some(p) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { + return radix(p, 16); + } + if let Some(p) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) { + return radix(p, 8); + } + if let Some(p) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) { + return radix(p, 2); + } + let (neg, body) = match t.as_bytes().first() { + Some(b'-') => (true, t.get(1..).unwrap_or("")), + Some(b'+') => (false, t.get(1..).unwrap_or("")), + _ => (false, t), + }; + if body == "Infinity" { + return if neg { f64::NEG_INFINITY } else { f64::INFINITY }; + } + // digits [. digits] [e[+-]digits], or . digits [e…] + let b = body.as_bytes(); + let mut i = 0; + let digits = |i: &mut usize| { + let from = *i; + while b.get(*i).is_some_and(u8::is_ascii_digit) { + *i += 1; + } + *i - from + }; + let int = digits(&mut i); + let mut frac = 0; + if b.get(i) == Some(&b'.') { + i += 1; + frac = digits(&mut i); + } + if int + frac == 0 { + return f64::NAN; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + if digits(&mut i) == 0 { + return f64::NAN; + } + } + if i != b.len() { + return f64::NAN; + } + let v: f64 = body.parse().unwrap_or(f64::NAN); + if neg { -v } else { v } +} + +/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without +/// a point, exponents outside 1e-6 … 1e21. +pub 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, + } +} + +/// Length in UTF-16 units, as ActionScript's `String.length` counts. +pub fn text_len(s: &str) -> usize { + s.encode_utf16().count() +} + +/// Where an instance path starts. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Base { + /// The script's timeline. + #[default] + This, + /// The stage (keyboard listeners live there). + Stage, + /// The event's `target`. + Target, + /// The event's `currentTarget`: the instance (or stage) listened to. + Current, +} + +impl Base { + pub fn is_this(&self) -> bool { + *self == Base::This + } +} + +/// An instance a script names: a base and a name path from it (`hero_mc.arm_mc`, `parent`, +/// `root.menu`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Place { + #[serde(default, skip_serializing_if = "Base::is_this")] + pub base: Base, + #[serde(default, skip_serializing_if = "Target::is_this")] + pub path: Target, +} + +impl Place { + pub fn this() -> Place { + Place::default() + } + pub fn named(path: impl Into) -> Place { + Place { base: Base::This, path: Target::new(path) } + } +} + +impl std::fmt::Display for Place { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let base = match self.base { + Base::This => "", + Base::Stage => "stage", + Base::Target => "e.target", + Base::Current => "e.currentTarget", + }; + match (base, self.path.is_this()) { + ("", _) => write!(f, "{}", self.path), + (b, true) => f.write_str(b), + (b, false) => write!(f, "{b}.{}", self.path), + } + } +} + +/// A property a script reads (of an instance or of the timeline). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Prop { + X, + Y, + Alpha, + Visible, + Rotation, + ScaleX, + ScaleY, + /// 1-based, as ActionScript counts frames. + CurrentFrame, + TotalFrames, + /// The label at or before the playhead, or `null`. + CurrentLabel, + /// The pointer in the instance's own space. + MouseX, + MouseY, + /// The instance name. + Name, + /// A text field's text, and its length in UTF-16 units (ADR 0066). Only as `field.text` and + /// `field.length`: a bare `text` is a variable. + Text, + Length, +} + +impl Prop { + pub fn from_name(s: &str) -> Option { + Some(match s { + "x" => Prop::X, + "y" => Prop::Y, + "alpha" => Prop::Alpha, + "visible" => Prop::Visible, + "rotation" => Prop::Rotation, + "scaleX" => Prop::ScaleX, + "scaleY" => Prop::ScaleY, + "currentFrame" => Prop::CurrentFrame, + "totalFrames" => Prop::TotalFrames, + "currentLabel" => Prop::CurrentLabel, + "mouseX" => Prop::MouseX, + "mouseY" => Prop::MouseY, + "name" => Prop::Name, + _ => return None, + }) + } + /// A property read or set as `instance.m`: those [`Prop::from_name`] knows, and a text + /// field's `text` and `length`. + pub fn from_member(s: &str) -> Option { + match s { + "text" => Some(Prop::Text), + "length" => Some(Prop::Length), + _ => Prop::from_name(s), + } + } + pub fn name(self) -> &'static str { + match self { + Prop::X => "x", + Prop::Y => "y", + Prop::Alpha => "alpha", + Prop::Visible => "visible", + Prop::Rotation => "rotation", + Prop::ScaleX => "scaleX", + Prop::ScaleY => "scaleY", + Prop::CurrentFrame => "currentFrame", + Prop::TotalFrames => "totalFrames", + Prop::CurrentLabel => "currentLabel", + Prop::MouseX => "mouseX", + Prop::MouseY => "mouseY", + Prop::Name => "name", + Prop::Text => "text", + Prop::Length => "length", + } + } + /// The instance property a script may also set. + pub fn settable(self) -> Option { + Some(match self { + Prop::X => Property::X, + Prop::Y => Property::Y, + Prop::Alpha => Property::Alpha, + Prop::Visible => Property::Visible, + Prop::Rotation => Property::Rotation, + Prop::ScaleX => Property::ScaleX, + Prop::ScaleY => Property::ScaleY, + _ => return None, + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnOp { + Neg, + Plus, + Not, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BinOp { + Add, + Sub, + Mul, + Div, + Mod, + Lt, + Gt, + Le, + Ge, + Eq, + Ne, + StrictEq, + StrictNe, +} + +impl BinOp { + pub fn from_token(s: &str) -> Option { + Some(match s { + "+" => BinOp::Add, + "-" => BinOp::Sub, + "*" => BinOp::Mul, + "/" => BinOp::Div, + "%" => BinOp::Mod, + "<" => BinOp::Lt, + ">" => BinOp::Gt, + "<=" => BinOp::Le, + ">=" => BinOp::Ge, + "==" => BinOp::Eq, + "!=" => BinOp::Ne, + "===" => BinOp::StrictEq, + "!==" => BinOp::StrictNe, + _ => return None, + }) + } +} + +/// `Math` functions scripts may call. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MathFn { + Min, + Max, + Abs, + Floor, + Ceil, + Round, + /// From the player's seeded generator: the same movie and events give the same numbers. + Random, +} + +impl MathFn { + pub fn from_name(s: &str) -> Option { + Some(match s { + "min" => MathFn::Min, + "max" => MathFn::Max, + "abs" => MathFn::Abs, + "floor" => MathFn::Floor, + "ceil" => MathFn::Ceil, + "round" => MathFn::Round, + "random" => MathFn::Random, + _ => return None, + }) + } + /// How many arguments it takes (`None`: any number). + pub fn arity(self) -> Option { + match self { + MathFn::Min | MathFn::Max => None, + MathFn::Random => Some(0), + MathFn::Abs | MathFn::Floor | MathFn::Ceil | MathFn::Round => Some(1), + } + } +} + +/// What an assignment writes to. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "k", rename_all = "snake_case")] +pub enum LValue { + /// A function's own variable (or parameter). + Local { i: u16 }, + /// A variable of the timeline. + Var { n: String }, + /// An instance property. + Prop { at: Place, p: Property }, + /// A text field's text (`field.text = …`, `field.appendText(…)` as `+=`). + Text { at: Place }, +} + +/// An expression. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "e", rename_all = "snake_case")] +pub enum Expr { + Lit { v: Value }, + Local { i: u16 }, + Var { n: String }, + Get { at: Place, p: Prop }, + /// The keyboard event's `keyCode`. + Key, + /// The event a listener handles, passed on to a function's event parameter. + Event, + Un { op: UnOp, x: Box }, + Bin { op: BinOp, a: Box, b: Box }, + /// `a && b`, `a || b` (the operand's value, as ECMAScript gives it). + And { a: Box, b: Box }, + Or { a: Box, b: Box }, + Cond { c: Box, a: Box, b: Box }, + Math { f: MathFn, args: Vec }, + /// A call to a function of the timeline, by name. + Call { f: String, args: Vec }, + /// Whether two names are the same instance (`e.currentTarget == btn_a`); `ne` negates. + Same { a: Place, b: Place, ne: bool }, + /// `to = v` or `to op= v`; its value is what was written. + Set { to: LValue, op: Option, v: Box }, + /// `++` / `--` (`d` is +1 or -1); `post`: the value before. + Step { to: LValue, d: i8, post: bool }, + /// `int(x)`, `Number(x)`, `String(x)`, `Boolean(x)`, `uint(x)`. + Cast { t: Ty, x: Box }, +} + +impl Expr { + pub fn lit(v: Value) -> Expr { + Expr::Lit { v } + } +} + +/// A timeline method. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Method { + Stop, + Play, + GotoAndPlay, + GotoAndStop, + NextFrame, + PrevFrame, + NextScene, + PrevScene, +} + +impl Method { + pub fn from_name(s: &str) -> Option { + Some(match s { + "stop" => Method::Stop, + "play" => Method::Play, + "gotoAndPlay" => Method::GotoAndPlay, + "gotoAndStop" => Method::GotoAndStop, + "nextFrame" => Method::NextFrame, + "prevFrame" => Method::PrevFrame, + "nextScene" => Method::NextScene, + "prevScene" => Method::PrevScene, + _ => return None, + }) + } + pub fn name(self) -> &'static str { + match self { + Method::Stop => "stop", + Method::Play => "play", + Method::GotoAndPlay => "gotoAndPlay", + Method::GotoAndStop => "gotoAndStop", + Method::NextFrame => "nextFrame", + Method::PrevFrame => "prevFrame", + Method::NextScene => "nextScene", + Method::PrevScene => "prevScene", + } + } + /// The action it is, at a frame (go-tos) and scene. + pub fn action(self, target: Target, frame: FrameRef, scene: Option) -> crate::Action { + use crate::Action as A; + match self { + Method::Stop => A::Stop { target }, + Method::Play => A::Play { target }, + Method::GotoAndPlay => A::GotoAndPlay { target, frame, scene }, + Method::GotoAndStop => A::GotoAndStop { target, frame, scene }, + Method::NextFrame => A::NextFrame { target }, + Method::PrevFrame => A::PrevFrame { target }, + Method::NextScene => A::NextScene, + Method::PrevScene => A::PrevScene, + } + } +} + +/// An event a listener waits for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ListenEvent { + Click, + Press, + Release, + Over, + Out, + /// `Event.ENTER_FRAME`: every frame, playing or not. + EnterFrame, + /// `KeyboardEvent.KEY_DOWN` / `KEY_UP` on the stage. + KeyDown, + KeyUp, +} + +impl ListenEvent { + pub fn key(self) -> &'static str { + match self { + ListenEvent::Click => "click", + ListenEvent::Press => "press", + ListenEvent::Release => "release", + ListenEvent::Over => "over", + ListenEvent::Out => "out", + ListenEvent::EnterFrame => "enter_frame", + ListenEvent::KeyDown => "key_down", + ListenEvent::KeyUp => "key_up", + } + } + /// The pointer event it is, for mouse listeners. + pub fn mouse(self) -> Option { + use crate::ButtonEvent as B; + Some(match self { + ListenEvent::Click => B::Click, + ListenEvent::Press => B::Press, + ListenEvent::Release => B::Release, + ListenEvent::Over => B::Over, + ListenEvent::Out => B::Out, + _ => return None, + }) + } + pub fn from_mouse(b: crate::ButtonEvent) -> ListenEvent { + use crate::ButtonEvent as B; + match b { + B::Click => ListenEvent::Click, + B::Press => ListenEvent::Press, + B::Release => ListenEvent::Release, + B::Over => ListenEvent::Over, + B::Out => ListenEvent::Out, + } + } + pub fn is_key(self) -> bool { + matches!(self, ListenEvent::KeyDown | ListenEvent::KeyUp) + } +} + +/// The function a listener runs. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FuncRef { + /// A function of the timeline, by name. + Named(String), + /// A function written in place: the index in the enclosing code's `inner` list. + Inline(u16), +} + +/// A statement, with the line it starts on (for messages). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Stmt { + pub l: u32, + #[serde(flatten)] + pub s: S, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "s", rename_all = "snake_case")] +pub enum S { + /// An expression for its effect. + Do { x: Expr }, + If { c: Expr, a: Vec, b: Vec }, + /// `while (c)`, `for (; c; next)` (`first`: the condition is tested before the body) and + /// `do … while (c)`. + Loop { + c: Option, + body: Vec, + next: Option, + first: bool, + }, + Break, + Continue, + Return { v: Option }, + /// A timeline method on an instance; `args` are the frame and the scene, when it takes them. + Act { at: Place, m: Method, args: Vec }, + Trace { args: Vec }, + /// `addEventListener` (`add`) or `removeEventListener`. + Listen { at: Place, ev: ListenEvent, f: FuncRef, add: bool }, +} + +/// A parameter. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Param { + pub t: Ty, + /// The value when a call leaves it out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub d: Option, + /// It is the event (typed `…Event`): its fields read the event the listener handles. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub ev: bool, +} + +/// A function: its parameters, its own variables (parameters first, each slot's type), what it +/// returns and its body. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Function { + pub name: String, + pub line: u32, + pub params: Vec, + pub locals: Vec, + /// `None`: `void`, or no result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ret: Option, + pub body: Vec, + /// Functions written in place inside it (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, +} + +impl Function { + /// Whether the function's first parameter takes an event (it can be a listener). + pub fn takes_event(&self) -> bool { + let required = self.params.iter().filter(|p| p.d.is_none()).count(); + required <= 1 && self.params.first().is_some_and(|p| p.ev || p.t == Ty::Any) + } +} + +/// The keyboard key codes ActionScript names (`Keyboard.LEFT`, …): the public `flash.ui.Keyboard` +/// constants scripts compare `e.keyCode` with. +pub fn key_code(name: &str) -> Option { + let one = |s: &str| { + let mut c = s.chars(); + match (c.next(), c.next()) { + (Some(ch), None) => Some(ch), + _ => None, + } + }; + if let Some(c) = one(name).filter(char::is_ascii_uppercase) { + return Some(u32::from(c)); + } + if let Some(d) = name.strip_prefix("NUMBER_").and_then(one).and_then(|c| c.to_digit(10)) { + return Some(48 + d); + } + if let Some(d) = name.strip_prefix("NUMPAD_").and_then(one).and_then(|c| c.to_digit(10)) { + return Some(96 + d); + } + if let Some(n) = name.strip_prefix('F').and_then(|n| n.parse::().ok()).filter(|n| (1..=15).contains(n)) { + return Some(111 + n); + } + Some(match name { + "BACKSPACE" => 8, + "TAB" => 9, + "ENTER" => 13, + "SHIFT" => 16, + "CONTROL" => 17, + "ALTERNATE" => 18, + "CAPS_LOCK" => 20, + "ESCAPE" => 27, + "SPACE" => 32, + "PAGE_UP" => 33, + "PAGE_DOWN" => 34, + "END" => 35, + "HOME" => 36, + "LEFT" => 37, + "UP" => 38, + "RIGHT" => 39, + "DOWN" => 40, + "INSERT" => 45, + "DELETE" => 46, + "NUMPAD_MULTIPLY" => 106, + "NUMPAD_ADD" => 107, + "NUMPAD_ENTER" => 108, + "NUMPAD_SUBTRACT" => 109, + "NUMPAD_DECIMAL" => 110, + "NUMPAD_DIVIDE" => 111, + "SEMICOLON" => 186, + "EQUAL" => 187, + "COMMA" => 188, + "MINUS" => 189, + "PERIOD" => 190, + "SLASH" => 191, + "BACKQUOTE" => 192, + "LEFTBRACKET" => 219, + "BACKSLASH" => 220, + "RIGHTBRACKET" => 221, + "QUOTE" => 222, + _ => return None, + }) +} diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs index 6597f57a..385b682c 100644 --- a/crates/actions/src/as3/lower.rs +++ b/crates/actions/src/as3/lower.rs @@ -1,116 +1,71 @@ -//! 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. +//! Lowering: the syntax tree to the script IR ([`super::ir`]). It accepts what the IR can say +//! exactly and reports everything else where it is, so a script either compiles whole or +//! doesn't run at all. Names resolve here: a function's own variables become numbered slots, +//! the timeline's variables and functions are named (those another frame declares are listed +//! as [`Free`] names, which the timeline must have for the script to run), and instances become +//! name paths from a base. -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 super::ir::{self, Base, BinOp, Expr as X, FuncRef, Function, LValue, ListenEvent, MathFn, Method, Param as IrParam, Place, Prop, S as IS, Stmt as IStmt, Ty, UnOp, Value}; +use super::parse::{E, Expr, Func, S, Stmt, VarDecl}; +use super::{Compiled, Free, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem}; +use crate::{MAX_FRAME, MAX_LABEL_CHARS, Target, valid_instance_name}; +use std::collections::{BTreeMap, BTreeSet}; 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"]; +const BUILTINS: [&str; 12] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener", "getChildByName"]; /// 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"]; +/// Names that are classes, not values. +const CLASSES: [&str; 6] = ["Math", "Keyboard", "MouseEvent", "Event", "KeyboardEvent", "ExternalInterface"]; +/// Names that are always the path words. +const PATH_WORDS: [&str; 3] = ["root", "parent", "stage"]; -/// 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 type annotation as a script variable's type, or why it can't be one. `…Event` types are +/// events (`Ok(None)`). +fn var_type(ty: &Option<(String, Pos)>) -> Result, (Pos, String)> { + match ty { + None => Ok(Some(Ty::Any)), + Some((t, _)) if t.ends_with("Event") => Ok(None), + Some((t, p)) => Ty::from_name(t).map(Some).ok_or_else(|| (*p, format!("variables of type `{t}` aren't supported yet (Number, int, uint, Boolean, String and untyped ones are)"))), } } -/// 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)>, - /// 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). +/// What lowering a function's (or the script's top level's) code knows. +struct Unit { + /// The function's own variables: slot and type. + locals: BTreeMap, + types: Vec, + /// Its parameters that are the event. + events: BTreeSet, in_function: bool, - /// The parameters of the function being lowered (they can't be read). - params: Vec, - /// The script's functions being lowered, innermost last (to refuse recursion). - stack: Vec, + /// Loops it is inside (for `break` and `continue`). + loops: usize, + /// Functions written in place inside it. + inner: Vec>, +} + +impl Unit { + fn top() -> Unit { + Unit { locals: BTreeMap::new(), types: Vec::new(), events: BTreeSet::new(), in_function: false, loops: 0, inner: Vec::new() } + } } struct Lower<'a> { funcs: BTreeMap<&'a str, &'a Func>, + /// The script's top-level variables (the timeline's). + vars: BTreeMap, problems: Vec, notes: Vec, + free: Vec, listeners: usize, - /// Statements lowered so far, counting each inlined copy (calls can fan out). - work: usize, + /// Functions being lowered (inline listeners nest). + depth: 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; +type O = Option; impl<'a> Lower<'a> { fn problem(&mut self, pos: Pos, msg: impl Into) { @@ -125,444 +80,908 @@ impl<'a> Lower<'a> { } } - fn stmts(&mut self, list: &'a [Stmt], cx: &Cx, out: &mut Vec) -> Returned { - for s in list { - if self.stmt(s, cx, out) { - return true; - } + fn free(&mut self, name: &str, pos: Pos, call: bool) { + if !self.free.iter().any(|f| f.name == name && f.call == call) && self.free.len() < 1024 { + self.free.push(Free { name: name.to_string(), line: pos.line, column: pos.column, call }); } - false } - fn stmt(&mut self, s: &'a Stmt, cx: &Cx, out: &mut Vec) -> 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; + // ----- statements ---------------------------------------------------------------------- + + fn stmts(&mut self, list: &'a [Stmt], u: &mut Unit, out: &mut Vec) { + for s in list { + self.stmt(s, u, out); } + } + + fn body(&mut self, list: &'a [Stmt], u: &mut Unit) -> Vec { + let mut out = Vec::new(); + self.stmts(list, u, &mut out); + out + } + + fn stmt(&mut self, s: &'a Stmt, u: &mut Unit, out: &mut Vec) { + let l = s.pos.line; + let push = |out: &mut Vec, s: IS| out.push(IStmt { l, s }); match &s.kind { S::Empty | S::Import => {} // Declared functions run where they are called or listened for. S::Function(_) => { - if cx.in_function { + if u.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::Block(b) => self.stmts(b, u, out), + S::Var(_, list) => self.var_stmt(list, u, out, l), + S::If(c, a, b) => { + let Some(c) = self.expr(c, u) else { return }; + let a = self.body(a, u); + let b = self.body(b, u); + push(out, IS::If { c, a, b }); + } + S::For(init, c, next, body) => { + if let Some(init) = init { + self.stmt(init, u, out); + } + let c = c.as_ref().and_then(|c| self.expr(c, u)); + let next = next.as_ref().and_then(|n| self.expr(n, u)); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next, first: true }); + } + S::While(c, body) | S::DoWhile(body, c) => { + let first = matches!(s.kind, S::While(..)); + let c = self.expr(c, u); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next: None, first }); + } + S::Break | S::Continue => { + if u.loops == 0 { + let w = if matches!(s.kind, S::Break) { "break" } else { "continue" }; + return self.problem(s.pos, format!("`{w}` is only for loops here")); + } + push(out, if matches!(s.kind, S::Break) { IS::Break } else { IS::Continue }); + } S::Other(w, _) => { let what = match *w { - "for" | "while" | "do" => format!("`{w}` loops aren't supported yet"), + "for each" | "for in" => format!("`{w}` loops aren't supported yet (`for`, `while` and `do` are)"), + "labelled break" => "labels on `break` and `continue` aren't supported".to_string(), _ => 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::Return(e) => { + let v = match e { + Some(e) => match self.expr(e, u) { + Some(v) => Some(v), + None => return, + }, + None => None, + }; + push(out, IS::Return { v }); } - S::Expr(e) => self.expr_stmt(e, cx, out), + S::Expr(e) => self.expr_stmt(e, u, out, l), } - false } - fn expr_stmt(&mut self, e: &'a Expr, cx: &Cx, out: &mut Vec) { + fn var_stmt(&mut self, list: &'a [VarDecl], u: &mut Unit, out: &mut Vec, l: u32) { + for d in list { + let Some(init) = &d.init else { continue }; + let to = if u.in_function { + match u.locals.get(&d.name) { + Some((i, _)) => LValue::Local { i: *i }, + None => continue, + } + } else { + LValue::Var { n: d.name.clone() } + }; + let Some(v) = self.expr(init, u) else { continue }; + out.push(IStmt { l, s: IS::Do { x: X::Set { to, op: None, v: Box::new(v) } } }); + } + } + + fn expr_stmt(&mut self, e: &'a Expr, u: &mut Unit, out: &mut Vec, l: u32) { 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::Call(callee, args) => { + if let Some(s) = self.call_stmt(e.pos, callee, args, u) { + out.push(IStmt { l, s }); + } + } E::Comma(list) => { for x in list { - self.expr_stmt(x, cx, out); + self.expr_stmt(x, u, out, l); } } // 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"), + E::Assign(_, lhs, _) if matches!(&lhs.kind, E::Member(_, p) if p == "buttonMode" || p == "useHandCursor") => { + let E::Member(_, p) = &lhs.kind else { return }; + self.note(e.pos, format!("`{p}` is ignored: the pointer is a hand over everything clickable here")); + } + _ => { + if let Some(x) = self.expr(e, u) { + out.push(IStmt { l, s: IS::Do { x } }); + } + } } } - fn call(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + /// A call as a statement: timeline methods, `trace`, listeners, and any call with a value. + fn call_stmt(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { match &callee.kind { - E::Name(n) => { + E::Name(n) if !u.locals.contains_key(n) => { let n = n.as_str(); - if let Some(f) = self.funcs.get(n).copied() { - return self.inline(pos, f, args, cx, out); + if self.funcs.contains_key(n) { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); } 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)")), + "trace" => { + let args = self.args(args, u)?; + Some(IS::Trace { args }) + } + "addEventListener" | "removeEventListener" => self.listen(pos, Place::this(), args, n == "addEventListener", u), + n if Method::from_name(n).is_some() => self.method(pos, Place::this(), n, args, u), + n if OUTSIDE.contains(&n) => { + self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")); + None + } + n if CASTS.contains(&n) => { + self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")); + None + } + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } 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")); + self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + return None; } - 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); + if matches!(&obj.kind, E::Name(o) if o == "Math") { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); + } + // `field.appendText(v)` is `field.text += v` (ADR 0066). + if m == "appendText" { + let [arg] = args else { + self.problem(pos, "`appendText` takes one argument, the text to add"); + return None; + }; + let (at, v) = (self.field_place(obj, u), self.expr(arg, u)); + return Some(IS::Do { x: X::Set { to: LValue::Text { at: at? }, op: Some(BinOp::Add), v: Box::new(v?) } }); + } + if Method::from_name(m).is_none() && m != "addEventListener" && m != "removeEventListener" { + self.problem(pos, format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, `addEventListener` and `removeEventListener` are)")); + return None; + } + let at = self.place(obj, u)?; + match m { + "addEventListener" | "removeEventListener" => self.listen(pos, at, args, m == "addEventListener", u), + _ => self.method(pos, at, m, args, u), } - 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"), + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } - /// 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) { - 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). + fn args(&mut self, args: &'a [Expr], u: &mut Unit) -> O> { + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; 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"); + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, } } - 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); + ok.then_some(out) } - fn trace(&mut self, pos: Pos, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - 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), - } + /// A timeline method on the instance at `at`. + fn method(&mut self, pos: Pos, at: Place, m: &str, args: &'a [Expr], u: &mut Unit) -> O { + let method = Method::from_name(m)?; + let takes = matches!(method, Method::GotoAndPlay | Method::GotoAndStop); + if !takes && !args.is_empty() { + self.problem(pos, format!("`{m}()` takes no arguments")); + return None; } - 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")); + if matches!(method, Method::NextScene | Method::PrevScene) && (!at.path.is_this() || !at.base.is_this()) { + // 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). + self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + return None; } - out.push(ScriptOp::Action(Action::Trace { message })); - } - - /// A timeline method on the instance at `path`. - fn method(&mut self, pos: Pos, path: Vec, m: &str, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - 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; + if takes && (args.is_empty() || args.len() > 2) { + self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); + return None; + } + // Frames and scenes written out are checked now; computed ones when they run. + if let Some(f) = args.first() { + match &f.kind { + E::Num(n) if !(n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(n)) => { + self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)); + return None; } - // 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")); + E::Str(s) if !label_ok(s) => { + self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")); + return None; } - if m == "nextScene" { Action::NextScene } else { Action::PrevScene } + E::Bool(_) | E::Null => { + self.problem(f.pos, "the frame is a number or a label"); + return None; + } + _ => {} } - "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, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - 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)) + if let Some(s) = args.get(1) + && (matches!(&s.kind, E::Num(_) | E::Bool(_)) || matches!(&s.kind, E::Str(t) if !label_ok(t))) { - return self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + self.problem(s.pos, "the scene is its name, as a string"); + return None; + } + let args = self.args(args, u)?; + Some(IS::Act { at, m: method, args }) + } + + /// `at.addEventListener(event, function)` (or `removeEventListener`). + fn listen(&mut self, pos: Pos, at: Place, args: &'a [Expr], add: bool, u: &mut Unit) -> O { + let verb = if add { "addEventListener" } else { "removeEventListener" }; + let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= if add { 5 } else { 3 }) else { + self.problem(pos, format!("`{verb}` takes an event and a function")); + return None; + }; + let event = self.event(ev)?; + if let Some(c) = args.get(2) + && !matches!(c.kind, E::Bool(false) | E::Null) + { + self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + return None; } 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"); + if !matches!(extra.kind, E::Num(_) | E::Bool(_) | E::Null) { + self.problem(extra.pos, "listener priority and weak references are values"); + return None; } } - 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"), + if event.is_key() && at.base != Base::Stage { + self.note(pos, "keys go to the stage here: listen with `stage.addEventListener(KeyboardEvent.KEY_DOWN, …)`; this listener is ignored"); + return None; + } + if at.base == Base::Stage && event.mouse().is_some() { + self.problem(pos, "mouse listeners on the stage aren't supported yet (on buttons and movie clips they are)"); + return None; + } + let f = match &handler.kind { + E::Name(n) if !u.locals.contains_key(n) => { + match self.funcs.get(n.as_str()).copied() { + Some(f) => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + } + None if CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) => { + self.problem(handler.pos, format!("`{n}` isn't a function declared in a frame script")); + return None; + } + None => self.free(n, handler.pos, true), + } + FuncRef::Named(n.clone()) + } + E::Function(f) if add => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + let name = format!("function at line {}, column {}", f.pos.line, f.pos.column); + let func = self.function(f, name)?; + if u.inner.len() >= usize::from(u16::MAX) { + return None; + } + u.inner.push(func); + FuncRef::Inline((u.inner.len() - 1) as u16) + } + E::Function(_) => { + self.problem(handler.pos, "a function written in place can't be removed; give it a name and listen with that"); + return None; + } + _ => { + self.problem(handler.pos, "the listener is a function declared in a frame script, or written in place"); + return None; + } }; - // 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 add { + if self.listeners >= MAX_LISTENERS { + self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); + return None; + } + self.listeners += 1; } - 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 = 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) })); + Some(IS::Listen { at, ev: event, f, add }) } - /// The mouse event an `addEventListener` names. - fn event(&mut self, e: &Expr) -> Option { - 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")) => { + /// The event an `addEventListener` names. + fn event(&mut self, e: &Expr) -> O { + let (name, key) = match &e.kind { + E::Member(o, k) if matches!(&o.kind, E::Name(c) if 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 { "" }) + let ev = match (class, k.as_str()) { + ("MouseEvent", "CLICK") => Some(ListenEvent::Click), + ("MouseEvent", "MOUSE_DOWN") => Some(ListenEvent::Press), + ("MouseEvent", "MOUSE_UP") => Some(ListenEvent::Release), + ("MouseEvent", "ROLL_OVER" | "MOUSE_OVER") => Some(ListenEvent::Over), + ("MouseEvent", "ROLL_OUT" | "MOUSE_OUT") => Some(ListenEvent::Out), + ("Event", "ENTER_FRAME") => Some(ListenEvent::EnterFrame), + ("KeyboardEvent", "KEY_DOWN") => Some(ListenEvent::KeyDown), + ("KeyboardEvent", "KEY_UP") => Some(ListenEvent::KeyUp), + _ => None, + }; + (format!("{class}.{k}"), ev) } - 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", - _ => "", - }), + E::Str(s) => ( + format!("\"{s}\""), + match s.as_str() { + "click" => Some(ListenEvent::Click), + "mouseDown" => Some(ListenEvent::Press), + "mouseUp" => Some(ListenEvent::Release), + "rollOver" | "mouseOver" => Some(ListenEvent::Over), + "rollOut" | "mouseOut" => Some(ListenEvent::Out), + "enterFrame" => Some(ListenEvent::EnterFrame), + "keyDown" => Some(ListenEvent::KeyDown), + "keyUp" => Some(ListenEvent::KeyUp), + _ => None, + }, + ), _ => { 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) { - 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"); + if key.is_none() { + self.problem(e.pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT, Event.ENTER_FRAME and KeyboardEvent.KEY_DOWN and KEY_UP are)")); } - out.push(ScriptOp::Action(Action::SetProperty { target, property, value })); + key } - /// 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> { - 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"); + // ----- functions ----------------------------------------------------------------------- + + /// A function's IR: parameters, its own variables (hoisted, as ActionScript does) and body. + fn function(&mut self, f: &'a Func, name: String) -> O> { + if self.depth >= 8 { + self.problem(f.pos, "listeners written in place nest more than 8 deep"); + return None; + } + let before = self.problems.len(); + let mut u = Unit { in_function: true, ..Unit::top() }; + let mut params = Vec::new(); + for (i, p) in f.params.iter().enumerate() { + if p.rest { + self.problem(p.pos, "rest parameters (`...args`) aren't supported"); + continue; + } + let (t, ev) = match var_type(&p.ty) { + Ok(Some(t)) => (t, false), + Ok(None) => (Ty::Any, true), + Err((pos, m)) => { + self.problem(pos, m.replace("variables of type", "parameters of type")); + continue; + } + }; + // An untyped first parameter can be the event, too (`function f(e)`). + if ev || (i == 0 && p.ty.is_none()) { + u.events.insert(p.name.clone()); + } + let d = match &p.default { + None => None, + Some(e) => match literal(e) { + Some(v) => Some(t.coerce(v)), + None => { + self.problem(e.pos, "a parameter's default is a value written out (a number, a string, true, false or null)"); + continue; + } + }, + }; + if u.locals.insert(p.name.clone(), (u.types.len() as u16, t)).is_some() { + self.problem(p.pos, format!("the parameter `{}` is named twice", p.name)); + } + u.types.push(t); + params.push(IrParam { t, d, ev }); + } + // Every `var` in the body is the function's (hoisted). + let mut decls = Vec::new(); + collect_vars(&f.body, &mut decls); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + self.problem(d.pos, "variables can't hold events; read `e.keyCode`, `e.target` or `e.currentTarget` from the parameter"); + continue; + } + Err((pos, m)) => { + self.problem(pos, m); + continue; + } + }; + match u.locals.get(&d.name) { + Some((_, old)) if *old != t && d.ty.is_some() => self.problem(d.pos, format!("`{}` is declared again with another type", d.name)), + Some(_) => {} + None => { + if u.types.len() >= 1024 { + self.problem(d.pos, "a function has at most 1024 variables"); + continue; + } + u.locals.insert(d.name.clone(), (u.types.len() as u16, t)); + u.types.push(t); + } + } + } + let ret = match &f.ret { + None => Some(Ty::Any), + Some((t, _)) if t == "void" => None, + Some((t, p)) => match Ty::from_name(t) { + Some(t) => Some(t), + None => { + self.problem(*p, format!("functions returning `{t}` aren't supported yet (Number, int, uint, Boolean, String, void and untyped ones are)")); + None + } + }, + }; + self.depth += 1; + let body = self.body(&f.body, &mut u); + self.depth -= 1; + if self.problems.len() > before { + return None; + } + Some(Arc::new(Function { name, line: f.pos.line, params, locals: u.types, ret, body, inner: u.inner })) + } + + // ----- names and places ---------------------------------------------------------------- + + /// An instance a script names, from the timeline or the event; `None` after reporting why + /// it isn't one. + fn place(&mut self, e: &Expr, u: &Unit) -> O { + let mut at = match &e.kind { + E::This => Place::this(), + E::Name(n) if u.locals.contains_key(n) && !u.events.contains(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); return None; } - E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => { + E::Name(n) if u.events.contains(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")); + E::Name(n) if n == "stage" => Place { base: Base::Stage, path: Target::this() }, + E::Name(n) if n == "root" || n == "parent" => Place::named(n.clone()), + E::Name(n) if self.vars.contains_key(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); 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"); + E::Name(n) if CLASSES.contains(&n.as_str()) => { + self.problem(e.pos, format!("`{n}` is a class, not an instance")); return None; } + E::Name(n) => Place::named(n.clone()), + E::Member(o, m) if (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)) => Place { base: if m == "target" { Base::Target } else { Base::Current }, path: Target::this() }, E::Member(o, m) => { - let mut p = self.target(o, cx)?; - p.push(m.clone()); + let mut p = self.place(o, u)?; + if p.base == Base::Stage { + self.problem(e.pos, format!("`stage.{m}` isn't supported")); + return None; + } + let path = if p.path.is_this() { m.clone() } else { format!("{}.{m}", p.path.0.trim()) }; + p.path = Target::new(path); 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), + 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.place(a, u)), + E::Binary("as", x, _) => return self.place(x, u), _ => { 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); + let segs: Vec = at.path.0.trim().split('.').filter(|s| !s.is_empty()).map(str::to_string).collect(); + if let Some(i) = segs.iter().rposition(|s| s == "root") { + at = Place { base: Base::This, path: Target::new(segs.get(i..).unwrap_or_default().join(".")) }; } - Some(path) - } - - /// The IR target for a path, checked. - fn path(&mut self, pos: Pos, path: &[String]) -> Option { - 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 `$`)")); + for s in at.path.0.split('.').filter(|s| !s.is_empty()) { + if !matches!(s, "root" | "parent" | "this") && !valid_instance_name(s) { + self.problem(e.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); + if let Err(m) = at.path.segments() { + self.problem(e.pos, m); + return None; + } + Some(at) + } + + /// The text field a script names (`score_txt`, `panel.name_txt`): an instance, not the + /// stage or a timeline (`this` is one only if it is a field, which a frame script's isn't). + fn field_place(&mut self, e: &Expr, u: &Unit) -> O { + let at = self.place(e, u)?; + if at.base == Base::Stage || (at.base == Base::This && at.path.is_this()) { + self.problem(e.pos, "this isn't a text field; name the field by its instance name, as in `score_txt.text`"); + return None; + } + Some(at) + } + + /// Whether an expression names an instance rather than a value (for `==` between instances). + fn is_instance(&self, e: &Expr, u: &Unit) -> bool { + match &e.kind { + E::This => true, + E::Name(n) => n == "stage" || n == "root" || n == "parent", + E::Member(o, m) => (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)), + E::Call(f, args) => matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1, + E::Binary("as", ..) => true, + _ => false, + } + } + + /// Where an assignment writes. + fn lvalue(&mut self, e: &'a Expr, u: &mut Unit) -> O { + match &e.kind { + E::Name(n) => { + if let Some((i, _)) = u.locals.get(n) { + return Some(LValue::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(LValue::Var { n: n.clone() }); + } + if let Some(p) = Prop::from_name(n) { + return match p.settable() { + Some(p) => Some(LValue::Prop { at: Place::this(), p }), + None => { + self.problem(e.pos, format!("`{n}` can only be read")); + None + } + }; + } + if self.funcs.contains_key(n.as_str()) || PATH_WORDS.contains(&n.as_str()) || CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) || matches!(n.as_str(), "undefined" | "NaN" | "Infinity") { + self.problem(e.pos, format!("`{n}` can't be assigned to")); + return None; + } + self.free(n, e.pos, false); + Some(LValue::Var { n: n.clone() }) + } + E::Member(o, m) if m == "text" => Some(LValue::Text { at: self.field_place(o, u)? }), + E::Member(o, m) => { + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY and a text field's text are)")); + return None; + }; + let Some(p) = p.settable() else { + self.problem(e.pos, format!("`{m}` can only be read")); + return None; + }; + let at = self.place(o, u)?; + if at.base == Base::Stage { + self.problem(e.pos, "the stage's properties can't be set here"); + return None; + } + Some(LValue::Prop { at, p }) + } + _ => { + self.problem(e.pos, "only variables and instance properties can be assigned to"); None } } } - /// A value computed from literals (`"Score: " + 10`, `-5`, `0.5`). - fn constant(&self, e: &Expr, cx: &Cx) -> Result { - 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")); + // ----- expressions --------------------------------------------------------------------- + + fn expr(&mut self, e: &'a Expr, u: &mut Unit) -> O { + Some(match &e.kind { + E::Num(n) => X::lit(Value::Num(*n)), + E::Str(s) => { + if ir::text_len(s) > super::run::MAX_TEXT { + self.problem(e.pos, "this text is too long"); + return None; + } + X::lit(Value::str(s)) + } + E::Bool(b) => X::lit(Value::Bool(*b)), + E::Null => X::lit(Value::Null), + E::Name(n) => return self.name(e.pos, n, u), + E::Member(o, m) => return self.member(e, o, m, u), + E::Unary(op, x) => match *op { + "-" | "+" | "!" => { + let x = self.expr(x, u)?; + let op = match *op { + "-" => UnOp::Neg, + "+" => UnOp::Plus, + _ => UnOp::Not, + }; + X::Un { op, x: Box::new(x) } + } + "++" | "--" => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: false }, + other => { + self.problem(e.pos, format!("`{other}` isn't supported yet")); + return None; + } + }, + E::Postfix(op, x) => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: true }, + E::Binary(op, a, b) => match *op { + "&&" | "||" => { + let (a, b) = (self.expr(a, u), self.expr(b, u)); + let (a, b) = (Box::new(a?), Box::new(b?)); + if *op == "&&" { X::And { a, b } } else { X::Or { a, b } } + } + "==" | "!=" | "===" | "!==" if self.is_instance(a, u) || self.is_instance(b, u) => { + let (pa, pb) = (self.place(a, u), self.place(b, u)); + X::Same { a: pa?, b: pb?, ne: op.starts_with('!') } + } + op => { + let Some(bop) = BinOp::from_token(op) else { + let what = match op { + "as" | "is" | "instanceof" | "in" => format!("`{op}` isn't supported here"), + _ => format!("the `{op}` operator isn't supported yet"), + }; + self.problem(e.pos, what); + return None; + }; + let (a, b) = (self.expr(a, u), self.expr(b, u)); + X::Bin { op: bop, a: Box::new(a?), b: Box::new(b?) } + } + }, + E::Assign(op, lhs, rhs) => { + let op = match *op { + "=" => None, + o => match BinOp::from_token(o.trim_end_matches('=')) { + Some(b @ (BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod)) => Some(b), + _ => { + self.problem(e.pos, format!("`{o}` isn't supported yet (`=`, `+=`, `-=`, `*=`, `/=` and `%=` are)")); + return None; } - 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)); + let (to, v) = (self.lvalue(lhs, u), self.expr(rhs, u)); + X::Set { to: to?, op, v: Box::new(v?) } + } + E::Cond(c, a, b) => { + let (c, a, b) = (self.expr(c, u), self.expr(a, u), self.expr(b, u)); + X::Cond { c: Box::new(c?), a: Box::new(a?), b: Box::new(b?) } + } + E::Call(callee, args) => return self.call_expr(e.pos, callee, args, u), + E::Comma(_) => { + self.problem(e.pos, "`,` between expressions isn't supported here"); + return None; + } + E::Function(_) => { + self.problem(e.pos, "a function written in place is only supported as a listener"); + return None; + } + E::This => { + self.problem(e.pos, "`this` is the timeline; read a property of it, as in `this.currentFrame`"); + return None; + } + E::Array(_) => { + self.problem(e.pos, "arrays aren't supported yet"); + return None; + } + E::Object(_) => { + self.problem(e.pos, "objects (`{…}`) aren't supported yet"); + return None; + } + E::New(..) => { + self.problem(e.pos, "`new` isn't supported yet"); + return None; + } + E::Index(..) => { + self.problem(e.pos, "`[…]` access isn't supported yet"); + return None; } - _ => return Err(Problem::at(e.pos, "only values written out (numbers, strings, true, false) and `+` of them are supported here")), }) } + + /// A bare name as a value. + fn name(&mut self, pos: Pos, n: &str, u: &mut Unit) -> O { + if let Some((i, _)) = u.locals.get(n) { + return Some(X::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(X::Var { n: n.to_string() }); + } + match n { + "undefined" => return Some(X::lit(Value::Undefined)), + "NaN" => return Some(X::lit(Value::Num(f64::NAN))), + "Infinity" => return Some(X::lit(Value::Num(f64::INFINITY))), + _ => {} + } + if let Some(p) = Prop::from_name(n) { + return Some(X::Get { at: Place::this(), p }); + } + if self.funcs.contains_key(n) || BUILTINS.contains(&n) { + self.problem(pos, format!("`{n}` is a function; call it, as in `{n}()`")); + return None; + } + if PATH_WORDS.contains(&n) || CLASSES.contains(&n) || CASTS.contains(&n) { + self.problem(pos, format!("`{n}` isn't a value; read one of its properties")); + return None; + } + self.free(n, pos, false); + Some(X::Var { n: n.to_string() }) + } + + /// `o.m` as a value: constants, the event's key code, or a property of an instance. + fn member(&mut self, e: &'a Expr, o: &'a Expr, m: &str, u: &mut Unit) -> O { + if let E::Name(c) = &o.kind + && (!u.locals.contains_key(c) || u.events.contains(c)) + && !self.vars.contains_key(c) + { + match c.as_str() { + "Math" => { + return match m { + "PI" => Some(X::lit(Value::Num(std::f64::consts::PI))), + "E" => Some(X::lit(Value::Num(std::f64::consts::E))), + _ => { + self.problem(e.pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round, random and PI are)")); + None + } + }; + } + "Keyboard" => { + return match ir::key_code(m) { + Some(k) => Some(X::lit(Value::Num(f64::from(k)))), + None => { + self.problem(e.pos, format!("`Keyboard.{m}` isn't a key AniCraft knows")); + None + } + }; + } + ev if u.events.contains(ev) => { + return match m { + "keyCode" => Some(X::Key), + "currentTarget" | "target" => { + self.problem(e.pos, format!("`{ev}.{m}` is an instance; read one of its properties, as in `{ev}.{m}.name`")); + None + } + _ => { + self.problem(e.pos, format!("reading the event's `{m}` isn't supported yet (keyCode, target and currentTarget are)")); + None + } + }; + } + _ => {} + } + } + if let E::Name(n) = &o.kind + && n == "stage" + && !matches!(m, "mouseX" | "mouseY") + { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + if let E::Name(n) = &o.kind + && ((u.locals.contains_key(n) && !u.events.contains(n)) || self.vars.contains_key(n)) + { + self.problem(e.pos, format!("reading `{m}` of a value isn't supported yet")); + return None; + } + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY, name, and a text field's text and length are)")); + return None; + }; + let at = if matches!(p, Prop::Text | Prop::Length) { self.field_place(o, u)? } else { self.place(o, u)? }; + if at.base == Base::Stage && !matches!(p, Prop::MouseX | Prop::MouseY) { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + Some(X::Get { at, p }) + } + + /// A call with a value: the timeline's functions, `Math`, and casts. + fn call_expr(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { + match &callee.kind { + E::Member(o, m) if matches!(&o.kind, E::Name(c) if c == "Math") => { + let Some(f) = MathFn::from_name(m) else { + self.problem(pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round and random are)")); + return None; + }; + if let Some(n) = f.arity() + && n != args.len() + { + self.problem(pos, format!("`Math.{m}` takes {n} argument{}", if n == 1 { "" } else { "s" })); + return None; + } + let args = self.args(args, u)?; + Some(X::Math { f, args }) + } + E::Name(n) if !u.locals.contains_key(n) => { + let n = n.as_str(); + let cast = match n { + "int" => Some(Ty::Int), + "uint" => Some(Ty::Uint), + "Number" => Some(Ty::Number), + "String" => Some(Ty::String), + "Boolean" => Some(Ty::Boolean), + _ => None, + }; + if let Some(t) = cast { + let [a] = args else { + self.problem(pos, format!("`{n}(…)` takes one value")); + return None; + }; + let x = self.expr(a, u)?; + // `String(x)` of null is "null"; as a variable type it stays null. + return Some(match t { + Ty::String => X::Bin { op: BinOp::Add, a: Box::new(X::lit(Value::str(""))), b: Box::new(x) }, + t => X::Cast { t, x: Box::new(x) }, + }); + } + if Method::from_name(n).is_some() || matches!(n, "trace" | "addEventListener" | "removeEventListener") { + self.problem(pos, format!("`{n}()` gives no value; call it as a statement")); + return None; + } + if OUTSIDE.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || n == "getChildByName" { + self.problem(pos, format!("`{n}(…)` isn't supported here")); + return None; + } + let local = self.funcs.get(n).copied(); + if local.is_none() { + self.free(n, callee.pos, true); + } + if let Some(f) = local { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + if args.len() < required || args.len() > f.params.len() { + self.problem(pos, format!("`{n}` takes {}{} argument{}, not {}", required, if required == f.params.len() { String::new() } else { format!(" to {}", f.params.len()) }, if f.params.len() == 1 { "" } else { "s" }, args.len())); + return None; + } + } + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; + for a in args { + // The event a listener handles passes on to the function's event parameter. + if let E::Name(x) = &a.kind + && u.events.contains(x) + { + out.push(X::Event); + continue; + } + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, + } + } + ok.then_some(X::Call { f: n.to_string(), args: out }) + } + E::Member(_, m) => { + self.problem(pos, format!("calling `{m}` here isn't supported")); + None + } + _ => { + self.problem(pos, "only named functions and methods can be called"); + None + } + } + } } -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, - } +/// Whether a declared function can be a listener: the event is its one required parameter. +fn takes_event(f: &Func) -> bool { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + required <= 1 && !f.params.is_empty() +} + +/// A value written out (for parameter defaults). +fn literal(e: &Expr) -> O { + Some(match &e.kind { + E::Num(n) => Value::Num(*n), + E::Str(s) => Value::str(s), + E::Bool(b) => Value::Bool(*b), + E::Null => Value::Null, + E::Name(n) if n == "undefined" => Value::Undefined, + E::Name(n) if n == "NaN" => Value::Num(f64::NAN), + E::Unary("-", x) => match &x.kind { + E::Num(n) => Value::Num(-n), + _ => return None, + }, + _ => return None, + }) } fn label_ok(s: &str) -> bool { @@ -570,6 +989,27 @@ fn label_ok(s: &str) -> bool { (1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace()) } +/// Every `var` in a list of statements, into blocks and loops but not into functions. +fn collect_vars<'a>(list: &'a [Stmt], out: &mut Vec<&'a VarDecl>) { + for s in list { + match &s.kind { + S::Var(_, l) => out.extend(l.iter()), + S::Block(b) | S::While(_, b) | S::DoWhile(b, _) | S::Other(_, b) => collect_vars(b, out), + S::If(_, a, b) => { + collect_vars(a, out); + collect_vars(b, out); + } + S::For(init, _, _, b) => { + if let Some(i) = init { + collect_vars(std::slice::from_ref(&**i), out); + } + collect_vars(b, out); + } + _ => {} + } + } +} + /// 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) { @@ -577,7 +1017,7 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble match &s.kind { S::Function(f) => { let Some(n) = f.name.as_deref() else { continue }; - if BUILTINS.contains(&n) || CASTS.contains(&n) { + if BUILTINS.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || Prop::from_name(n).is_some() || matches!(n, "int" | "uint" | "Number" | "String" | "Boolean") { 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"))); @@ -589,21 +1029,70 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble } } +/// Counts statements (for "runs, N steps"). +fn count(list: &[IStmt]) -> usize { + list.iter() + .map(|s| { + 1 + match &s.s { + IS::If { a, b, .. } => count(a) + count(b), + IS::Loop { body, .. } => count(body), + _ => 0, + } + }) + .sum() +} + pub(super) fn lower(prog: &[Stmt]) -> Result> { 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"))); + // The script's top-level `var`s are the timeline's variables. + let mut decls = Vec::new(); + collect_vars(prog, &mut decls); + let mut vars = BTreeMap::new(); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + problems.push(Problem::at(d.pos, "variables can't hold events")); + continue; + } + Err((p, m)) => { + problems.push(Problem::at(p, m)); + continue; + } + }; + if Prop::from_name(&d.name).is_some() || PATH_WORDS.contains(&d.name.as_str()) || funcs.contains_key(d.name.as_str()) || BUILTINS.contains(&d.name.as_str()) { + problems.push(Problem::at(d.pos, format!("`{}` is already a name of the timeline; choose another name for the variable", d.name))); + continue; + } + match vars.get(&d.name) { + Some(old) if *old != t && d.ty.is_some() => problems.push(Problem::at(d.pos, format!("`{}` is declared again with another type", d.name))), + Some(_) => {} + None => { + vars.insert(d.name.clone(), t); + } + } } + let mut l = Lower { funcs, vars, problems, notes: Vec::new(), free: Vec::new(), listeners: 0, depth: 0 }; + let mut functions = Vec::new(); + let names: Vec<(&str, &Func)> = l.funcs.iter().map(|(n, f)| (*n, *f)).collect(); + for (n, f) in names { + if let Some(func) = l.function(f, n.to_string()) { + functions.push(func); + } + } + let mut top = Unit::top(); + let body = l.body(prog, &mut top); let tidy = |mut v: Vec| { 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)) } + if !l.problems.is_empty() { + return Err(tidy(l.problems)); + } + let steps = count(&body) + functions.iter().map(|f| count(&f.body)).sum::(); + Ok(Compiled { body, inner: top.inner, functions, vars: l.vars.into_iter().collect(), free: l.free, notes: tidy(l.notes), steps }) } diff --git a/crates/actions/src/as3/mod.rs b/crates/actions/src/as3/mod.rs index 191bd386..31702d3f 100644 --- a/crates/actions/src/as3/mod.rs +++ b/crates/actions/src/as3/mod.rs @@ -1,29 +1,40 @@ -//! 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. +//! The ActionScript 3.0 subset (ADR 0013 tiers 2 and 2.5): a hand-written lexer and +//! recursive-descent parser, a lowering to a small typed script IR ([`ir`]), and the evaluator +//! that runs it ([`run`]) over the player. //! -//! 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. +//! What runs is what Animate frame scripts do: timeline control (`stop()`, `play()`, +//! `gotoAndPlay`/`gotoAndStop` by frame or label and scene, `nextFrame()` … on this timeline or +//! on instance-name paths); **typed variables** (`var n:int = 0;` as Number, int, uint, Boolean, +//! String or untyped), kept per timeline instance across its frame scripts as ActionScript 3.0 +//! timelines keep them; **expressions** (arithmetic, comparison, logic, joining text, +//! `Math.min/max/abs/floor/ceil/round/random`, `int(…)` and the other casts); `if`/`else`, +//! `for`, `while` and `do` loops; **reading properties** of named instances and of the +//! timeline (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, +//! `totalFrames`, `currentLabel`, `mouseX/Y`, `name`); setting the instance ones; functions +//! with parameters and results, called from any frame script of the same timeline; listeners +//! (`addEventListener` and `removeEventListener`) for mouse events on buttons and movie clips, +//! `Event.ENTER_FRAME`, and `KeyboardEvent.KEY_DOWN`/`KEY_UP` on the stage with `e.keyCode`; +//! `e.target` and `e.currentTarget`; and `trace`. //! -//! 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. +//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all. +//! Calls that would reach outside the movie (`navigateToURL`, `fscommand`, `ExternalInterface`) +//! are ignored and listed as notes. A compiled script names the variables and functions it +//! uses from other frames ([`Compiled::free`]); the timeline must declare them +//! ([`Decls::problems`]) or the script doesn't run either. //! //! 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. +//! nesting depth, listeners and problems here; fuel, call depth and text length when it runs. +pub mod ir; mod lex; mod lower; mod parse; +pub mod run; -use crate::{Action, ButtonEvent, Target}; +use ir::{Function, Ty}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use std::sync::Arc; /// Longest script that runs, in bytes (far more than frame scripts written by hand). @@ -32,8 +43,6 @@ pub const MAX_RUN_BYTES: usize = 256 * 1024; 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. @@ -73,53 +82,95 @@ impl std::fmt::Display for Problem { } } -/// 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>, +/// A name a script uses that it doesn't declare: a variable or function of another frame +/// script of the same timeline. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Free { + pub name: String, + pub line: u32, + pub column: u32, + /// Called (a function), or read and written (a variable). + pub call: bool, } -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::>().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. +/// A script that runs. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Compiled { - pub ops: Vec, + /// The top-level statements, in order. + pub body: Vec, + /// Functions written in place at the top level (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, + /// The functions it declares (the timeline's, callable from its other frames). + pub functions: Vec>, + /// The variables it declares (the timeline's), with their types. + pub vars: Vec<(String, Ty)>, + /// Names it uses from other frames of the timeline. + pub free: Vec, /// Calls that are ignored (they would reach outside the movie, or do nothing here). pub notes: Vec, + /// Statements it holds, functions included (for "runs, N steps"). + pub steps: usize, } -/// 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`]). +/// A timeline's declarations: every function and variable its frame scripts declare (the +/// first one of a name, in frame order, top layer first), as ActionScript 3.0 makes them +/// members of the timeline. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Decls { + pub functions: BTreeMap>, + pub vars: BTreeMap, +} + +impl Decls { + /// From the timeline's compiled scripts, in frame order (top layer first within a frame). + pub fn build<'a>(scripts: impl IntoIterator) -> Decls { + let mut d = Decls::default(); + for c in scripts { + for f in &c.functions { + d.functions.entry(f.name.clone()).or_insert_with(|| f.clone()); + } + for (n, t) in &c.vars { + d.vars.entry(n.clone()).or_insert(*t); + } + } + d + } + + /// Why `c` can't run on a timeline with these declarations: a name from another frame that + /// the timeline doesn't declare, or a declaration another frame already makes differently. + pub fn problems(&self, c: &Compiled) -> Vec { + let mut out = Vec::new(); + for f in &c.free { + let pos = Pos { line: f.line, column: f.column }; + let known = if f.call { self.functions.contains_key(&f.name) } else { self.vars.contains_key(&f.name) }; + if !known { + let msg = match (f.call, self.functions.contains_key(&f.name) || self.vars.contains_key(&f.name)) { + (true, true) => format!("`{}` is a variable, not a function", f.name), + (false, true) => format!("`{}` is a function; call it, as in `{}()`", f.name, f.name), + (true, false) => format!("`{}` isn't a function of this timeline (declare it in one of its frame scripts)", f.name), + (false, false) => format!("`{}` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)", f.name), + }; + out.push(Problem::at(pos, msg)); + } + } + for f in &c.functions { + if self.functions.get(&f.name).is_some_and(|g| !Arc::ptr_eq(f, g) && **f != **g) { + out.push(Problem::at(Pos { line: f.line, column: 1 }, format!("`{}` is also declared on another frame of this timeline", f.name))); + } + } + for (n, t) in &c.vars { + if self.vars.get(n).is_some_and(|u| u != t) { + out.push(Problem::whole(format!("`{n}` is declared with another type on another frame of this timeline"))); + } + } + out.truncate(MAX_PROBLEMS); + out + } +} + +/// Compiles ActionScript 3.0 source to the script IR, or says why it doesn't run (the problems +/// sorted by position, at most [`MAX_PROBLEMS`]). pub fn compile(src: &str) -> Result> { 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))]); diff --git a/crates/actions/src/as3/parse.rs b/crates/actions/src/as3/parse.rs index ccdea22d..da49786f 100644 --- a/crates/actions/src/as3/parse.rs +++ b/crates/actions/src/as3/parse.rs @@ -1,8 +1,8 @@ //! 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 +//! can say exactly which construct isn't run and where; what it reads but never runs (`for in` +//! heads, `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}; @@ -47,7 +47,9 @@ pub enum E { pub struct Param { pub name: String, pub pos: Pos, - pub default: bool, + /// The type annotation as written (`int`, `MouseEvent`, `*`), when there is one. + pub ty: Option<(String, Pos)>, + pub default: Option, pub rest: bool, } @@ -56,9 +58,20 @@ pub struct Func { pub name: Option, pub pos: Pos, pub params: Vec, + /// The result type as written (`void`, `int`), when there is one. + pub ret: Option<(String, Pos)>, pub body: Vec, } +/// One name of a `var` (or `const`) statement. +#[derive(Clone, Debug, PartialEq)] +pub struct VarDecl { + pub name: String, + pub pos: Pos, + pub ty: Option<(String, Pos)>, + pub init: Option, +} + #[derive(Clone, Debug, PartialEq)] pub struct Stmt { pub pos: Pos, @@ -71,8 +84,15 @@ pub enum S { Import, Function(Func), /// `var`, `const`. - Var(&'static str), + Var(&'static str, Vec), If(Expr, Vec, Vec), + /// `for (init; cond; update) body` (`init` a `var` statement or an expression). + For(Option>, Option, Option, Vec), + While(Expr, Vec), + DoWhile(Vec, Expr), + /// `break` and `continue` (without a label). + Break, + Continue, Return(Option), Block(Vec), Empty, @@ -228,12 +248,83 @@ impl<'a> Parser<'a> { } } - /// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.`). - fn annotation(&mut self) -> R<()> { + /// `: Type` (`*`, `void`, `a.b.C`, `Vector.`), as written. + fn annotation(&mut self) -> R> { if !self.eat(":") { - return Ok(()); + return Ok(None); } - self.type_name() + let pos = self.pos(); + let start = self.i; + self.type_name()?; + let text: String = self + .toks + .get(start..self.i) + .unwrap_or_default() + .iter() + .map(|t| match &t.tok { + Tok::Name(n) => n.clone(), + Tok::Punct(p) => (*p).to_string(), + _ => String::new(), + }) + .collect(); + Ok(Some((text, pos))) + } + + /// The names of a `var` statement after the keyword. + fn var_list(&mut self) -> R> { + let mut out = Vec::new(); + loop { + let (name, pos) = self.name("a variable name")?; + let ty = self.annotation()?; + let init = if self.eat("=") { Some(self.assign()?) } else { None }; + out.push(VarDecl { name, pos, ty, init }); + if !self.eat(",") { + return Ok(out); + } + } + } + + /// `( init ; cond ; update )` after `for`, or `None` for `for … in` (read, not run). + #[allow(clippy::type_complexity)] + fn for_head(&mut self) -> R>, Option, Option)>> { + let open = self.i; + self.expect("(", "after `for`")?; + let pos = self.pos(); + let init = if self.is(";") { + None + } else if self.is_word("var") || self.is_word("const") { + let w = if self.is_word("var") { "var" } else { "const" }; + self.i += 1; + let list = self.var_list()?; + if self.is_word("in") || list.iter().any(|d| matches!(&d.init, Some(Expr { kind: E::Binary("in", ..), .. }))) { + self.i = open; + self.skip_group()?; + return Ok(None); + } + Some(Box::new(Stmt { pos, kind: S::Var(w, list) })) + } else { + let e = self.expr()?; + if matches!(e.kind, E::Binary("in", ..)) { + self.i = open; + self.skip_group()?; + return Ok(None); + } + Some(Box::new(Stmt { pos, kind: S::Expr(e) })) + }; + self.expect(";", "after the loop's start")?; + let cond = if self.is(";") { None } else { Some(self.expr()?) }; + self.expect(";", "after the loop's condition")?; + let update = if self.is(")") { None } else { Some(self.expr()?) }; + self.expect(")", "to close the loop's head")?; + Ok(Some((init, cond, update))) + } + + /// `( expr )` + fn paren(&mut self, what: &str) -> R { + self.expect("(", what)?; + let e = self.expr()?; + self.expect(")", "after the condition")?; + Ok(e) } fn type_name(&mut self) -> R<()> { @@ -323,18 +414,9 @@ impl<'a> Parser<'a> { "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; - } - } + let list = self.var_list()?; self.end()?; - S::Var(w) + S::Var(w, list) } "if" => { self.i += 1; @@ -353,14 +435,20 @@ impl<'a> Parser<'a> { } "for" => { self.i += 1; - self.eat_word("each"); - self.skip_group()?; - S::Other("for", self.body()?) + if self.eat_word("each") { + self.skip_group()?; + S::Other("for each", self.body()?) + } else { + match self.for_head()? { + Some((init, cond, update)) => S::For(init, cond, update, self.body()?), + None => S::Other("for in", self.body()?), + } + } } "while" => { self.i += 1; - self.skip_group()?; - S::Other("while", self.body()?) + let c = self.paren("after `while`")?; + S::While(c, self.body()?) } "do" => { self.i += 1; @@ -368,9 +456,9 @@ impl<'a> Parser<'a> { if !self.eat_word("while") { return Err(self.unexpected("`while` after the `do` body")); } - self.skip_group()?; + let c = self.paren("after `while`")?; self.end()?; - S::Other("do", b) + S::DoWhile(b, c) } "with" => { self.i += 1; @@ -408,11 +496,17 @@ impl<'a> Parser<'a> { _ => "throw", }; self.i += 1; - if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) { + let bare = self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl(); + if !bare { self.expr()?; } self.end()?; - S::Other(w, Vec::new()) + match (w, bare) { + ("break", true) => S::Break, + ("continue", true) => S::Continue, + ("throw", _) => S::Other("throw", Vec::new()), + _ => S::Other("labelled break", Vec::new()), + } } // Applications, not timeline scripts (ADR 0013 tier 3). "package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => { @@ -454,21 +548,18 @@ impl<'a> Parser<'a> { 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 }); + let ty = self.annotation()?; + let default = if self.eat("=") { Some(self.assign()?) } else { None }; + params.push(Param { name: n, pos: p, ty, default, rest }); if self.eat(")") { break; } self.expect(",", "or `)` after the parameter")?; } } - self.annotation()?; + let ret = self.annotation()?; let body = self.block()?; - Ok(Func { name, pos, params, body }) + Ok(Func { name, pos, params, ret, body }) } /// An expression (`a, b` included). @@ -534,29 +625,44 @@ impl<'a> Parser<'a> { ]; let Some(ops) = LEVELS.get(level) else { return self.unary() }; let mut lhs = self.binary(level + 1)?; - loop { + // Each operator in a row nests the tree one deeper: it counts toward the depth limit, + // so what runs the tree can't recurse without bound. + let mut chain = 0; + let r = 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) }; + let Some(op) = op else { break Ok(lhs) }; + chain += 1; + self.depth += 1; + if self.depth > MAX_DEPTH { + break Err(Problem::at(self.pos(), format!("this expression has too many operators in a row (code nests at most {MAX_DEPTH} levels deep)"))); + } 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()?; + if let Err(e) = self.type_name() { + break Err(e); + } 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)? + match self.binary(level + 1) { + Ok(e) => e, + Err(e) => break Err(e), + } }; lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) }; - } + }; + self.depth -= chain; + r } fn unary(&mut self) -> R { diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs new file mode 100644 index 00000000..262237fe --- /dev/null +++ b/crates/actions/src/as3/run.rs @@ -0,0 +1,538 @@ +//! Running the script IR (ADR 0052): a small tree-walking evaluator over a +//! [`World`] (the player, which knows the movie). It is deterministic (the only random numbers +//! come from the world's seeded generator) and bounded: every statement and expression costs +//! fuel, text has a length limit, calls a depth limit. When fuel runs out or something can't +//! be done (a name that isn't there, a value of the wrong kind), the run stops where it is, +//! as an ActionScript error stops a script, and says why; what it did before stays done. +//! +//! The HTML canvas player (`player.js`) mirrors this file step for step. + +use super::ir::*; +use crate::{FrameRef, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property}; +use std::sync::Arc; + +/// Fuel one frame script (or one listener call) may use. +pub const FUEL_PER_RUN: u64 = 100_000; +/// Deepest chain of calls. +pub const MAX_CALL_DEPTH: usize = 16; +/// Longest text a script makes, in UTF-16 units. +pub const MAX_TEXT: usize = 16_384; + +/// Why a run stopped before its end. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Stop { + /// It used its fuel (an endless loop, most likely). + Fuel, + /// Something couldn't be done, at `line`. + Error { line: u32, message: String }, + /// The world stopped everything (a per-frame budget ran out); it already said why. + Halt, +} + +impl Stop { + pub fn describe(&self) -> String { + match self { + Stop::Fuel => format!("it ran more than {FUEL_PER_RUN} steps (an endless loop?)"), + Stop::Error { line, message } if *line > 0 => format!("line {line}: {message}"), + Stop::Error { message, .. } => message.clone(), + Stop::Halt => "the frame's budget ran out".into(), + } + } +} + +/// What a running script talks to. Errors stop the run (`Err(message)`); actions that can't +/// find their instance write a line to Output and the script goes on, as before (tier 2). +pub trait World { + /// A timeline action, on the instance `base` starts from (`action`'s target is the name path). + fn act(&mut self, base: Base, action: &crate::Action) -> Result<(), Option>; + /// Reads a property. + fn get(&mut self, at: &Place, p: Prop) -> Result; + /// Sets an instance property. + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option>; + /// Sets a text field's text (ADR 0066). + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option>; + fn trace(&mut self, line: String); + /// A timeline variable's value, and writing one (the world knows its type). + fn read(&mut self, name: &str) -> Result; + fn write(&mut self, name: &str, v: Value) -> Result<(), String>; + /// The timeline's function by that name. + fn function(&mut self, name: &str) -> Option>; + /// Adds (or removes) a listener; `name` is how it is known (adding the same again does + /// nothing). + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option>; + /// The next number from the movie's seeded generator, in [0, 1). + fn random(&mut self) -> f64; + /// Whether two names are one instance. + fn same(&mut self, a: &Place, b: &Place) -> Result; + /// The keyboard event's key code. + fn key_code(&mut self) -> Result; +} + +/// The error of a world call: `None` means the world halted (and said so). +fn lift(line: u32, e: Option) -> Stop { + match e { + Some(message) => Stop::Error { line, message }, + None => Stop::Halt, + } +} + +enum Flow { + Normal, + Break, + Continue, + Return(Value), +} + +struct Frame<'f> { + locals: Vec, + /// Each local's type (a write coerces to it). + types: &'f [Ty], + inner: &'f [Arc], +} + +struct Vm<'w> { + w: &'w mut dyn World, + fuel: u64, + depth: usize, + line: u32, +} + +type R = Result; + +/// Runs a frame script's top-level statements; returns the fuel used and how it ended. +pub fn run_script(w: &mut dyn World, body: &[Stmt], inner: &[Arc], fuel: u64) -> (u64, Result<(), Stop>) { + let mut vm = Vm { w, fuel, depth: 0, line: 0 }; + let mut frame = Frame { locals: Vec::new(), types: &[], inner }; + let r = vm.block(body, &mut frame).map(|_| ()); + (fuel - vm.fuel, r) +} + +/// Calls a listener's function with the event (its first parameter). +pub fn run_listener(w: &mut dyn World, f: &Arc, fuel: u64) -> (u64, Result<(), Stop>) { + let mut vm = Vm { w, fuel, depth: 0, line: f.line }; + let r = vm.call(f, &[Expr::Event], &mut Frame { locals: Vec::new(), types: &[], inner: &[] }).map(|_| ()); + (fuel - vm.fuel, r) +} + +/// JavaScript's `Math.round`: the nearest integer, halves toward +∞. +pub fn round(x: f64) -> f64 { + if !x.is_finite() { + return x; + } + let f = x.floor(); + if x - f >= 0.5 { f + 1.0 } else { f } +} + +/// Math.min / Math.max: NaN wins, no arguments give ±Infinity. +fn min_max(vals: &[f64], max: bool) -> f64 { + let mut out = if max { f64::NEG_INFINITY } else { f64::INFINITY }; + for &v in vals { + if v.is_nan() { + return f64::NAN; + } + if (max && v > out) || (!max && v < out) { + out = v; + } + } + out +} + +/// `==` (ECMA-262 §11.9.3) over primitives. +pub fn loose_eq(a: &Value, b: &Value) -> bool { + use Value as V; + match (a, b) { + (V::Undefined | V::Null, V::Undefined | V::Null) => true, + (V::Undefined | V::Null, _) | (_, V::Undefined | V::Null) => false, + (V::Num(x), V::Num(y)) => x == y, + (V::Str(x), V::Str(y)) => x == y, + (V::Bool(x), V::Bool(y)) => x == y, + (V::Num(x), V::Str(_)) => *x == b.number(), + (V::Str(_), V::Num(y)) => a.number() == *y, + (V::Bool(_), _) => loose_eq(&V::Num(a.number()), b), + (_, V::Bool(_)) => loose_eq(a, &V::Num(b.number())), + } +} + +/// `===` (§11.9.6). +pub fn strict_eq(a: &Value, b: &Value) -> bool { + use Value as V; + match (a, b) { + (V::Num(x), V::Num(y)) => x == y, + (V::Undefined, V::Undefined) | (V::Null, V::Null) => true, + (V::Str(x), V::Str(y)) => x == y, + (V::Bool(x), V::Bool(y)) => x == y, + _ => false, + } +} + +/// `<` (§11.8.5): text by UTF-16 units, the rest as numbers; `None` when a NaN is involved. +fn compare(a: &Value, b: &Value) -> Option { + if let (Value::Str(x), Value::Str(y)) = (a, b) { + return Some(x.encode_utf16().cmp(y.encode_utf16())); + } + a.number().partial_cmp(&b.number()) +} + +/// Text cut to [`MAX_TRACE_CHARS`] UTF-16 units (never through a surrogate pair), with `…`. +pub fn trace_line(s: String) -> String { + let units: Vec = s.encode_utf16().collect(); + if units.len() <= MAX_TRACE_CHARS { + return s; + } + let mut n = MAX_TRACE_CHARS; + if units.get(n - 1).is_some_and(|u| (0xd800..0xdc00).contains(u)) { + n -= 1; + } + let mut out = String::from_utf16_lossy(units.get(..n).unwrap_or(&[])); + out.push('…'); + out +} + +impl Vm<'_> { + fn tick(&mut self, n: u64) -> R<()> { + if self.fuel < n { + self.fuel = 0; + return Err(Stop::Fuel); + } + self.fuel -= n; + Ok(()) + } + + fn err(&self, message: impl Into) -> R { + Err(Stop::Error { line: self.line, message: message.into() }) + } + + fn block(&mut self, list: &[Stmt], fr: &mut Frame<'_>) -> R { + for s in list { + match self.stmt(s, fr)? { + Flow::Normal => {} + other => return Ok(other), + } + } + Ok(Flow::Normal) + } + + fn stmt(&mut self, st: &Stmt, fr: &mut Frame<'_>) -> R { + self.tick(1)?; + self.line = st.l; + match &st.s { + S::Do { x } => { + self.expr(x, fr)?; + } + S::If { c, a, b } => { + let c = self.expr(c, fr)?.truthy(); + return self.block(if c { a } else { b }, fr); + } + S::Loop { c, body, next, first } => { + let mut test = *first; + loop { + if test && let Some(c) = c { + self.line = st.l; + if !self.expr(c, fr)?.truthy() { + break; + } + } + test = true; + // A loop with nothing in it still costs fuel. + self.tick(1)?; + match self.block(body, fr)? { + Flow::Break => break, + Flow::Return(v) => return Ok(Flow::Return(v)), + Flow::Normal | Flow::Continue => {} + } + if let Some(n) = next { + self.line = st.l; + self.expr(n, fr)?; + } + } + } + S::Break => return Ok(Flow::Break), + S::Continue => return Ok(Flow::Continue), + S::Return { v } => { + let v = match v { + Some(v) => self.expr(v, fr)?, + None => Value::Undefined, + }; + return Ok(Flow::Return(v)); + } + S::Act { at, m, args } => { + let frame = match args.first() { + Some(a) => Some(self.expr(a, fr)?), + None => None, + }; + let scene = match args.get(1) { + Some(a) => Some(self.expr(a, fr)?), + None => None, + }; + self.line = st.l; + let frame = match frame { + None => FrameRef::default(), + Some(Value::Str(s)) if label_ok(&s) => FrameRef::Label(s.to_string()), + Some(Value::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1), + Some(v) => return self.err(format!("`{}` needs a frame number from 1 or a label, not {}", m.name(), shown(&v))), + }; + let scene = match scene { + None | Some(Value::Null | Value::Undefined) => None, + Some(Value::Str(s)) if label_ok(&s) => Some(s.to_string()), + Some(v) => return self.err(format!("the scene is its name, not {}", shown(&v))), + }; + let action = m.action(at.path.clone(), frame, scene); + self.w.act(at.base, &action).map_err(|e| lift(st.l, e))?; + } + S::Trace { args } => { + let mut parts = Vec::with_capacity(args.len()); + for a in args { + parts.push(self.expr(a, fr)?.text()); + } + self.w.trace(trace_line(parts.join(" "))); + } + S::Listen { at, ev, f, add } => { + let func = match f { + FuncRef::Named(n) => match self.w.function(n) { + Some(f) => f, + None => return self.err(format!("there's no function `{n}` on this timeline")), + }, + FuncRef::Inline(i) => match fr.inner.get(usize::from(*i)) { + Some(f) => f.clone(), + None => return self.err("the listener's function is missing"), + }, + }; + self.w.listen(at, *ev, &func, *add).map_err(|e| lift(st.l, e))?; + } + } + Ok(Flow::Normal) + } + + fn text(&mut self, s: String) -> R { + let n = text_len(&s); + if n > MAX_TEXT { + return self.err(format!("this text would be longer than {MAX_TEXT} characters")); + } + // Making text costs fuel for its length, so a loop building text can't run long. + self.tick(n as u64 / 64)?; + Ok(Value::Str(s.into())) + } + + fn binary(&mut self, op: BinOp, a: Value, b: Value) -> R { + use std::cmp::Ordering::*; + Ok(match op { + BinOp::Add if a.is_str() || b.is_str() => return self.text(a.text() + &b.text()), + BinOp::Add => Value::Num(a.number() + b.number()), + BinOp::Sub => Value::Num(a.number() - b.number()), + BinOp::Mul => Value::Num(a.number() * b.number()), + BinOp::Div => Value::Num(a.number() / b.number()), + BinOp::Mod => Value::Num(a.number() % b.number()), + BinOp::Lt => Value::Bool(compare(&a, &b) == Some(Less)), + BinOp::Gt => Value::Bool(compare(&a, &b) == Some(Greater)), + BinOp::Le => Value::Bool(matches!(compare(&a, &b), Some(Less | Equal))), + BinOp::Ge => Value::Bool(matches!(compare(&a, &b), Some(Greater | Equal))), + BinOp::Eq => Value::Bool(loose_eq(&a, &b)), + BinOp::Ne => Value::Bool(!loose_eq(&a, &b)), + BinOp::StrictEq => Value::Bool(strict_eq(&a, &b)), + BinOp::StrictNe => Value::Bool(!strict_eq(&a, &b)), + }) + } + + fn load(&mut self, to: &LValue, fr: &Frame<'_>) -> R { + match to { + LValue::Local { i } => Ok(fr.locals.get(usize::from(*i)).cloned().unwrap_or_default()), + LValue::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }), + LValue::Prop { at, p } => { + let prop = match p { + Property::X => Prop::X, + Property::Y => Prop::Y, + Property::Alpha => Prop::Alpha, + Property::Visible => Prop::Visible, + Property::Rotation => Prop::Rotation, + Property::ScaleX => Prop::ScaleX, + Property::ScaleY => Prop::ScaleY, + }; + self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message }) + } + LValue::Text { at } => self.w.get(at, Prop::Text).map_err(|message| Stop::Error { line: self.line, message }), + } + } + + /// Writes `v`; the value is what the place holds after (a typed variable's coercion). + fn store(&mut self, to: &LValue, v: Value, fr: &mut Frame<'_>) -> R { + match to { + LValue::Local { i } => { + let ty = fr.types.get(usize::from(*i)).copied().unwrap_or_default(); + let v = ty.coerce(v); + if let Some(slot) = fr.locals.get_mut(usize::from(*i)) { + *slot = v.clone(); + } + Ok(v) + } + LValue::Var { n } => { + self.w.write(n, v).map_err(|message| Stop::Error { line: self.line, message })?; + self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }) + } + LValue::Prop { at, p } => { + let n = v.number(); + if !n.is_finite() { + return self.err(format!("`{}` is set to a number, not {}", prop_name(*p), shown(&v))); + } + self.w.set(at, *p, n).map_err(|e| lift(self.line, e))?; + Ok(v) + } + LValue::Text { at } => { + if matches!(v, Value::Null | Value::Undefined) { + return self.err(format!("`text` is set to text, not {}", v.text())); + } + self.w.set_text(at, v.text()).map_err(|e| lift(self.line, e))?; + Ok(v) + } + } + } + + fn expr(&mut self, e: &Expr, fr: &mut Frame<'_>) -> R { + self.tick(1)?; + Ok(match e { + Expr::Lit { v } => v.clone(), + Expr::Local { i } => fr.locals.get(usize::from(*i)).cloned().unwrap_or_default(), + Expr::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })?, + Expr::Get { at, p } => self.w.get(at, *p).map_err(|message| Stop::Error { line: self.line, message })?, + Expr::Key => Value::Num(self.w.key_code().map_err(|message| Stop::Error { line: self.line, message })?), + Expr::Event => return self.err("the event can only be passed to a function's event parameter"), + Expr::Un { op, x } => { + let v = self.expr(x, fr)?; + match op { + UnOp::Neg => Value::Num(-v.number()), + UnOp::Plus => Value::Num(v.number()), + UnOp::Not => Value::Bool(!v.truthy()), + } + } + Expr::Bin { op, a, b } => { + let a = self.expr(a, fr)?; + let b = self.expr(b, fr)?; + return self.binary(*op, a, b); + } + Expr::And { a, b } => { + let a = self.expr(a, fr)?; + if a.truthy() { self.expr(b, fr)? } else { a } + } + Expr::Or { a, b } => { + let a = self.expr(a, fr)?; + if a.truthy() { a } else { self.expr(b, fr)? } + } + Expr::Cond { c, a, b } => { + if self.expr(c, fr)?.truthy() { + self.expr(a, fr)? + } else { + self.expr(b, fr)? + } + } + Expr::Math { f, args } => { + let mut v = Vec::with_capacity(args.len()); + for a in args { + v.push(self.expr(a, fr)?.number()); + } + let x = v.first().copied().unwrap_or(f64::NAN); + Value::Num(match f { + MathFn::Min => min_max(&v, false), + MathFn::Max => min_max(&v, true), + MathFn::Abs => x.abs(), + MathFn::Floor => x.floor(), + MathFn::Ceil => x.ceil(), + MathFn::Round => round(x), + MathFn::Random => self.w.random(), + }) + } + Expr::Call { f, args } => { + let Some(func) = self.w.function(f) else { return self.err(format!("there's no function `{f}` on this timeline")) }; + let line = self.line; + let v = self.call(&func, args, fr)?; + self.line = line; + v + } + Expr::Same { a, b, ne } => { + let same = self.w.same(a, b).map_err(|message| Stop::Error { line: self.line, message })?; + Value::Bool(same != *ne) + } + Expr::Set { to, op, v } => { + let new = match op { + None => self.expr(v, fr)?, + Some(op) => { + let old = self.load(to, fr)?; + let rhs = self.expr(v, fr)?; + self.binary(*op, old, rhs)? + } + }; + return self.store(to, new, fr); + } + Expr::Step { to, d, post } => { + let old = Value::Num(self.load(to, fr)?.number()); + let new = Value::Num(old.number() + f64::from(*d)); + let stored = self.store(to, new, fr)?; + if *post { old } else { stored } + } + Expr::Cast { t, x } => { + let v = self.expr(x, fr)?; + t.coerce(v) + } + }) + } + + /// Calls `f` with `args` evaluated in the caller's frame. + fn call(&mut self, f: &Arc, args: &[Expr], caller: &mut Frame<'_>) -> R { + if self.depth >= MAX_CALL_DEPTH { + return self.err(format!("functions call each other more than {MAX_CALL_DEPTH} deep")); + } + let required = f.params.iter().filter(|p| p.d.is_none()).count(); + if args.len() < required || args.len() > f.params.len() { + let want = if required == f.params.len() { format!("{required}") } else { format!("{required} to {}", f.params.len()) }; + return self.err(format!("`{}` takes {want} argument{}, not {}", f.name, if f.params.len() == 1 { "" } else { "s" }, args.len())); + } + let mut locals: Vec = f.locals.iter().map(|t| t.default_value()).collect(); + for (i, p) in f.params.iter().enumerate() { + let v = match args.get(i) { + Some(Expr::Event) if p.ev || p.t == Ty::Any => Value::Null, + Some(Expr::Event) => return self.err("the event can only be passed to a function's event parameter"), + Some(a) => self.expr(a, caller)?, + None => p.d.clone().unwrap_or_default(), + }; + if let Some(slot) = locals.get_mut(i) { + *slot = p.t.coerce(v); + } + } + self.depth += 1; + self.line = f.line; + let mut fr = Frame { locals, types: &f.locals, inner: &f.inner }; + let flow = self.block(&f.body, &mut fr); + self.depth -= 1; + let v = match flow? { + Flow::Return(v) => v, + _ => Value::Undefined, + }; + Ok(match f.ret { + Some(t) => t.coerce(v), + None => Value::Undefined, + }) + } +} + +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()) +} + +/// A value as a message names it. +fn shown(v: &Value) -> String { + match v { + Value::Str(s) => format!("\"{}\"", s.chars().take(40).collect::()), + other => other.text(), + } +} + +fn prop_name(p: Property) -> &'static str { + match p { + Property::X => "x", + Property::Y => "y", + Property::Alpha => "alpha", + Property::Visible => "visible", + Property::Rotation => "rotation", + Property::ScaleX => "scaleX", + Property::ScaleY => "scaleY", + } +} diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 7ce85de8..2cc2e506 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -1,21 +1,13 @@ +use super::ir::*; +use super::run::{self, Stop, World}; use super::*; -use crate::{Action, ButtonEvent, FrameRef, Property, Target}; +use crate::{Action, FrameRef, Property}; +use std::collections::BTreeMap; fn ok(src: &str) -> Compiled { compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}")) } -fn actions(src: &str) -> Vec { - 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) { @@ -27,99 +19,273 @@ fn err(src: &str) -> (u32, u32, String) { } } -fn t(s: &str) -> Target { - Target::new(s) +/// A movie in miniature: one timeline with its variables and functions, instances with +/// properties, and a log of everything the script did. +#[derive(Default)] +struct Mock { + decls: Decls, + vars: BTreeMap, + props: BTreeMap<(String, &'static str), f64>, + log: Vec, + rng: u32, + key: Option, + frame: u32, + /// Text fields' text, by name. + texts: BTreeMap, } -#[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 = 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 = 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:?}"), +impl World for Mock { + fn act(&mut self, base: Base, a: &Action) -> Result<(), Option> { + if let Action::GotoAndStop { frame: FrameRef::Number(n), .. } = a { + self.frame = *n; + } + self.log.push(format!("{base:?} {}", a.describe())); + Ok(()) + } + fn get(&mut self, at: &Place, p: Prop) -> Result { + if at.path.0 == "ghost" { + return Err("no instance named “ghost” here".into()); + } + Ok(match p { + Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)), + Prop::Name => Value::str(&at.to_string()), + Prop::Visible => Value::Bool(true), + Prop::Text | Prop::Length => { + let t = self.texts.get(&at.path.0).ok_or_else(|| format!("“{at}” isn't a text field"))?; + if p == Prop::Text { Value::str(t) } else { Value::Num(text_len(t) as f64) } + } + p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)), }) - .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}"); + } + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option> { + let name = Prop::from_name(match p { + Property::X => "x", + Property::Y => "y", + Property::Alpha => "alpha", + Property::Visible => "visible", + Property::Rotation => "rotation", + Property::ScaleX => "scaleX", + Property::ScaleY => "scaleY", + }) + .map_or("?", Prop::name); + self.props.insert((at.path.0.clone(), name), v); + Ok(()) + } + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option> { + if !self.texts.contains_key(&at.path.0) { + return Err(Some(format!("“{at}” isn't a text field"))); + } + self.log.push(format!("text {at} = {text}")); + self.texts.insert(at.path.0.clone(), text); + Ok(()) + } + fn trace(&mut self, line: String) { + self.log.push(line); + } + fn read(&mut self, name: &str) -> Result { + match self.vars.get(name) { + Some(v) => Ok(v.clone()), + None => self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't defined")), + } + } + fn write(&mut self, name: &str, v: Value) -> Result<(), String> { + let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't defined"))?; + self.vars.insert(name.to_string(), t.coerce(v)); + Ok(()) + } + fn function(&mut self, name: &str) -> Option> { + self.decls.functions.get(name).cloned() + } + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + self.log.push(format!("{} {} {at} {}", if add { "listen" } else { "unlisten" }, ev.key(), f.name)); + Ok(()) + } + fn random(&mut self) -> f64 { + self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345); + f64::from(self.rng >> 8) / f64::from(1u32 << 24) + } + fn same(&mut self, a: &Place, b: &Place) -> Result { + Ok(a == b) + } + fn key_code(&mut self) -> Result { + self.key.ok_or_else(|| "there's no keyboard event here".into()) } } +/// Compiles and runs `src` on a fresh timeline; the log and how the run ended. +fn exec(src: &str) -> (Vec, Result<(), Stop>, Mock) { + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + assert!(m.decls.problems(&c).is_empty(), "{:?}", m.decls.problems(&c)); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + (std::mem::take(&mut m.log), r, m) +} + +fn lines(src: &str) -> Vec { + let (log, r, _) = exec(src); + assert_eq!(r, Ok(()), "{src}: {log:?}"); + log +} + #[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), .. }))); +fn timeline_calls_run_as_actions() { + let a = lines("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();\ngotoAndStop(1); gotoAndPlay(\"run\"); gotoAndPlay(12, \"Scene 2\"); gotoAndStop('end', null); gotoAndStop(2 + 3);"); + assert_eq!(a, ["This Stop", "This Play", "This Next frame", "This Previous frame", "This Next scene", "This Previous scene", "This Go to frame 1 and stop", "This Go to “run” and play", "This Go to frame 12 in “Scene 2” and play", "This Go to “end” and stop", "This Go to frame 5 and stop"]); + let a = lines("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();"); + assert_eq!(a, ["This Go to “run” and stop (hero_mc)", "This Play (hero_mc.arm_mc)", "This Stop (parent)", "This Next frame (parent.parent)", "This Play (root.menu)", "This Stop (root)", "This Stop (root)", "This Previous frame (parent.door)"]); +} + +#[test] +fn typed_variables_coerce_as_actionscript_does() { + let a = lines( + "var n:int = 7.9; var u:uint = -1; var num:Number = \"2.5\"; var b:Boolean = \"no\"; var s:String = 12; var z:String; var any = \"x\";\n\ + var big:int = 2147483647; big = big + 1;\n\ + var nan:Number; var none:int;\n\ + trace(n, u, num, b, s, z, any, big, nan, none);\n\ + n += 0.7; n++; ++n; trace(n, n++ + n, --n);", + ); + assert_eq!(a, ["7 4294967295 2.5 true 12 null x -2147483648 NaN 0", "9 19 9"]); +} + +#[test] +fn expressions_follow_ecmascript() { + let a = lines( + r#"trace(1 + 2 * 3 - 4 / 8, 7 % 3, -7 % 3, 1 / 0, -1 / 0, 0 / 0); + trace("a" + 1 + 2, 1 + 2 + "a", "5" * "2", "x" - 1, true + 1, null + 1, undefined + 1); + trace(1 < 2, "b" < "a", "10" < "9", 10 < "9", NaN < 1, NaN >= 1, 2 >= 2); + trace(1 == "1", 1 === "1", null == undefined, null === undefined, 0 == false, "" == 0, NaN == NaN, "a" != "b"); + trace(0 || "x", 1 && "y", !0, !"", true ? "t" : "f", null || undefined); + trace(int("12px"), int(" 0x1F "), Number(""), Number("1e3"), String(null), Boolean("false"), uint(-2), Number("Infinity"), Number("infinity")); + trace(Math.min(3, 1, 2), Math.max(), Math.min(1, NaN), Math.abs(-4.5), Math.floor(-1.5), Math.ceil(1.2), Math.round(2.5), Math.round(-2.5), Math.round(-0.4), Math.PI > 3.14);"#, + ); + assert_eq!( + a, + [ + "6.5 1 -1 Infinity -Infinity NaN", + "a12 3a 10 NaN 2 1 NaN", + "true false true false false false true", + "true false true false true true false true", + "x y true true t undefined", + "0 31 0 1000 null true 4294967294 Infinity NaN", + "1 -Infinity NaN 4.5 -2 2 3 -2 0 true", + ] + ); +} + +#[test] +fn if_else_and_loops_run_with_break_and_continue() { + let a = lines( + "var total:int = 0;\n\ + for (var i:int = 0; i < 10; i++) { if (i == 2) continue; if (i > 5) break; total += i; }\n\ + trace(total, i);\n\ + var k:int = 3; while (k > 0) { k--; } trace(k);\n\ + do { k++; } while (k < 2); trace(k);\n\ + do { k = 100; } while (false); trace(k);\n\ + if (k > 50) trace(\"big\"); else if (k > 5) trace(\"mid\"); else trace(\"small\");\n\ + for (;;) { break; } trace(\"out\");", + ); + assert_eq!(a, ["13 6", "0", "2", "100", "big", "out"]); +} + +#[test] +fn functions_take_parameters_return_values_and_recurse() { + let a = lines( + "function add(a:int, b:int = 10):int { return a + b; }\n\ + function fact(n:Number):Number { if (n <= 1) return 1; return n * fact(n - 1); }\n\ + function hello(who:String):void { trace(\"hi \" + who); return; trace(\"never\"); }\n\ + function untyped(x) { return x; }\n\ + trace(add(1, 2), add(5), add(1.9, 0.9), fact(5), untyped(\"u\"), hello(\"you\"));\n\ + function loopy():int { var s:int; for (var j:int = 0; j < 4; j++) s += j; return s; } trace(loopy(), loopy());", + ); + assert_eq!(a, ["hi you", "3 15 1 120 u undefined", "6 6"]); +} + +#[test] +fn properties_are_read_and_set() { + let (log, r, m) = exec("hero.x = 10; hero.x += 5; hero.alpha = .5; trace(hero.x, hero.alpha, hero.name, currentFrame, this.currentFrame, hero.visible);\ngotoAndStop(4); trace(currentFrame);\nhero.rotation = hero.x * 2;"); + assert_eq!(r, Ok(())); + assert_eq!(log, ["15 0.5 hero 1 1 true", "This Go to frame 4 and stop", "4"]); + assert_eq!(m.props.get(&("hero".into(), "rotation")), Some(&30.0)); + // Reading an instance that isn't there stops the script there. + let (log, r, _) = exec("trace(\"a\");\ntrace(ghost.x);\ntrace(\"b\");"); + assert_eq!(log, ["a"]); + assert_eq!(r, Err(Stop::Error { line: 2, message: "no instance named “ghost” here".into() })); +} + +#[test] +fn listeners_name_their_events_and_functions() { + let c = ok("import flash.events.*;\nbtn.addEventListener(MouseEvent.CLICK, go);\naddEventListener(Event.ENTER_FRAME, tick);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT) trace(\"left\"); });\nbtn.removeEventListener(MouseEvent.CLICK, go);\nfunction go(e:MouseEvent):void { MovieClip(e.currentTarget).gotoAndStop(2); trace(e.target.name); }\nfunction tick(e:Event):void {}\nhero.addEventListener(\"mouseOver\", go, false, 0, true);"); + assert_eq!(c.inner.len(), 1); + assert_eq!(c.functions.iter().map(|f| f.name.as_str()).collect::>(), ["go", "tick"]); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert_eq!(r, Ok(())); + assert_eq!(m.log, ["listen click btn go", "listen enter_frame this tick", "listen key_down stage function at line 4, column 48", "unlisten click btn go", "listen over hero go"]); + // The listener functions: the event's key code, target and current target. + m.log.clear(); + m.key = Some(37.0); + let key = c.inner[0].clone(); + assert_eq!(run::run_listener(&mut m, &key, 1000).1, Ok(())); + let go = c.functions[0].clone(); + assert_eq!(run::run_listener(&mut m, &go, 1000).1, Ok(())); + assert_eq!(m.log, ["left", "Current Go to frame 2 and stop", "e.target"]); + // Keyboard listeners belong on the stage; elsewhere they are ignored and noted. + let c = ok("addEventListener(KeyboardEvent.KEY_UP, f); function f(e) {}"); + assert!(c.body.is_empty() && c.notes[0].message.starts_with("keys go to the stage"), "{c:?}"); +} + +#[test] +fn names_from_other_frames_link_through_the_timeline() { + let frame1 = ok("var score:int = 0;\nfunction addPoints(n:int):void { score += n; }\nfunction shout():String { return \"score \" + score; }"); + let frame5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout(), lives);"); + assert_eq!(frame5.free.iter().map(|f| (f.name.as_str(), f.call)).collect::>(), [("addPoints", true), ("score", false), ("shout", true), ("lives", false)]); + let d = Decls::build([&frame1, &frame5]); + let p = d.problems(&frame5); + assert_eq!(p.len(), 1, "{p:?}"); + assert_eq!((p[0].line, p[0].column), (3, 16)); + assert!(p[0].message.starts_with("`lives` isn't a variable of this timeline"), "{}", p[0].message); + let ok5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout());"); + let d = Decls::build([&frame1, &ok5]); + assert!(d.problems(&ok5).is_empty() && d.problems(&frame1).is_empty()); + let mut m = Mock { decls: d, ..Mock::default() }; + for c in [&frame1, &ok5] { + assert_eq!(run::run_script(&mut m, &c.body, &c.inner, 10_000).1, Ok(())); + } + assert_eq!(m.log, ["score 6"]); + // A function declared on two frames, or a variable with two types, is a problem. + let again = ok("function shout():String { return \"again\"; }\nvar score:String;"); + let d = Decls::build([&frame1, &again]); + assert_eq!(d.problems(&again).len(), 2, "{:?}", d.problems(&again)); +} + +#[test] +fn fuel_stops_an_endless_loop_cleanly() { + let c = ok("trace(\"before\");\nwhile (true) {}\ntrace(\"after\");"); + let mut m = Mock::default(); + let (used, r) = run::run_script(&mut m, &c.body, &c.inner, 5_000); + assert_eq!((used, r), (5_000, Err(Stop::Fuel))); + assert_eq!(m.log, ["before"]); + // Recursion is bounded by depth, text by length, and both stop the run. + let (_, r, _) = exec("function f(n:int):int { return f(n + 1); } f(0);"); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("more than 16 deep")), "{r:?}"); + let (_, r, _) = exec("var s:String = \"x\"; while (true) s = s + s;"); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("longer than 16384")), "{r:?}"); + // Building text costs fuel for its length. + let c = ok("var s:String = \"\"; for (var i:int = 0; i < 100000; i++) s = s + \"ab\";"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + assert_eq!(run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1, Err(Stop::Fuel)); +} + +#[test] +fn random_comes_from_the_world() { + let a = lines("var r:Number = Math.random(); trace(r >= 0 && r < 1, Math.floor(Math.random() * 6) + 1 <= 6);"); + assert_eq!(a, ["true true"]); } #[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("") })]); + assert_eq!(c.body.len(), 1); let lines: Vec = 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); @@ -127,50 +293,52 @@ fn calls_outside_the_movie_are_ignored_and_noted() { #[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("") }]); + let a = lines("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\""); + assert_eq!(a, ["This Stop", "This Play"]); 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"), + (" for each (var v in list) {}", 1, 3, "`for each` loops aren't supported yet"), + ("for (var k in o) {}", 1, 1, "`for in` 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"), + ("var a:Array = [];", 1, 7, "variables of type `Array` aren't supported yet"), + ("var x:int = 1;", 1, 5, "`x` is already a name of the timeline"), ("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"), + ("currentFrame = 5;", 1, 1, "`currentFrame` can only be read"), ("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"), + ("trace(hero.width);", 1, 7, "reading `width` isn't supported yet"), + ("trace([1]);", 1, 7, "arrays aren't supported yet"), + ("trace(stage.stageWidth);", 1, 7, "`stage.stageWidth` isn't supported yet"), + ("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "mouse listeners on the stage"), + ("b.addEventListener(Event.RESIZE, f); function f(e) {}", 1, 20, "listening for Event.RESIZE isn't supported yet"), ("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"), + ("b.addEventListener(MouseEvent.CLICK, f); function f(e:MouseEvent) { trace(e.stageX); }", 1, 75, "reading the event's `stageX`"), + ("b.removeEventListener(MouseEvent.CLICK, function (e) {});", 1, 41, "a function written in place can't be removed"), ("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`"), + ("function f(a:int, n) { n.play(); } f(1, 2);", 1, 24, "`n` is a variable, not an instance"), + ("function f(a:int) {} f();", 1, 22, "`f` takes 1 argument, not 0"), + ("function f(...rest) {}", 1, 15, "rest parameters"), + ("var n:int; n.play();", 1, 12, "`n` is a variable, not an instance"), + ("var s:String = \"ab\"; trace(s.length);", 1, 28, "reading `length` of a value"), ("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"), + ("trace(new Date());", 1, 7, "`new` isn't supported yet"), + ("trace(1 & 2);", 1, 7, "the `&` operator isn't supported yet"), + ("var n:int; n <<= 2;", 1, 12, "`<<=` isn't supported yet"), + ("break;", 1, 1, "`break` is only for loops here"), + ("trace(stop());", 1, 7, "`stop()` gives no value"), + ("trace(Math.sqrt(4));", 1, 7, "`Math.sqrt` isn't supported yet"), + ("trace(Keyboard.WIGGLE);", 1, 7, "`Keyboard.WIGGLE` isn't a key"), ("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"), @@ -183,9 +351,8 @@ fn every_problem_says_where_it_is() { ("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"), + ("\tstop();\n\t\twith (a) {}", 2, 3, "`with` statements"), ]; for (src, line, col, msg) in cases { let (l, c, m) = err(src); @@ -195,19 +362,34 @@ fn every_problem_says_where_it_is() { #[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 p = compile("stop();\nvar a:Array;\nswitch (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!(at, [(2, 7), (3, 1), (5, 1)]); + let many: String = (0..200).map(|i| format!("hero.w{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}"); + assert_eq!(number_text(n), s, "{n}"); } + for (s, n) in [("", 0.0), (" 12 ", 12.0), ("1e3", 1000.0), (".5", 0.5), ("5.", 5.0), ("-0x10", f64::NAN), ("0x10", 16.0), ("0b101", 5.0), ("+Infinity", f64::INFINITY), ("inf", f64::NAN), ("1_0", f64::NAN), ("\u{a0}7\u{feff}", 7.0), ("1e", f64::NAN), ("-", f64::NAN)] { + let v = string_number(s); + assert!(v == n || (v.is_nan() && n.is_nan()), "{s:?}: {v}"); + } + assert_eq!((to_int32(4_294_967_296.0 + 5.0), to_int32(-1.5), to_uint32(-1.0), to_int32(f64::NAN)), (5, -1, 4_294_967_295, 0)); + assert_eq!((run::round(0.49999999999999994), run::round(-0.5), run::round(1.5)), (0.0, 0.0, 2.0)); +} + +#[test] +fn the_ir_reads_and_writes_as_json() { + let c = ok("var n:Number = NaN; var s:String = \"a\"; if (n != n) trace(s + 1, -Infinity); function f(e:MouseEvent = null):void {} btn.addEventListener(MouseEvent.CLICK, f);"); + let v = serde_json::to_value(&c).unwrap(); + let back: Compiled = serde_json::from_value(v.clone()).unwrap(); + assert_eq!(back, c); + let text = v.to_string(); + assert!(text.contains("\"nan\"") && text.contains("{\"inf\":false}") && text.contains("\"s\":\"if\""), "{text}"); } #[test] @@ -218,25 +400,41 @@ fn limits_are_problems_not_crashes() { 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)); + let deep = format!("var a; {}1;", "a = ".repeat(10_000)); assert!(err(&deep).2.contains("nested more than")); + // A long row of operators would make a deep tree; it counts as nesting. + let long = format!("trace({}1);", "1 + ".repeat(10_000)); + let m = err(&long).2; + assert!(m.contains("too many operators in a row") || m.contains("nested more than"), "{m}"); 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))); +} + +/// The deepest code the limits allow runs in a small stack: calls 16 deep, each as nested as +/// the parser lets code be. +#[test] +fn the_deepest_allowed_code_fits_a_small_stack() { + let nest = |depth: usize| format!("{}n{}", "(1 + ".repeat(depth), ")".repeat(depth)); + let mut src = String::from("function f0(n:int):int { return n; }\n"); + for i in 1..20 { + src.push_str(&format!("function f{i}(n:int):int {{ return f{}({}); }}\n", i - 1, nest(18))); } - src.push_str("f15();"); - let t0 = std::time::Instant::now(); - assert!(compile(&src).is_err()); - assert!(t0.elapsed().as_secs_f32() < 5.0); + src.push_str("trace(f19(0));"); + let c = ok(&src); + let r = std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(move || { + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1 + }) + .unwrap() + .join() + .unwrap(); + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("deep")), "{r:?}"); } /// A small deterministic generator (no clock, no randomness crate). @@ -256,20 +454,25 @@ impl Rng { #[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", "@", + const PIECES: [&str; 80] = [ + "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", "@", "while", "do", "break", "continue", "int", "n", "++", "+=", "==", "&&", "||", "Math.random()", "e.keyCode", "stage", "Event.ENTER_FRAME", "removeEventListener", ]; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); let t0 = std::time::Instant::now(); let mut compiled = 0; - for _ in 0..4_000 { + for _ in 0..5_000 { let n = rng.next() as usize % 80; let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect(); - if compile(&src).is_ok() { + if let Ok(c) = compile(&src) { compiled += 1; + // What compiles runs, within its fuel, whatever it is. + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let _ = run::run_script(&mut m, &c.body, &c.inner, 2_000); + for f in &c.functions { + let _ = run::run_listener(&mut m, f, 2_000); + } } } - // Raw bytes as text, too. for _ in 0..1_000 { let n = rng.next() as usize % 200; let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); @@ -286,8 +489,65 @@ fn compiles_once_per_script() { 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()); } + +#[test] +fn trace_lines_are_cut_at_whole_characters() { + let long = "é".repeat(2000); + let cut = run::trace_line(long); + assert_eq!(cut.chars().count(), crate::MAX_TRACE_CHARS + 1); + let emoji = format!("{}{}", "a".repeat(crate::MAX_TRACE_CHARS - 1), "😀".repeat(5)); + assert_eq!(run::trace_line(emoji).encode_utf16().count(), crate::MAX_TRACE_CHARS); +} + +#[test] +fn a_full_budget_runs_quickly() { + let c = ok("var n:int = 0; var s:Number = 0; while (true) { n++; s += Math.abs(n % 7 - 3) * 0.5; }"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + let t0 = std::time::Instant::now(); + let (used, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + eprintln!("{used} fuel in {ms:.2} ms"); + assert_eq!(r, Err(Stop::Fuel)); + assert!(ms < 500.0, "{ms} ms"); +} + +#[test] +fn scripts_set_append_and_read_text_fields() { + let src = r#" + var n:int = 3; + score_txt.text = "Score: " + n; + score_txt.appendText("!"); + score_txt.text += "?"; + trace(score_txt.text, score_txt.length); + panel.name_txt.text = String(score_txt.length * 2); + var text:String = "a variable named text"; + trace(text); + "#; + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("score_txt".into(), String::new()); + m.texts.insert("panel.name_txt".into(), "x".into()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert_eq!(r, Ok(())); + assert_eq!(m.texts["score_txt"], "Score: 3!?"); + assert_eq!(m.texts["panel.name_txt"], "20"); + assert!(m.log.contains(&"Score: 3!? 10".to_string()), "{:?}", m.log); + assert!(m.log.contains(&"a variable named text".to_string()), "a bare `text` stays a variable"); + // Setting null stops the script with a message; `this.text` and the stage aren't fields. + let (_, r, _) = { + let c = ok("score_txt.text = null;"); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("score_txt".into(), String::new()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + ((), r, ()) + }; + assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("not null")), "{r:?}"); + assert!(err("this.text = 'x';").2.contains("isn't a text field")); + assert!(err("stage.text = 'x';").2.contains("text field") || err("stage.text = 'x';").2.contains("stage")); + assert!(err("a_txt.appendText();").2.contains("one argument")); + assert!(err("a_txt.length = 3;").2.contains("can only be read")); +} diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index cbd943a9..621e7b3f 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -19,6 +19,7 @@ anicraft-doc.workspace = true anicraft-engine.workspace = true anicraft-render.workspace = true anicraft-geom.workspace = true +anicraft-guide.workspace = true serde_json.workspace = true [lints] diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42a4cc5b..d87ab681 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -18,10 +18,14 @@ USAGE: anicraft-cli render --out [--frame N] [--scale S] anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S] anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes] + anicraft-cli apng|webp --out [--from A] [--to B] [--scale S] + [--loop forever|N] [--background yes] [--overwrite yes] + full colour with real transparency (WebP: lossless) anicraft-cli commands anicraft-cli run [--save ] anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] + anicraft-cli guide --out writes the user guide as HTML pages (open index.html) anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) anicraft-cli bench --check yes the default scenario against the budgets in docs/performance.md; fails when one is missed @@ -73,6 +77,12 @@ pub fn open_session(src: Option<&str>) -> Result { match src { None => Ok(Session::default()), Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())), + // An Animate document imports as File › Open does (#226), untitled. + Some(p) if anicraft_engine::is_animate(std::path::Path::new(p)) => { + let mut s = Session::default(); + s.execute("file.open", &serde_json::json!({"path": p})).map_err(|e| e.to_string())?; + Ok(s) + } Some(p) => { let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?; let mut s = Session::new(doc); @@ -120,6 +130,12 @@ pub fn run(argv: &[String]) -> Result { let list: Vec = commands().iter().map(|c| c.to_json()).collect(); serde_json::to_string_pretty(&list).map_err(|e| e.to_string()) } + // The user guide as the static HTML book Help › User Guide opens (ADR 0069). + "guide" => { + let out = a.flag("out").ok_or("guide needs --out ")?; + let n = anicraft_guide::write_site(std::path::Path::new(out)).map_err(|e| format!("{out}: {e}"))?; + Ok(format!("wrote {n} files of the user guide to {out}; open {out}/index.html")) + } "info" => { let s = session(&a, Some(src.ok_or("info needs a file or --sample")?))?; serde_json::to_string_pretty(&s.info()).map_err(|e| e.to_string()) @@ -148,9 +164,11 @@ pub fn run(argv: &[String]) -> Result { } exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string()) } - "gif" => { - let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?; - let out = a.flag("out").ok_or("gif needs --out ")?; + "gif" | "apng" | "webp" => { + let mut s = session(&a, Some(src.ok_or(format!("{cmd} needs a file or --sample"))?))?; + let cmd = cmd.as_str(); + let ext = if cmd == "apng" { "png" } else { cmd }; + let out = a.flag("out").ok_or(format!("{cmd} needs --out "))?; let mut p = json!({"path": out}); if let Some(f) = one_based(&a, "from")? { p["from"] = json!(f); @@ -164,7 +182,16 @@ pub fn run(argv: &[String]) -> Result { if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") { p["confirm"] = json!(true); } - exec(&mut s, "file.export_gif", &p).map(|v| v.to_string()) + if cmd != "gif" { + match a.flag("loop") { + None | Some("forever") => {} + Some(n) => p["loop"] = json!(n.parse::().map_err(|_| format!("--loop is forever or how many times it plays, not '{n}'"))?), + } + if a.flag("background").is_some_and(|v| v == "yes" || v == "true") { + p["background"] = json!(true); + } + } + exec(&mut s, &format!("file.export_{cmd}"), &p).map(|v| v.to_string()) } "new" => { let mut s = Session::default(); @@ -457,6 +484,17 @@ pub fn serve(s: &mut Session, input: R, out: &mut W) -> st mod tests { use super::*; + /// #226: `info`, `render` and the other subcommands take an Animate document as File › Open + /// does (an import, untitled), not only `.anicraft` files. + #[test] + fn subcommands_open_animate_documents() { + let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl"); + let s = open_session(Some(&xfl.display().to_string())).unwrap(); + assert!(s.path.is_none() && !s.doc.timeline(0).layers.is_empty()); + let info = run(&["info".to_string(), xfl.display().to_string()]).unwrap(); + assert!(info.contains("\"layers\""), "{info}"); + } + #[test] fn serve_round_trip() { let mut s = Session::default(); @@ -566,5 +604,6 @@ mod tests { assert!(run(&["bogus".into()]).is_err()); assert!(run(&["info".into()]).is_err()); assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe")); + assert!(run(&["guide".into()]).is_err()); } } diff --git a/crates/doc/src/aids.rs b/crates/doc/src/aids.rs new file mode 100644 index 00000000..ff7913e9 --- /dev/null +++ b/crates/doc/src/aids.rs @@ -0,0 +1,135 @@ +//! Drawing aids saved with the document (ADR 0076): each scene's guides, and how the grid and +//! the guides look. Whether they show and snap is the editor's (`anicraft_engine::ViewAids`): +//! a working preference, like Snap to Objects, not part of the artwork. None of this is ever +//! rendered into a picture or an export; the editor's stage draws it. + +use crate::Rgba; +use serde::{Deserialize, Serialize}; + +/// Which way a guide runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum GuideAxis { + /// A horizontal line at `y = at` (dragged from the top ruler). + Horizontal, + /// A vertical line at `x = at` (dragged from the left ruler). + Vertical, +} + +impl GuideAxis { + pub fn key(self) -> &'static str { + match self { + GuideAxis::Horizontal => "horizontal", + GuideAxis::Vertical => "vertical", + } + } + /// `horizontal`/`h` or `vertical`/`v`. + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "horizontal" | "h" => Some(GuideAxis::Horizontal), + "vertical" | "v" => Some(GuideAxis::Vertical), + _ => None, + } + } +} + +/// A guide: a line across the whole stage and pasteboard, in stage pixels from the stage's +/// top-left corner. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Guide { + pub axis: GuideAxis, + pub at: f32, +} + +/// Most guides one scene keeps. +pub const MAX_GUIDES: usize = 1_000; +/// Farthest a guide may be from the stage's corner, in stage pixels (well past any pasteboard). +pub const GUIDE_REACH: f32 = 100_000.0; +/// The grid's spacing range, in stage pixels. +pub const GRID_MIN: f32 = 1.0; +pub const GRID_MAX: f32 = 4_096.0; + +impl Guide { + /// A guide with its position kept in range; `None` for a position that isn't a number. + pub fn new(axis: GuideAxis, at: f32) -> Option { + at.is_finite().then(|| Guide { axis, at: at.clamp(-GUIDE_REACH, GUIDE_REACH) }) + } +} + +/// How the grid looks (View › Grid › Edit Grid). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Grid { + /// Between vertical lines, in stage pixels. + pub spacing_x: f32, + /// Between horizontal lines, in stage pixels. + pub spacing_y: f32, + pub color: Rgba, + /// Drawn over the artwork; off (the default, as in Animate) it shows under it, on the stage. + pub over_objects: bool, +} + +impl Default for Grid { + fn default() -> Self { + Grid { spacing_x: 20.0, spacing_y: 20.0, color: Rgba::hex(0x949494), over_objects: false } + } +} + +impl Grid { + /// Spacing clamped to [`GRID_MIN`]..=[`GRID_MAX`] (non-numbers back to the default). + pub fn sanitized(self) -> Grid { + let sp = |v: f32| if v.is_finite() { v.clamp(GRID_MIN, GRID_MAX) } else { 20.0 }; + Grid { spacing_x: sp(self.spacing_x), spacing_y: sp(self.spacing_y), color: self.color.sanitized(), over_objects: self.over_objects } + } +} + +/// The grid and the guides' looks, saved with the document. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Aids { + pub grid: Grid, + pub guide_color: Rgba, +} + +impl Default for Aids { + fn default() -> Self { + Aids { grid: Grid::default(), guide_color: Rgba::hex(0x3ec8f0) } + } +} + +impl Aids { + pub fn is_default(&self) -> bool { + *self == Aids::default() + } + pub fn sanitized(self) -> Aids { + Aids { grid: self.grid.sanitized(), guide_color: self.guide_color.sanitized() } + } +} + +/// Guides from a file kept to numbers in range, at most [`MAX_GUIDES`]. +pub fn sanitize_guides(guides: &mut Vec) { + guides.retain(|g| g.at.is_finite()); + guides.truncate(MAX_GUIDES); + for g in guides.iter_mut() { + g.at = g.at.clamp(-GUIDE_REACH, GUIDE_REACH); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hostile_values_are_kept_in_range() { + let mut g = vec![Guide { axis: GuideAxis::Vertical, at: f32::NAN }, Guide { axis: GuideAxis::Horizontal, at: 1e30 }]; + g.extend(std::iter::repeat_n(Guide { axis: GuideAxis::Vertical, at: 3.0 }, MAX_GUIDES + 5)); + sanitize_guides(&mut g); + assert_eq!(g.len(), MAX_GUIDES); + assert_eq!(g[0], Guide { axis: GuideAxis::Horizontal, at: GUIDE_REACH }); + let grid = Grid { spacing_x: 0.0, spacing_y: f32::INFINITY, ..Grid::default() }.sanitized(); + assert_eq!((grid.spacing_x, grid.spacing_y), (GRID_MIN, 20.0)); + assert_eq!(Guide::new(GuideAxis::Vertical, f32::NAN), None); + assert_eq!(GuideAxis::parse(" V "), Some(GuideAxis::Vertical)); + assert_eq!(GuideAxis::parse("diagonal"), None); + } +} diff --git a/crates/doc/src/armature.rs b/crates/doc/src/armature.rs index 61d9123d..9af7ce9c 100644 --- a/crates/doc/src/armature.rs +++ b/crates/doc/src/armature.rs @@ -19,6 +19,7 @@ //! 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::skin::{self, Skin}; use crate::{Element, ElementId, Keyframe, Layer}; use anicraft_geom::{Affine, Vec2}; use serde::{Deserialize, Serialize}; @@ -111,6 +112,11 @@ impl Bone { pub struct Armature { #[serde(default)] pub bones: Vec, + /// A shape armature (ADR 0071): the bones are inside this shape and bend its outline. Its + /// bones join joint nodes (ids that are no element) instead of instances; see + /// [`crate::skin`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skin: Option, } impl Armature { @@ -118,6 +124,12 @@ impl Armature { self.bones.is_empty() } + /// The shape a shape armature's bones are inside (ADR 0071); `None` for an armature of + /// symbol instances. + pub fn skin_shape(&self) -> Option { + self.skin.as_ref().map(|s| s.shape) + } + pub fn bone(&self, id: BoneId) -> Option<&Bone> { self.bones.iter().find(|b| b.id == id) } @@ -152,8 +164,12 @@ impl Armature { out } - /// The instances no bone moves (one for an armature made with the Bone tool). + /// The instances no bone moves (one for an armature made with the Bone tool; a shape + /// armature's shape). pub fn roots(&self) -> Vec { + if let Some(s) = self.skin_shape() { + return vec![s]; + } let mut out = Vec::new(); for b in &self.bones { if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) { @@ -210,8 +226,12 @@ impl Armature { kept.push(b); } // Order: a bone after the bone moving its parent. What never gets placed is a cycle. + // A shape armature's bones all hang from its shape. let children: HashSet = kept.iter().map(|b| b.child).collect(); - let mut placed: HashSet = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(); + let mut placed: HashSet = match self.skin_shape() { + Some(s) => HashSet::from([s]), + None => 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 { @@ -227,7 +247,8 @@ impl Armature { } ordered.truncate(MAX_BONES); self.bones = ordered; - self.bones != before + let skin_changed = skin::sanitize(self); + self.bones != before || skin_changed } } @@ -296,19 +317,21 @@ impl Pose { } /// `R(angle)` about point `j`. -fn turn_about(j: Vec2, angle: f32) -> Affine { +pub(crate) 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. +/// keyframe keeps its own transform. A shape armature's joint nodes (ADR 0071) are placed +/// the same way from the shape's transform. pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap { let mut world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + let nodes = arm.skin.is_some(); for b in &arm.bones { let Some(wp) = world.get(&b.parent).copied() else { continue }; - if !world.contains_key(&b.child) { + if !nodes && !world.contains_key(&b.child) { continue; } let j = wp.apply(b.head); @@ -320,12 +343,15 @@ pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap< world } -/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that -/// move are cloned). Returns whether any moved. +/// Puts the instances of `elements` where `pose` has them, and bends a shape armature's shape +/// (copy-on-write: only what changes is cloned). Returns whether anything changed. pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { if arm.is_empty() { return false; } + if arm.skin.is_some() { + return skin::apply(arm, elements, pose); + } let world = place(arm, elements, pose); let mut moved = false; for e in elements.iter_mut() { @@ -372,7 +398,8 @@ pub struct BoneAt { /// 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], pose: &Pose) -> Vec { - let world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + // A shape armature's joint nodes are no elements: forward kinematics places them. + let world: HashMap = if arm.skin.is_some() { place(arm, elements, pose) } else { elements.iter().map(|e| (e.id, e.transform)).collect() }; arm.bones .iter() .filter_map(|b| { @@ -382,6 +409,15 @@ pub fn bones_at(arm: &Armature, elements: &[Arc], pose: &Pose) -> Vec], pose: &Pose, id: BoneId, p: Vec2) -> Option { + let child = arm.bone(id)?.child; + let q = place(arm, elements, pose).get(&child)?.inverse()?.apply(p); + (q.x.is_finite() && q.y.is_finite()).then_some(q) +} + /// What a solve came to. #[derive(Clone, Debug, PartialEq)] pub struct Solved { diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index 56067e98..f2f5d993 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -26,7 +26,7 @@ fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone { /// 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>) { - let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] }; + let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)], skin: None }; (arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)]) } @@ -173,7 +173,7 @@ fn every_export_sees_the_pose() { 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.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: 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); @@ -242,7 +242,7 @@ fn long_chains_and_collinear_targets_converge() { 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 arm = Armature { bones, skin: None }; let last = BoneId(5000 + n as u64 - 1); let reach = 100.0 * n as f32; for k in 0..12 { diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 196de0bd..4df45cf5 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -222,6 +222,7 @@ pub(crate) mod base64_bytes { } } +pub use base64_bytes::decode as base64_decode; pub use base64_bytes::encode as base64_encode; #[cfg(test)] diff --git a/crates/doc/src/camera.rs b/crates/doc/src/camera.rs index 2b6385a7..f3a78f65 100644 --- a/crates/doc/src/camera.rs +++ b/crates/doc/src/camera.rs @@ -11,7 +11,7 @@ //! keeping its size (so a layer at depth 0 moves with the stage, a far background barely moves). //! Everything here is pure: the camera at a frame is a function of the document. -use crate::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements}; +use crate::{ColorEffect, ColorTransform, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements}; use anicraft_geom::{Affine, Decomposed, Vec2}; /// Smallest and largest camera zoom (5 % to 2,000 %). @@ -55,13 +55,17 @@ impl Camera { let center = Vec2::new(fin(d.tx, rest.center.x), fin(d.ty, rest.center.y)); let zoom = fin(d.sx.abs(), 1.0).clamp(MIN_ZOOM, MAX_ZOOM); let rotation = fin(d.rotation, 0.0); - let c = el.color; - Camera { center, zoom, rotation, tint: c.tint.sanitized(), tint_amount: fin(c.tint_amount, 0.0).clamp(0.0, 1.0) } + // The camera's colour effect is a tint (ADR 0027); other styles leave the view as it is. + let (tint, amount) = match el.color { + ColorEffect::Tint { color, amount } => (color.sanitized(), fin(amount, 0.0).clamp(0.0, 1.0)), + _ => (Rgba::WHITE, 0.0), + }; + Camera { center, zoom, rotation, tint, tint_amount: amount } } /// The camera element holding this camera (for commands). pub fn to_element(&self, id: ElementId) -> Element { - Element { id, name: String::new(), transform: self.transform(), color: ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }, kind: ElementKind::Camera } + Element { id, name: String::new(), transform: self.transform(), color: ColorEffect::Tint { color: self.tint, amount: self.tint_amount }, kind: ElementKind::Camera } } /// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`. @@ -70,8 +74,8 @@ impl Camera { } /// The colour effect the camera puts on everything it shows. - pub fn color(&self) -> ColorEffect { - ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount } + pub fn color(&self) -> ColorTransform { + ColorTransform::tint(self.tint, self.tint_amount) } /// Stage space → output space for a layer `depth` pixels behind the stage: the camera's @@ -219,7 +223,7 @@ mod tests { fn hostile_cameras_stay_finite() { let mut el = Camera::rest(&stage()).to_element(ElementId(1)); el.transform = Affine { m: [f32::NAN, 0.0, 0.0, f32::INFINITY, f32::NAN, 1e30] }; - el.color.tint_amount = f32::NAN; + el.color = ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }; let c = Camera::of_element(&el, &stage()); assert!(c.view(&stage(), 0.0).is_finite()); assert!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom)); diff --git a/crates/doc/src/camera_tests.rs b/crates/doc/src/camera_tests.rs index 7854e915..f17f50f1 100644 --- a/crates/doc/src/camera_tests.rs +++ b/crates/doc/src/camera_tests.rs @@ -70,8 +70,7 @@ fn camera_rotation_and_tint_apply_to_the_whole_view() { // Stage point (105, 50) is right of the centre; the camera turned clockwise, so it shows // above the middle. In the square's space that point is (10, 50). assert!(i.transform.apply(Vec2::new(10.0, 50.0)).distance(Vec2::new(100.0, 45.0)) < 1e-3); - assert_eq!(i.color.tint_amount, 0.5); - assert_eq!(i.color.tint, Rgba::hex(0xff0000)); + assert_eq!(i.color, crate::ColorTransform::tint(Rgba::hex(0xff0000), 0.5)); } #[test] @@ -141,7 +140,7 @@ fn the_camera_stays_on_top_alone_and_old_files_read_without_one() { // A symbol's camera layer is a normal layer. let mut sl = Layer::new(LayerId(80), "in symbol"); sl.kind = LayerKind::Camera; - d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); + d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(sl)] } })); d.sanitize(); assert_eq!(d.library[0].timeline.layers[0].kind, LayerKind::Normal); // Depth round-trips, is left out when 0, and an old file reads at 0; hostile depths clamp. diff --git a/crates/doc/src/color_effect.rs b/crates/doc/src/color_effect.rs new file mode 100644 index 00000000..ad099ad3 --- /dev/null +++ b/crates/doc/src/color_effect.rs @@ -0,0 +1,526 @@ +//! Colour effects (ADR 0056): what Animate's Properties calls an instance's colour effect +//! *style* (None, Brightness, Tint, Advanced, Alpha), and the one colour transform every style +//! is (a multiply and an offset per channel). +//! +//! An element stores its [`ColorEffect`] as authored, so Properties shows the style and values +//! the artist chose (a tint keeps its colour at 0 %). Everything that draws works on its +//! [`ColorTransform`]: nested instances, the camera and onion skin compose their transforms +//! exactly (`concat` is the composition of the two maps), and every renderer applies the same +//! arithmetic to straight colour: `c ↦ clamp(c·multiply + offset, 0, 1)`. +//! +//! Brightness `b` is a tint towards white (`b > 0`) or black (`b < 0`) by `|b|`; a tint of +//! colour `t` by amount `k` multiplies each colour channel by `1 − k` and adds `k·t`; alpha +//! multiplies the alpha channel; Advanced is the transform itself (Animate's per-channel +//! percent and −255..255 offset, here as fractions: offset 1 is 255). + +use crate::Rgba; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// A colour transform on straight (not premultiplied) colour: channel `i` (red, green, blue, +/// alpha) becomes `clamp(c·mul[i] + add[i], 0, 1)`. Offsets are fractions of the full range. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorTransform { + pub mul: [f32; 4], + pub add: [f32; 4], +} + +impl Default for ColorTransform { + fn default() -> Self { + ColorTransform::IDENTITY + } +} + +/// Animate's Advanced ranges: multipliers −100..=100 %, offsets −255..=255. +pub const ADVANCED_MUL: std::ops::RangeInclusive = -1.0..=1.0; +pub const ADVANCED_ADD: std::ops::RangeInclusive = -1.0..=1.0; + +fn fin(v: f32, or: f32) -> f32 { + if v.is_finite() { v } else { or } +} + +impl ColorTransform { + pub const IDENTITY: ColorTransform = ColorTransform { mul: [1.0; 4], add: [0.0; 4] }; + + /// Multiplies alpha by `a`. + pub fn alpha(a: f32) -> ColorTransform { + ColorTransform { mul: [1.0, 1.0, 1.0, a], add: [0.0; 4] } + } + /// Mixes colour `t` in by `k` (alpha untouched). + pub fn tint(t: Rgba, k: f32) -> ColorTransform { + let j = 1.0 - k; + ColorTransform { mul: [j, j, j, 1.0], add: [k * t.r, k * t.g, k * t.b, 0.0] } + } + /// Brightness `b` in −1..=1: a tint towards white or black by `|b|`. + pub fn brightness(b: f32) -> ColorTransform { + if b >= 0.0 { ColorTransform::tint(Rgba::WHITE, b) } else { ColorTransform::tint(Rgba::BLACK, -b) } + } + + pub fn is_identity(&self) -> bool { + *self == ColorTransform::IDENTITY + } + + /// `self` applied after `inner`: the effect of `inner` nested inside `self`. Exact (no clamp + /// between the two), so composing then applying is applying one then the other on colours + /// that stay in range. + pub fn concat(&self, inner: &ColorTransform) -> ColorTransform { + let mut out = ColorTransform::IDENTITY; + for i in 0..4 { + out.mul[i] = self.mul[i] * inner.mul[i]; + out.add[i] = self.mul[i] * inner.add[i] + self.add[i]; + } + out + } + + pub fn lerp(&self, o: &ColorTransform, t: f32) -> ColorTransform { + let mut out = ColorTransform::IDENTITY; + for i in 0..4 { + out.mul[i] = anicraft_geom::lerp(self.mul[i], o.mul[i], t); + out.add[i] = anicraft_geom::lerp(self.add[i], o.add[i], t); + } + out + } + + /// Non-finite values drawn as a channel of 0 (as a NaN colour always was). + pub fn sanitized(&self) -> ColorTransform { + let mut out = *self; + for i in 0..4 { + if !(out.mul[i].is_finite() && out.add[i].is_finite()) { + out.mul[i] = 0.0; + out.add[i] = 0.0; + } + } + out + } + + /// The transform applied to straight colour `c`, clamped to `0..=1` (NaN to 0). + pub fn apply(&self, c: Rgba) -> Rgba { + let f = self.sanitized(); + let ch = |v: f32, i: usize| { + let x = fin(v, 0.0) * f.mul[i] + f.add[i]; + if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } + }; + Rgba::new(ch(c.r, 0), ch(c.g, 1), ch(c.b, 2), ch(c.a, 3)) + } + + /// The alpha multiplier when alpha is only multiplied (no alpha offset): what can fade a + /// whole group at once. + pub fn alpha_factor(&self) -> Option { + (self.add[3] == 0.0).then(|| fin(self.mul[3], 0.0).clamp(0.0, 1.0)) + } + + /// The same transform with alpha untouched. + pub fn without_alpha(&self) -> ColorTransform { + let mut out = *self; + out.mul[3] = 1.0; + out.add[3] = 0.0; + out + } + + /// Whether colour channels change (anything beyond alpha). + pub fn changes_colour(&self) -> bool { + self.mul[..3].iter().any(|m| *m != 1.0) || self.add[..3].iter().any(|a| *a != 0.0) + } + + /// The alpha multiplier as an opacity estimate `0..=1` (picking, outlines). + pub fn opacity(&self) -> f32 { + fin(self.mul[3] + self.add[3], 0.0).clamp(0.0, 1.0) + } +} + +/// The colour effect styles of Properties' Style menu, in menu order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ColorStyle { + None, + Brightness, + Tint, + Advanced, + Alpha, +} + +impl ColorStyle { + pub const ALL: [ColorStyle; 5] = [ColorStyle::None, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]; + + /// The name used in files and commands. + pub fn key(self) -> &'static str { + match self { + ColorStyle::None => "none", + ColorStyle::Brightness => "brightness", + ColorStyle::Tint => "tint", + ColorStyle::Advanced => "advanced", + ColorStyle::Alpha => "alpha", + } + } + pub fn label(self) -> &'static str { + match self { + ColorStyle::None => "None", + ColorStyle::Brightness => "Brightness", + ColorStyle::Tint => "Tint", + ColorStyle::Advanced => "Advanced", + ColorStyle::Alpha => "Alpha", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase(); + ColorStyle::ALL.into_iter().find(|x| x.key() == s) + } +} + +/// An element's colour effect, as authored: one style and its values. Draw it through +/// [`ColorEffect::transform`]. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub enum ColorEffect { + #[default] + None, + /// Brightness −1..=1 (−100..=100 %). + Brightness(f32), + /// Tint colour (opaque) and amount 0..=1. + Tint { color: Rgba, amount: f32 }, + /// Per-channel multiply and offset (Animate's Advanced). + Advanced(ColorTransform), + /// Alpha multiplier 0..=1. + Alpha(f32), +} + +impl ColorEffect { + pub fn style(&self) -> ColorStyle { + match self { + ColorEffect::None => ColorStyle::None, + ColorEffect::Brightness(_) => ColorStyle::Brightness, + ColorEffect::Tint { .. } => ColorStyle::Tint, + ColorEffect::Advanced(_) => ColorStyle::Advanced, + ColorEffect::Alpha(_) => ColorStyle::Alpha, + } + } + + /// What it does to colour (its values clamped into the style's range first). + pub fn transform(&self) -> ColorTransform { + match self.sanitized() { + ColorEffect::None => ColorTransform::IDENTITY, + ColorEffect::Brightness(b) => ColorTransform::brightness(b), + ColorEffect::Tint { color, amount } => ColorTransform::tint(color, amount), + ColorEffect::Advanced(t) => t, + ColorEffect::Alpha(a) => ColorTransform::alpha(a), + } + } + + /// The values clamped into each style's range, non-finite ones to the style's rest value. + pub fn sanitized(&self) -> ColorEffect { + match *self { + ColorEffect::None => ColorEffect::None, + ColorEffect::Brightness(b) => ColorEffect::Brightness(fin(b, 0.0).clamp(-1.0, 1.0)), + ColorEffect::Tint { color, amount } => ColorEffect::Tint { color: color.sanitized().with_alpha(1.0), amount: fin(amount, 0.0).clamp(0.0, 1.0) }, + ColorEffect::Advanced(t) => { + let mut o = t; + for i in 0..4 { + o.mul[i] = fin(t.mul[i], 1.0).clamp(*ADVANCED_MUL.start(), *ADVANCED_MUL.end()); + o.add[i] = fin(t.add[i], 0.0).clamp(*ADVANCED_ADD.start(), *ADVANCED_ADD.end()); + } + ColorEffect::Advanced(o) + } + ColorEffect::Alpha(a) => ColorEffect::Alpha(fin(a, 1.0).clamp(0.0, 1.0)), + } + } + + /// The alpha multiplier the effect has (1 for styles that leave alpha alone). + pub fn alpha(&self) -> f32 { + self.transform().mul[3] + } + + /// The effect with its alpha multiplier set to `a`, the rest kept (what ActionScript's + /// `alpha` and `element.set_alpha` do): None and Alpha become Alpha(a); Advanced keeps + /// its other channels; Brightness and Tint become Advanced when `a` isn't 1. + pub fn with_alpha(&self, a: f32) -> ColorEffect { + match *self { + ColorEffect::None | ColorEffect::Alpha(_) => ColorEffect::Alpha(a), + ColorEffect::Advanced(mut t) => { + t.mul[3] = a; + ColorEffect::Advanced(t) + } + ColorEffect::Brightness(_) | ColorEffect::Tint { .. } if a == 1.0 => *self, + ColorEffect::Brightness(_) | ColorEffect::Tint { .. } => { + let mut t = self.transform(); + t.mul[3] = a; + ColorEffect::Advanced(t) + } + } + } + + /// The effect in `style`, as close to this one as that style can be: Advanced is exactly + /// this transform; Alpha keeps the alpha multiplier; a tint keeps its colour; Brightness and + /// Tint otherwise start where they change nothing (the look doesn't jump when the style + /// changes, except to None). + pub fn to_style(&self, style: ColorStyle) -> ColorEffect { + if self.style() == style { + return *self; + } + match style { + ColorStyle::None => ColorEffect::None, + ColorStyle::Advanced => ColorEffect::Advanced(self.transform()), + ColorStyle::Alpha => ColorEffect::Alpha(fin(self.alpha(), 1.0).clamp(0.0, 1.0)), + ColorStyle::Brightness => ColorEffect::Brightness(0.0), + ColorStyle::Tint => ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }, + } + } + + /// `inner` nested inside `self` as one effect (Break Apart): the other when either is None, + /// alphas multiplied, else the composed transform as Advanced. + pub fn nested(&self, inner: &ColorEffect) -> ColorEffect { + match (self, inner) { + (ColorEffect::None, x) | (x, ColorEffect::None) => *x, + (ColorEffect::Alpha(a), ColorEffect::Alpha(b)) => ColorEffect::Alpha(a * b), + (o, i) => ColorEffect::Advanced(o.transform().concat(&i.transform())), + } + } + + /// Alpha `a`, or None at full opacity. + pub fn opacity(a: f32) -> ColorEffect { + if a < 1.0 { ColorEffect::Alpha(a) } else { ColorEffect::None } + } + + /// The classic tween between two effects: within one style its values travel (a tint's + /// colour and amount); None meets any style as that style's rest value; any other change of + /// style travels in the Advanced space (multiplies and offsets), as in Animate. + pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { + use anicraft_geom::lerp; + let rest = |s: ColorStyle| ColorEffect::None.to_style(s); + let (a, b) = match (self, o) { + (ColorEffect::None, ColorEffect::None) => return ColorEffect::None, + (ColorEffect::None, x) if x.style() != ColorStyle::Advanced => (rest(x.style()), *x), + (x, ColorEffect::None) if x.style() != ColorStyle::Advanced => (*x, rest(x.style())), + (x, y) => (*x, *y), + }; + // A tint meeting None keeps its colour all the way. + let (a, b) = match (a, b) { + (ColorEffect::Tint { amount, .. }, ColorEffect::Tint { color, amount: k }) if self.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }), + (ColorEffect::Tint { color, amount }, ColorEffect::Tint { amount: k, .. }) if o.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }), + p => p, + }; + match (a, b) { + (ColorEffect::Brightness(x), ColorEffect::Brightness(y)) => ColorEffect::Brightness(lerp(x, y, t)), + (ColorEffect::Alpha(x), ColorEffect::Alpha(y)) => ColorEffect::Alpha(lerp(x, y, t)), + (ColorEffect::Tint { color: c1, amount: k1 }, ColorEffect::Tint { color: c2, amount: k2 }) => ColorEffect::Tint { color: c1.lerp(c2, t), amount: lerp(k1, k2, t) }, + (x, y) => ColorEffect::Advanced(x.transform().lerp(&y.transform(), t)), + } + } + + /// The effect several families make together (a motion tween keying more than one, or an + /// older file's alpha with a tint): the one family when only one is in use, else Advanced + /// with them composed (alpha outermost, then brightness, tint, advanced). + pub fn compose(alpha: Option, brightness: Option, tint: Option<(Rgba, f32)>, advanced: Option) -> ColorEffect { + let n = usize::from(alpha.is_some()) + usize::from(brightness.is_some()) + usize::from(tint.is_some()) + usize::from(advanced.is_some()); + if n == 1 { + if let Some(a) = alpha { + return ColorEffect::Alpha(a); + } + if let Some(b) = brightness { + return ColorEffect::Brightness(b); + } + if let Some((color, amount)) = tint { + return ColorEffect::Tint { color, amount }; + } + if let Some(t) = advanced { + return ColorEffect::Advanced(t); + } + } + if n == 0 { + return ColorEffect::None; + } + let mut t = advanced.unwrap_or(ColorTransform::IDENTITY); + if let Some((c, k)) = tint { + t = ColorTransform::tint(c, k).concat(&t); + } + if let Some(b) = brightness { + t = ColorTransform::brightness(b).concat(&t); + } + if let Some(a) = alpha { + t = ColorTransform::alpha(a).concat(&t); + } + ColorEffect::Advanced(t) + } +} + +// ----- files --------------------------------------------------------------------------------- +// +// Every effect is written with the fields older AniCraft files have (`alpha`, `tint`, +// `tint_amount`: the look as near as they can say it), so None, Alpha and Tint effects are +// written exactly as before. `style` (and `brightness`, `multiply`, `offset`) are added only +// when those fields alone would read back as something else. A file without `style` reads as +// it always looked: a tint, an alpha, both (Advanced), or none. + +fn one() -> f32 { + 1.0 +} +fn white() -> Rgba { + Rgba::WHITE +} + +#[derive(Serialize, Deserialize)] +struct Wire { + #[serde(default = "one")] + alpha: f32, + #[serde(default = "white")] + tint: Rgba, + #[serde(default)] + tint_amount: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + style: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + brightness: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + multiply: Option<[f32; 4]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + offset: Option<[f32; 4]>, +} + +/// What the legacy fields alone say. +fn legacy(alpha: f32, tint: Rgba, amount: f32) -> ColorEffect { + // Older builds clamped these where they drew them. + let (alpha, amount) = (fin(alpha, 1.0).clamp(0.0, 1.0), fin(amount, 0.0).clamp(0.0, 1.0)); + let a = (alpha != 1.0).then_some(alpha); + let t = (amount != 0.0).then_some((tint, amount)); + ColorEffect::compose(a, None, t, None) +} + +impl Serialize for ColorEffect { + fn serialize(&self, s: S) -> Result { + let mut w = Wire { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0, style: None, brightness: None, multiply: None, offset: None }; + match *self { + ColorEffect::None => {} + ColorEffect::Alpha(a) => w.alpha = a, + ColorEffect::Tint { color, amount } => (w.tint, w.tint_amount) = (color, amount), + ColorEffect::Brightness(b) => { + (w.tint, w.tint_amount) = (if b >= 0.0 { Rgba::WHITE } else { Rgba::BLACK }, b.abs()); + w.brightness = Some(b); + } + ColorEffect::Advanced(t) => { + w.alpha = t.mul[3]; + (w.multiply, w.offset) = (Some(t.mul), Some(t.add)); + } + } + if legacy(w.alpha, w.tint, w.tint_amount) != *self { + w.style = Some(self.style().key().to_string()); + } + w.serialize(s) + } +} + +impl<'de> Deserialize<'de> for ColorEffect { + fn deserialize>(d: D) -> Result { + let w = Wire::deserialize(d)?; + let fx = match w.style.as_deref().and_then(ColorStyle::from_key) { + None => legacy(w.alpha, w.tint, w.tint_amount), + Some(ColorStyle::None) => ColorEffect::None, + Some(ColorStyle::Alpha) => ColorEffect::Alpha(w.alpha), + Some(ColorStyle::Tint) => ColorEffect::Tint { color: w.tint, amount: w.tint_amount }, + Some(ColorStyle::Brightness) => ColorEffect::Brightness(w.brightness.unwrap_or(0.0)), + Some(ColorStyle::Advanced) => ColorEffect::Advanced(ColorTransform { mul: w.multiply.unwrap_or([1.0; 4]), add: w.offset.unwrap_or([0.0; 4]) }), + }; + Ok(fx.sanitized()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: Rgba, b: Rgba) -> bool { + (a.r - b.r).abs() < 1e-5 && (a.g - b.g).abs() < 1e-5 && (a.b - b.b).abs() < 1e-5 && (a.a - b.a).abs() < 1e-5 + } + + #[test] + fn styles_are_the_transforms_animate_documents() { + let c = Rgba::new(0.4, 0.2, 0.8, 1.0); + // Brightness +60 %: towards white; −50 %: towards black. + assert!(close(ColorEffect::Brightness(0.6).transform().apply(c), Rgba::new(0.4 * 0.4 + 0.6, 0.2 * 0.4 + 0.6, 0.8 * 0.4 + 0.6, 1.0))); + assert!(close(ColorEffect::Brightness(-0.5).transform().apply(c), Rgba::new(0.2, 0.1, 0.4, 1.0))); + // Tint 25 % red. + let t = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.25 }.transform().apply(c); + assert!(close(t, Rgba::new(0.4 * 0.75 + 0.25, 0.15, 0.6, 1.0))); + // Advanced: red ×50 %, green +51 (0.2), alpha ×80 % −25.5 (−0.1); clamped. + let adv = ColorTransform { mul: [0.5, 1.0, 1.0, 0.8], add: [0.0, 0.2, 0.5, -0.1] }; + assert!(close(adv.apply(c), Rgba::new(0.2, 0.4, 1.0, 0.7))); + assert!(close(ColorEffect::Alpha(0.3).transform().apply(c), c.with_alpha(0.3))); + } + + #[test] + fn composition_is_exact() { + let outer = ColorTransform::tint(Rgba::new(0.0, 0.5, 1.0, 1.0), 0.4); + let inner = ColorTransform { mul: [0.5, -0.2, 0.9, 0.7], add: [0.1, 0.6, 0.0, 0.05] }; + let c = Rgba::new(0.3, 0.6, 0.2, 0.9); + assert!(close(outer.concat(&inner).apply(c), outer.apply(inner.apply(c)))); + assert_eq!(ColorTransform::IDENTITY.concat(&inner), inner); + assert_eq!(inner.concat(&ColorTransform::IDENTITY), inner); + } + + #[test] + fn nan_draws_a_zero_channel() { + let t = ColorTransform { mul: [f32::NAN, 1.0, 1.0, 1.0], add: [0.0; 4] }; + assert_eq!(t.apply(Rgba::WHITE), Rgba::new(0.0, 1.0, 1.0, 1.0)); + assert_eq!(ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }.sanitized(), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }); + } + + #[test] + fn tweens_within_a_style_and_across_styles() { + let red = Rgba::new(1.0, 0.0, 0.0, 1.0); + let blue = Rgba::new(0.0, 0.0, 1.0, 1.0); + assert_eq!(ColorEffect::Alpha(1.0).lerp(&ColorEffect::Alpha(0.0), 0.25), ColorEffect::Alpha(0.75)); + assert_eq!(ColorEffect::None.lerp(&ColorEffect::Brightness(-1.0), 0.5), ColorEffect::Brightness(-0.5)); + assert_eq!(ColorEffect::None.lerp(&ColorEffect::Tint { color: red, amount: 1.0 }, 0.5), ColorEffect::Tint { color: red, amount: 0.5 }); + assert_eq!(ColorEffect::Tint { color: red, amount: 1.0 }.lerp(&ColorEffect::Tint { color: blue, amount: 1.0 }, 0.5), ColorEffect::Tint { color: Rgba::new(0.5, 0.0, 0.5, 1.0), amount: 1.0 }); + // A style change travels in the advanced space: halfway between the two transforms. + let a = ColorEffect::Tint { color: red, amount: 1.0 }; + let b = ColorEffect::Alpha(0.5); + let mid = a.lerp(&b, 0.5); + assert_eq!(mid.style(), ColorStyle::Advanced); + assert_eq!(mid.transform(), a.transform().lerp(&b.transform(), 0.5)); + // The ends look like the keyframes. + assert_eq!(a.lerp(&b, 0.0).transform(), a.transform()); + assert_eq!(a.lerp(&b, 1.0).transform(), b.transform()); + } + + #[test] + fn style_changes_keep_the_look_where_they_can() { + let fx = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.4 }; + assert_eq!(fx.to_style(ColorStyle::Advanced).transform(), fx.transform()); + assert_eq!(ColorEffect::Alpha(0.3).to_style(ColorStyle::Advanced).alpha(), 0.3); + assert_eq!(ColorEffect::Advanced(ColorTransform::alpha(0.3)).to_style(ColorStyle::Alpha), ColorEffect::Alpha(0.3)); + assert!(fx.to_style(ColorStyle::Brightness).transform().is_identity()); + assert_eq!(fx.with_alpha(0.5).transform(), ColorTransform::alpha(0.5).concat(&fx.transform())); + assert_eq!(fx.with_alpha(1.0), fx); + assert_eq!(ColorEffect::None.with_alpha(0.2), ColorEffect::Alpha(0.2)); + } + + #[test] + fn older_files_read_as_they_looked_and_simple_effects_write_as_before() { + let read = |s: &str| serde_json::from_str::(s).unwrap(); + let white = r#""tint":{"r":1.0,"g":1.0,"b":1.0,"a":1.0}"#; + assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)), ColorEffect::None); + assert_eq!(read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)), ColorEffect::Alpha(0.5)); + assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.25}}"#)), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.25 }); + let both = read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.25}}"#)); + assert_eq!(both.transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::WHITE, 0.25))); + // Byte for byte as before. + assert_eq!(serde_json::to_string(&ColorEffect::None).unwrap(), format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)); + assert_eq!(serde_json::to_string(&ColorEffect::Alpha(0.5)).unwrap(), format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)); + for fx in [ + ColorEffect::None, + ColorEffect::Alpha(1.0), + ColorEffect::Alpha(0.25), + ColorEffect::Brightness(-0.5), + ColorEffect::Brightness(0.0), + ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.0 }, + ColorEffect::Tint { color: Rgba::new(0.0, 0.5, 1.0, 1.0), amount: 0.75 }, + ColorEffect::Advanced(ColorTransform { mul: [0.5, -1.0, 1.0, 0.75], add: [0.25, 0.0, -0.5, 0.125] }), + ColorEffect::Advanced(ColorTransform::IDENTITY), + ] { + let json = serde_json::to_string(&fx).unwrap(); + assert_eq!(read(&json), fx, "{json}"); + } + // Brightness still reads, in older builds, as the tint it looks like. + let json = serde_json::to_string(&ColorEffect::Brightness(-0.5)).unwrap(); + assert!(json.contains(r#""tint_amount":0.5"#) && json.contains(r#""style":"brightness""#), "{json}"); + // Out-of-range values in a file are clamped; an unknown style reads as the legacy fields. + assert_eq!(read(r#"{"style":"brightness","brightness":7}"#), ColorEffect::Brightness(1.0)); + assert_eq!(read(r#"{"style":"sepia","alpha":0.5}"#), ColorEffect::Alpha(0.5)); + } +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8fb0a447..8351b331 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1,8 +1,9 @@ //! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching. use crate::camera::Camera; +use crate::nine_slice::Slicing; use crate::player::PlayerState; -use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; +use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; use anicraft_geom::walk::PathWalk; use anicraft_geom::{Affine, FillRule, Path}; use std::borrow::Cow; @@ -20,7 +21,8 @@ pub struct DisplayItem { pub fill: Option, pub stroke: Option, pub fill_rule: FillRule, - pub color: ColorEffect, + /// The colour transform of every instance around it, composed (ADR 0056). + pub color: ColorTransform, /// The top-level layer and element this item came from (for picking). pub layer: LayerId, pub element: ElementId, @@ -28,11 +30,13 @@ pub struct DisplayItem { pub outline: Option, /// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]). pub clip: Option, - /// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip. + /// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity + /// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as + /// drawn. pub masks: Option, /// Guide artwork: shown while editing, never in output. pub guide: bool, - /// The innermost group this item fades with (see [`DisplayList::groups`]); `color.alpha` + /// The innermost group this item fades with (see [`DisplayList::groups`]); `color` /// leaves out the groups' opacity. pub group: Option, /// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied). @@ -40,6 +44,10 @@ pub struct DisplayItem { /// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050); /// off, each pixel is a hard-edged square. pub smooth: bool, + /// A warped bitmap fill (ADR 0079): the mesh, in the item's local space, that carries the + /// image as drawn (`rest`) to where it shows (`shown`); renderers draw the image through + /// its triangles. `None` for everything else (a warped shape's path is already bent). + pub warp: Option>, } /// Back-to-front list of shapes. @@ -49,6 +57,9 @@ pub struct DisplayList { /// One entry per clip: the enclosing clip it is intersected with. A parent always has a /// lower index than its children. A clip with no mask artwork hides everything in it. pub clip_parents: Vec>, + /// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end + /// is [`MaskMode::Coverage`], so lists that don't care leave it empty. + pub clip_modes: Vec, /// Groups that fade as one: a symbol instance with an opacity below 1 composites its /// items together, then blends the result at `alpha`, so overlapping parts don't show /// through each other. A group's items are one unbroken run of `items`, nested runs for @@ -70,10 +81,28 @@ pub struct Group { } impl DisplayList { + /// How clip `c`'s artwork reveals (coverage when unset). + pub fn clip_mode(&self, c: u32) -> MaskMode { + self.clip_modes.get(c as usize).copied().unwrap_or_default() + } + + /// Sets clip `c`'s mode (only a soft mode is stored; coverage stays implicit). + pub fn set_clip_mode(&mut self, c: u32, mode: MaskMode) { + let i = c as usize; + if mode.is_soft() && i < self.clip_parents.len() { + if self.clip_modes.len() <= i { + self.clip_modes.resize(i + 1, MaskMode::Coverage); + } + if let Some(m) = self.clip_modes.get_mut(i) { + *m = mode; + } + } + } + /// The opacity an item ends up with: its own times every group's it is in (what an item /// looks like when nothing overlaps it; also what picking and outlines use). pub fn effective_alpha(&self, item: &DisplayItem) -> f32 { - let mut a = item.color.alpha; + let mut a = item.color.opacity(); let mut g = item.group; for _ in 0..self.groups.len() { let Some(id) = g else { break }; @@ -105,6 +134,9 @@ impl DisplayList { let gbase = self.groups.len() as u32; let gshift = |g: Option| g.map(|g| g + gbase); self.clip_parents.extend(other.clip_parents.into_iter().map(shift)); + for (i, m) in other.clip_modes.into_iter().enumerate() { + self.set_clip_mode(base + i as u32, m); + } self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) })); self.items.extend(other.items.into_iter().map(|mut i| { i.clip = shift(i.clip); @@ -176,6 +208,7 @@ pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Aff let mut out = DisplayList::default(); let mut cx = Ctx::top(xf); cx.depth = 1; + cx.stage = false; eval_timeline(doc, tl, frame, &cx, &mut out, play); out } @@ -258,7 +291,14 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option { let kind = match (&a.kind, &b.kind) { (ElementKind::Shape(sa), ElementKind::Shape(sb)) => { - let path = if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() { + // Warped on both keyframes (ADR 0079): the pins tween and bend the outline as drawn. + let warp = match (sa.live_warp(), sb.live_warp()) { + (Some(wa), Some(wb)) if !morph || hints.is_empty() => wa.lerp(wb, t), + _ => None, + }; + let path = if let Some(w) = &warp { + w.outline() + } else if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() { sa.path.clone() } else if morph { anicraft_geom::morph::morph_hinted(&sa.path, &sb.path, hints, t).map(Arc::new).unwrap_or_else(|| sa.path.clone()) @@ -273,12 +313,33 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft (Some(x), Some(y)) => Some(x.lerp(y, t)), (x, _) => x.clone(), }; - ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge }) + let warp = match warp { + Some(mut w) => { + w.shown = crate::warp::fingerprint(&path); + Some(Arc::new(w)) + } + // Not tweening the pins: the shape keeps its warp only while it shows it. + None => sa.warp.clone().filter(|w| w.shows(&path)), + }; + ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp }) } (ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(), // Text tweens its placement and colour effect; the words stay the first keyframe's. (ElementKind::Text(_), ElementKind::Text(_)) => a.kind.clone(), (ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera, + // A group tweens its placement and colour effect, and its members pair by order, layer by + // layer, tweening as they would on their own (ADR 0073); a member without a partner holds. + (ElementKind::Group { members: ma }, ElementKind::Group { members: mb }) => { + let mut members = ma.clone(); + for (la, lb) in members.layers.iter_mut().zip(&mb.layers) { + let (Some(ka), Some(kb)) = (la.keyframe_at(0), lb.keyframe_at(0)) else { continue }; + let els: Vec> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, t, morph, &[], None)).map_or_else(|| x.clone(), Arc::new)).collect(); + if let Some(k) = Arc::make_mut(la).keyframe_mut(0) { + k.elements = els; + } + } + ElementKind::Group { members } + } _ => return None, }; let mut transform = a.transform.decompose().lerp(&b.transform.decompose(), t).compose(); @@ -293,11 +354,14 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft struct Ctx { /// Local → stage transform and colour effect of the enclosing instance. xf: Affine, - color: ColorEffect, + color: ColorTransform, depth: usize, /// The top-level layer and element everything inside belongs to (for picking). root: Option<(LayerId, ElementId)>, outline: Option, + /// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for + /// the movie (every export, the player): View as Outlines is an editing aid. + stage: bool, /// The clip everything inside is drawn within. clip: Option, /// Set while evaluating mask artwork: everything inside forms this clip. @@ -309,16 +373,20 @@ struct Ctx { /// The camera the scene's layers are seen through (main timeline only; each layer's /// transform comes from it and the layer's depth, and `xf` is ignored). camera: Option, + /// The 9-slice scaling of the instance whose timeline this is (ADR 0055): its own shapes go + /// through it, in place of the scale in `xf`. Not passed on to nested symbols. + slice: Option, } impl Ctx { fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None } + Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. fn through(camera: Option) -> Ctx { let mut cx = Ctx::top(Affine::IDENTITY); + cx.stage = false; if let Some(c) = camera { cx.color = c.color(); cx.camera = Some(c); @@ -357,7 +425,7 @@ pub fn guide_walk(guide: &Layer, frame: u32) -> Option { } PathWalk::new(&pts) } - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, }) } @@ -388,8 +456,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut let mut clips: Vec<(LayerId, u32)> = Vec::new(); if cx.masks.is_none() { for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) { - clips.push((layer.id, out.clip_parents.len() as u32)); + let c = out.clip_parents.len() as u32; + clips.push((layer.id, c)); out.clip_parents.push(cx.clip); + out.set_clip_mode(c, layer.mask_mode); } } let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c); @@ -413,104 +483,278 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut // A layer guided by a guide layer: its tweens follow the guide's first path. let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame)); let Some((kf_start, elements)) = evaluate_guided(layer, frame, walk.as_ref()) else { continue }; - let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None }); + let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None }); // Through a camera, each layer is placed by the camera and its own depth. let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth)); + let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf }; for el in elements.iter() { - // In the player, a symbol instance has its own path, and maybe properties a script set. - let child = match (&el.kind, play) { - (ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)), - _ => None, + eval_element(doc, cx, &lc, el, out, play); + } + } +} + +/// The layer an element is drawn on, as [`eval_element`] needs it. +#[derive(Clone, Copy)] +struct LayerCtx<'a> { + layer: &'a Layer, + frame: u32, + /// The first frame of the keyframe the element is on. + kf_start: u32, + clip: Option, + masks: Option, + guide: bool, + outline: Option, + /// The layer's space (and, inside a group, the group's) to stage space. + xf: Affine, +} + +fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) { + let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc; + // In the player, a symbol instance has its own path, and maybe properties a script set. + let child = match (&el.kind, play) { + (ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)), + // So is a dynamic or input text field (ADR 0066). + (ElementKind::Text(t), Some(p)) if t.field.is_some() => Some(p.child(el.id)), + _ => None, + }; + let set; + let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) { + Some(ov) if !ov.shown() => return, + Some(ov) => { + set = ov.apply(el); + &set + } + None => el, + }; + let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id)); + let xf = layer_xf.mul(&el.transform); + let fx = el.color.transform(); + let color = cx.color.concat(&fx); + match &el.kind { + ElementKind::Shape(s) => { + // Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap + // fills scale normally, as in Animate). + let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl)); + let is_sliced = sliced.is_some(); + let (path, transform, fill, stroke) = match sliced { + Some(x) => x, + None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()), }; - let set; - let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) { - Some(ov) if !ov.shown() => continue, - Some(ov) => { - set = ov.apply(el); - &set + out.items.push(DisplayItem { + path, + transform, + fill, + stroke, + fill_rule: s.fill_rule, + color, + layer: root_layer, + element: root_el, + outline: layer_outline, + clip, + masks, + guide, + group: cx.group, + image: match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels), + _ => None, + }, + smooth: match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), + _ => true, + }, + // A bitmap bent by its warp is drawn through the mesh (ADR 0079). + warp: match &s.fill { + Some(Paint::Bitmap { .. }) if !is_sliced => s.live_warp().filter(|w| !w.at_rest()).and_then(crate::warp::Warp::mesh).map(Arc::new), + _ => None, + }, + }); + } + ElementKind::Text(t) => { + let item = |path: Arc, transform: Affine, fill: Option, stroke: Option, clip: Option, masks: Option| DisplayItem { + path, + transform, + fill, + stroke, + fill_rule: FillRule::NonZero, + color, + layer: root_layer, + element: root_el, + outline: layer_outline, + clip, + masks, + guide, + group: cx.group, + image: None, + smooth: true, + warp: None, + }; + match &t.field { + // Mask artwork: a field's text masks; its box and border don't. + Some(f) if masks.is_none() => { + let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice()))); + field_items(t, f, live, xf, clip, out, item); } - None => el, - }; - let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id)); - let xf = layer_xf.mul(&el.transform); - let color = cx.color.concat(&el.color); - match &el.kind { - ElementKind::Shape(s) => out.items.push(DisplayItem { - path: s.path.clone(), - transform: xf, - fill: s.fill.clone(), - stroke: s.stroke.clone(), - fill_rule: s.fill_rule, - color, - layer: root_layer, - element: root_el, - outline: layer_outline, - clip, - masks, - guide, - group: cx.group, - image: match &s.fill { - Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels), - _ => None, - }, - smooth: match &s.fill { - Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), - _ => true, - }, - }), - ElementKind::Text(t) => out.items.push(DisplayItem { - path: t.outline.clone(), - transform: xf, - fill: Some(Paint::Solid(t.color)), - stroke: None, - fill_rule: FillRule::NonZero, - color, - layer: root_layer, - element: root_el, - outline: layer_outline, - clip, - masks, - guide, - group: cx.group, - image: None, - smooth: true, - }), - ElementKind::Camera => {} - ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { - let Some(sym) = doc.symbol(*symbol) else { continue }; - let len = sym.timeline.frame_count(); - let local = match (sym.kind, &child) { - // A graphic keeps step with this timeline: loop mode and first frame apply. - (SymbolKind::Graphic, _) => loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, len), - // In the player, movie clips and buttons are where it has them. - (SymbolKind::MovieClip, Some(c)) => c.state.clip_frame(&c.path, len), - (SymbolKind::Button, Some(c)) => c.state.button_frame(&c.path, len), - // A movie clip plays its own timeline on a loop from when the instance - // appeared, carrying on across keyframes that hold the same instance. - (SymbolKind::MovieClip, None) => frame.saturating_sub(instance_start(layer, frame, el.id, *symbol)) % len.max(1), - // While editing, a button shows its Up frame. - (SymbolKind::Button, None) => 0, - }; - // An instance below full opacity fades as one: its contents composite in a - // group at full opacity, and the group blends at the instance's alpha. (Mask - // artwork ignores opacity, so it never needs one.) - // A blend mode composites the instance on its own too, then blends it. - let fade = el.color.alpha.clamp(0.0, 1.0); - let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) { - let gid = out.groups.len() as u32; - out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip }); - (cx.color.concat(&ColorEffect { alpha: 1.0, ..el.color }), Some(gid)) - } else { - (color, cx.group) - }; - let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None }; - eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); + _ => { + let path = child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()).map_or_else(|| t.outline.clone(), |l| l.outline.clone()); + out.items.push(item(path, xf, Some(Paint::Solid(t.color)), None, clip, masks)); } } } + ElementKind::Camera => {} + // A group (ADR 0073): its members, placed and coloured by it, as if they stood on its layer + // (graphics and movie clips inside keep time with it), picked as it. Below full opacity it + // fades as one, as an instance does. + ElementKind::Group { members } => { + if cx.depth > MAX_SYMBOL_DEPTH + crate::MAX_GROUP_DEPTH { + return; + } + let fade = fx.alpha_factor().unwrap_or(1.0); + let (color, group) = if masks.is_none() && fade < 1.0 - 1e-4 { + let gid = out.groups.len() as u32; + out.groups.push(Group { parent: cx.group, alpha: fade, blend: crate::BlendMode::Normal, filters: Arc::from(Vec::new()), clip }); + (cx.color.concat(&fx.without_alpha()), Some(gid)) + } else { + (color, cx.group) + }; + let inner = Ctx { color, depth: cx.depth + 1, root: Some((root_layer, root_el)), group, slice: None, camera: None, ..*cx }; + let lc = LayerCtx { xf, ..*lc }; + for m in members.layers.iter().rev().filter(|l| l.visible && l.kind != LayerKind::Guide).filter_map(|l| l.keyframe_at(0)).flat_map(|k| k.elements.iter()) { + eval_element(doc, &inner, &lc, m, out, play); + } + } + ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { + let Some(sym) = doc.symbol(*symbol) else { return }; + let len = sym.timeline.frame_count(); + let local = match (sym.kind, &child) { + // A graphic keeps step with this timeline: loop mode and first frame apply. + (SymbolKind::Graphic, _) => loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, len), + // In the player, movie clips and buttons are where it has them. + (SymbolKind::MovieClip, Some(c)) => c.state.clip_frame(&c.path, len), + (SymbolKind::Button, Some(c)) => c.state.button_frame(&c.path, len), + // A movie clip plays its own timeline on a loop from when the instance + // appeared, carrying on across keyframes that hold the same instance. + (SymbolKind::MovieClip, None) => frame.saturating_sub(instance_start(layer, frame, el.id, *symbol)) % len.max(1), + // While editing, a button shows its Up frame. + (SymbolKind::Button, None) => 0, + }; + // An instance below full opacity fades as one: its contents composite in a + // group at full opacity, and the group blends at the instance's alpha. (Mask + // artwork ignores opacity, so it never needs one.) + // A blend mode composites the instance on its own too, then blends it. + // An alpha offset (Advanced) changes each item's alpha on its own: it stays + // in the items' transform, and the group (for a blend or filters) is opaque. + let fade = fx.alpha_factor().unwrap_or(1.0); + let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) { + let gid = out.groups.len() as u32; + out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip }); + let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx }; + (cx.color.concat(&inner), Some(gid)) + } else { + (color, cx.group) + }; + // A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055). + let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s }); + let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice }; + eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); + } } } +/// The highlight behind selected text in a focused field. +pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0); + +/// A dynamic or input field's items (ADR 0066): its background, its text cut to its box, the +/// selection and caret when it has the keyboard, and its border. `live` is its state in the +/// player (and whether it is focused); without one, it shows its authored outline. +fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<&crate::field::FieldState>, bool)>, xf: Affine, clip: Option, out: &mut DisplayList, item: impl Fn(Arc, Affine, Option, Option, Option, Option) -> DisplayItem) { + let (w, h) = (t.box_width.max(0.0), t.box_height.max(0.0)); + let rect = Arc::new(Path::rect(0.0, 0.0, w, h)); + if f.background { + out.items.push(item(rect.clone(), xf, Some(Paint::Solid(f.background_color)), None, clip, None)); + } + // The box clips what is inside it. + let inner = out.clip_parents.len() as u32; + out.clip_parents.push(clip); + out.items.push(item(rect.clone(), xf, Some(Paint::Solid(Rgba::BLACK)), None, clip, Some(inner))); + let (state, focused) = live.unwrap_or((None, false)); + let scroll = state.map_or(anicraft_geom::Vec2::ZERO, |s| s.scroll); + let text_xf = xf.mul(&Affine::translate(-scroll.x, -scroll.y)); + let look = state.and_then(|s| s.look.as_deref()); + // The selection, under the text. + if let (true, Some(st), Some(look)) = (focused, state, look) { + let (a, b) = st.selection(); + if a != b { + for (row, l) in look.lines.iter().enumerate() { + let (from, to) = (a.max(l.start), b.min(l.end)); + if from > to || (from == to && !(a <= l.end && b > l.end)) { + continue; + } + let (x0, x1) = (l.x_at(from), if b > l.end { l.x_at(l.end) + t.size * 0.25 } else { l.x_at(to) }); + let y = row as f32 * look.line_height; + let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height); + out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None)); + } + } + } + // The text: laid out by the player when it changed, else the authored outline (a field whose + // text changed but couldn't be laid out shows none). + let outline = match (state.and_then(|s| s.text.as_ref()), look) { + (_, Some(l)) => Some(l.outline.clone()), + (None, None) => Some(t.outline.clone()), + (Some(_), None) => None, + }; + if let Some(path) = outline { + out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)); + } + // The caret, in an input field with the keyboard and nothing selected. + if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind) + && st.caret == st.anchor + { + let (at, lh) = look.map_or((anicraft_geom::Vec2::ZERO, t.size * 1.2), |l| (l.caret_at(st.caret), l.line_height)); + let r = Path::rect(crate::FIELD_GUTTER + at.x - 0.5, crate::FIELD_GUTTER + at.y, 1.0, lh); + out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)); + } + if f.border { + let mut s = Stroke::new(f.border_color, 1.0); + s.style.join = crate::Join::Miter; + out.items.push(item(rect, xf, None, Some(s), clip, None)); + } +} + +/// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then +/// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale. +/// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow +/// the map, their size the shape's own scale times the instance's. +fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc, Affine, Option, Option) { + let path = Arc::new(anicraft_geom::slice::slice_path(&s.path, own, &sl.map)); + let k = own.mean_scale(); + let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() }); + let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p)); + let size = k * sl.scale.mean_scale(); + let fill = s.fill.as_ref().map(|f| { + let mut f = f.clone(); + match &mut f { + Paint::Linear { start, end, .. } => { + *start = at(*start); + *end = at(*end); + } + Paint::Radial { center, radius, matrix, .. } => { + // The ring's shape (its matrix's linear part) stays, round the mapped centre. + let c = at(matrix.apply(*center)); + let l = Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] }; + if *matrix != Affine::IDENTITY { + *matrix = Affine::translate(c.x, c.y).mul(&l).mul(&Affine::translate(-c.x, -c.y)); + } + *center = c; + *radius *= size; + } + Paint::Solid(_) | Paint::Bitmap { .. } => {} + } + f + }); + (path, sl.post, fill, stroke) +} + #[cfg(test)] #[path = "eval_tests.rs"] mod tests; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e2d27250..ce50d93c 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind}; +use crate::{ColorEffect, Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind}; fn shape_el(id: u64, x: f32) -> Element { Element { @@ -85,7 +85,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { }, ); tl.layers.push(Arc::new(layer)); - d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, timeline: tl })); + d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: tl })); push( layer0(&mut d), 0, @@ -93,7 +93,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { id: ElementId(60), name: String::new(), transform: Affine::translate(100.0, 0.0), - color: ColorEffect { alpha: 0.5, ..Default::default() }, + color: ColorEffect::Alpha(0.5), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, }, ); @@ -101,7 +101,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH); assert_eq!(dl.items[0].transform.translation().x, 100.0); // The instance's opacity is its group's: it fades as one. - assert_eq!((dl.items[0].color.alpha, dl.effective_alpha(&dl.items[0])), (1.0, 0.5)); + assert_eq!((dl.items[0].color.mul[3], dl.effective_alpha(&dl.items[0])), (1.0, 0.5)); assert_eq!(dl.groups.len(), 1); assert!(dl.items.iter().all(|i| i.element == ElementId(60))); } @@ -140,7 +140,7 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { // The main timeline's masked layer holds an instance of a symbol that has its own mask. let mut d = mask_doc(); let sid = SymbolId(99); - d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, timeline: mask_doc().timeline(0).clone() })); + d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() })); let inst = Element { id: ElementId(60), name: String::new(), @@ -156,6 +156,27 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]); } +#[test] +fn a_soft_mask_layer_gives_its_clip_its_mode() { + let mut d = mask_doc(); + assert_eq!((evaluate(&d, 0).clip_mode(0), evaluate(&d, 0).clip_modes.len()), (crate::MaskMode::Coverage, 0), "coverage stays implicit"); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).mask_mode = crate::MaskMode::Luminance; + let dl = evaluate(&d, 0); + assert_eq!(dl.clip_mode(0), crate::MaskMode::Luminance); + // Appended lists keep their modes on their renumbered clips. + let mut a = evaluate(&mask_doc(), 0); + a.append(dl); + assert_eq!((a.clip_mode(0), a.clip_mode(1)), (crate::MaskMode::Coverage, crate::MaskMode::Luminance)); + // The mode is saved only when it isn't coverage, and older files (without it) open as coverage. + let json = serde_json::to_string(&*d.timeline(0).layers[0]).unwrap(); + assert!(json.contains("\"mask_mode\":\"luminance\""), "{json}"); + let plain = serde_json::to_string(&*mask_doc().timeline(0).layers[0]).unwrap(); + assert!(!plain.contains("mask_mode")); + let back: Layer = serde_json::from_str(&json).unwrap(); + assert_eq!(back.mask_mode, crate::MaskMode::Luminance); + assert_eq!(serde_json::from_str::(&plain).unwrap().mask_mode, crate::MaskMode::Coverage); +} + #[test] fn appending_lists_renumbers_clips() { let d = mask_doc(); @@ -295,7 +316,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() { }) .collect(); let mut d = Document::default(); - d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); + d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } })); // The same instance on two keyframes back to back (frames 0–4 and 5–11), moved on the second. let inst = |x: f32| Element { id: ElementId(60), @@ -352,7 +373,7 @@ fn a_motion_tween_drives_each_property_on_its_own_curve() { let d = motion_doc(); let at = |f| { let dl = evaluate(&d, f); - (dl.items[0].transform.translation().x, dl.items[0].color.alpha) + (dl.items[0].transform.translation().x, dl.items[0].color.mul[3]) }; assert_eq!(at(0), (0.0, 1.0)); // X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23. diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs new file mode 100644 index 00000000..b3eb7685 --- /dev/null +++ b/crates/doc/src/field.rs @@ -0,0 +1,390 @@ +//! Text fields while a movie plays (ADR 0066): what a dynamic or input field holds, where its +//! caret and selection are, and the editing that keys and the pointer do to it. +//! +//! Everything here is pure data and pure functions, like the rest of the player: the same field, +//! look and keys always give the same text, caret and selection. Laying text out needs the +//! fonts, which live a layer above (`anicraft-text`), so the player asks its host for a +//! [`FieldLook`] whenever a field's text changes and keeps it in the state; drawing a state then +//! needs nothing else. + +use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, TextBlock, TextField, TextKind}; +use anicraft_geom::{Path, Vec2}; +use std::sync::Arc; + +/// One laid-out line's characters and caret places (indices count `char`s of the shown text). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CaretLine { + /// The first character on the line and the boundary after its last. + pub start: u32, + pub end: u32, + /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending; `x` from + /// the text's left edge (the box's, less the gutter). + pub stops: Vec<(u32, f32)>, +} + +impl CaretLine { + /// The caret's x at boundary `i`. + pub fn x_at(&self, i: u32) -> f32 { + let mut x = self.stops.first().map_or(0.0, |s| s.1); + for &(c, sx) in &self.stops { + if c > i { + break; + } + x = sx; + } + x + } + + /// The boundary nearest `x`. + pub fn index_at(&self, x: f32) -> u32 { + let mut best = (self.start, f32::INFINITY); + for &(c, sx) in &self.stops { + let d = (sx - x).abs(); + if d < best.1 { + best = (c, d); + } + } + best.0.clamp(self.start, self.end) + } +} + +/// A field's text laid out: its outline (in the box's space, the gutter applied, as a text +/// block's outline is) and where the caret can stand. +#[derive(Clone, Debug, PartialEq)] +pub struct FieldLook { + pub outline: Arc, + /// Top line first; never empty. + pub lines: Arc<[CaretLine]>, + /// From one line's top to the next's. + pub line_height: f32, + /// The laid-out text's size (it may be bigger than the box, which clips it). + pub width: f32, + pub height: f32, +} + +impl FieldLook { + /// The line holding boundary `i`: the last that starts at or before it. + pub fn line_of(&self, i: u32) -> usize { + let mut at = 0; + for (n, l) in self.lines.iter().enumerate() { + if l.start <= i { + at = n; + } else { + break; + } + } + at + } + + /// The caret's place at boundary `i`: x from the text's left, and the line's top. + pub fn caret_at(&self, i: u32) -> Vec2 { + let n = self.line_of(i); + let x = self.lines.get(n).map_or(0.0, |l| l.x_at(i)); + Vec2::new(x, n as f32 * self.line_height) + } + + /// The boundary nearest a point in the text's space. + pub fn index_at(&self, p: Vec2) -> u32 { + let h = self.line_height.max(1e-3); + let row = if p.y.is_finite() { (p.y / h).floor().max(0.0) as usize } else { 0 }; + let row = row.min(self.lines.len().saturating_sub(1)); + self.lines.get(row).map_or(0, |l| l.index_at(p.x)) + } +} + +/// What a field holds while the movie plays. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FieldState { + /// Its text once a script or the viewer changed it; `None`: the timeline's own (so a + /// keyframe with other words still shows them). + pub text: Option, + /// The text laid out (the host's work); `None` while it shows the authored outline. + pub look: Option>, + /// The caret and the other end of the selection (character boundaries; equal: nothing + /// selected). + pub caret: u32, + pub anchor: u32, + /// How far the text has scrolled to keep the caret in view (pixels, never negative). + pub scroll: Vec2, +} + +impl FieldState { + /// The field's text: what was set, or the block's own. + pub fn value<'a>(&'a self, block: &'a TextBlock) -> &'a str { + self.text.as_deref().unwrap_or(&block.text) + } + + /// The selected range, low end first. + pub fn selection(&self) -> (u32, u32) { + (self.caret.min(self.anchor), self.caret.max(self.anchor)) + } + + /// The selected text. + pub fn selected(&self, block: &TextBlock) -> String { + let (a, b) = self.selection(); + slice(self.value(block), a, b).to_string() + } +} + +/// The byte offset of character boundary `i` in `s` (its end when past it). +pub fn byte_at(s: &str, i: u32) -> usize { + s.char_indices().nth(i as usize).map_or(s.len(), |(b, _)| b) +} + +/// The characters of `s` from boundary `a` to `b`. +pub fn slice(s: &str, a: u32, b: u32) -> &str { + let (x, y) = (byte_at(s, a.min(b)), byte_at(s, a.max(b))); + s.get(x..y).unwrap_or("") +} + +/// Characters in `s`, as boundaries count them. +pub fn chars(s: &str) -> u32 { + s.chars().count().min(u32::MAX as usize) as u32 +} + +/// Text a script sets, as a field keeps it: at most [`MAX_FIELD_CHARS`] characters, with `\r` +/// and `\r\n` (ActionScript's line ends) as line breaks. +pub fn fit(field: &TextField, text: &str) -> String { + let _ = field; + text.replace("\r\n", "\n").replace('\r', "\n").chars().take(MAX_FIELD_CHARS).collect() +} + +/// What an editing key does (the ActionScript key codes the player receives). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Edit { + Left, + Right, + Up, + Down, + Home, + End, + Backspace, + Delete, + Enter, + SelectAll, +} + +impl Edit { + /// The edit a key code makes, if any. + pub fn from_key(code: u32) -> Option { + Some(match code { + 37 => Edit::Left, + 39 => Edit::Right, + 38 => Edit::Up, + 40 => Edit::Down, + 36 => Edit::Home, + 35 => Edit::End, + 8 => Edit::Backspace, + 46 => Edit::Delete, + 13 => Edit::Enter, + _ => return None, + }) + } +} + +/// What an edit changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Changed { + pub text: bool, + pub caret: bool, +} + +/// A focused field being edited: its block (style and authored text), its state, and whether +/// the viewer may change the text (input fields) or only select it. +pub struct Editor<'a> { + pub block: &'a TextBlock, + pub field: &'a TextField, + pub st: &'a mut FieldState, +} + +impl Editor<'_> { + fn len(&self) -> u32 { + chars(self.st.value(self.block)) + } + + fn editable(&self) -> bool { + self.field.kind == TextKind::Input + } + + /// Replaces the selection with `s` (typed characters, a paste or a line break). + pub fn insert(&mut self, s: &str) -> Changed { + if !self.editable() { + return Changed::default(); + } + let one = !self.field.lines.multiline(); + let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).collect(); + let (a, b) = self.st.selection(); + let value = self.st.value(self.block).to_string(); + let kept = chars(&value) - (b - a); + let room = if self.field.max_chars > 0 { self.field.max_chars.saturating_sub(kept) } else { u32::MAX }; + let room = room.min((MAX_FIELD_CHARS as u32).saturating_sub(kept)); + if chars(&add) > room { + add = add.chars().take(room as usize).collect(); + } + if add.is_empty() && a == b { + return Changed::default(); + } + let mut next = String::with_capacity(value.len() + add.len()); + next.push_str(slice(&value, 0, a)); + next.push_str(&add); + next.push_str(slice(&value, b, u32::MAX)); + let caret = a + chars(&add); + self.st.text = Some(next); + self.st.caret = caret; + self.st.anchor = caret; + Changed { text: true, caret: true } + } + + /// One editing key; `shift` extends the selection with caret moves. + pub fn key(&mut self, e: Edit, shift: bool, look: Option<&FieldLook>) -> Changed { + let len = self.len(); + let (a, b) = self.st.selection(); + let moved = |st: &mut FieldState, to: u32, shift: bool| { + st.caret = to.min(len); + if !shift { + st.anchor = st.caret; + } + Changed { text: false, caret: true } + }; + match e { + Edit::SelectAll => { + self.st.anchor = 0; + self.st.caret = len; + Changed { text: false, caret: true } + } + Edit::Left if !shift && a != b => moved(self.st, a, false), + Edit::Right if !shift && a != b => moved(self.st, b, false), + Edit::Left => { + let to = self.st.caret.saturating_sub(1); + moved(self.st, to, shift) + } + Edit::Right => { + let to = self.st.caret.saturating_add(1); + moved(self.st, to, shift) + } + Edit::Home | Edit::End | Edit::Up | Edit::Down => { + let Some(look) = look else { + let to = if matches!(e, Edit::Home | Edit::Up) { 0 } else { len }; + return moved(self.st, to, shift); + }; + let n = look.line_of(self.st.caret); + let line = look.lines.get(n); + let to = match e { + Edit::Home => line.map_or(0, |l| l.start), + Edit::End => line.map_or(len, |l| l.end), + _ => { + let x = line.map_or(0.0, |l| l.x_at(self.st.caret)); + let target = if e == Edit::Up { n.checked_sub(1) } else { Some(n + 1).filter(|m| *m < look.lines.len()) }; + match target.and_then(|m| look.lines.get(m)) { + Some(l) => l.index_at(x), + None if e == Edit::Up => 0, + None => len, + } + } + }; + moved(self.st, to, shift) + } + Edit::Backspace | Edit::Delete if !self.editable() => Changed::default(), + Edit::Backspace | Edit::Delete if a != b => self.insert(""), + Edit::Backspace => { + if a == 0 { + return Changed::default(); + } + self.st.anchor = a - 1; + self.insert("") + } + Edit::Delete => { + if b >= len { + return Changed::default(); + } + self.st.anchor = a; + self.st.caret = b + 1; + self.insert("") + } + Edit::Enter if self.field.lines.multiline() => self.insert("\n"), + Edit::Enter => Changed::default(), + } + } + + /// The pointer at `p` (the text's space): pressed (`extend`: dragging from an earlier press). + pub fn point(&mut self, p: Vec2, extend: bool, look: Option<&FieldLook>) -> Changed { + let i = look.map_or(self.len(), |l| l.index_at(p + self.st.scroll)).min(self.len()); + self.st.caret = i; + if !extend { + self.st.anchor = i; + } + Changed { text: false, caret: true } + } +} + +/// Keeps the caret in view: scrolls the text so the caret's line fits in the box's height and +/// (when lines don't wrap) the caret in its width. +pub fn scroll_to_caret(block: &TextBlock, field: &TextField, st: &mut FieldState) { + let Some(look) = st.look.clone() else { + st.scroll = Vec2::ZERO; + return; + }; + let view = Vec2::new((block.box_width - 2.0 * FIELD_GUTTER).max(1.0), (block.box_height - 2.0 * FIELD_GUTTER).max(1.0)); + let c = look.caret_at(st.caret); + let mut s = st.scroll; + if field.lines != LineType::Multiline { + if c.x - s.x > view.x { + s.x = c.x - view.x; + } + if c.x < s.x { + s.x = c.x; + } + } else { + s.x = 0.0; + } + if c.y + look.line_height - s.y > view.y { + s.y = c.y + look.line_height - view.y; + } + if c.y < s.y { + s.y = c.y; + } + // Never past the text's end. + s.x = s.x.min((look.width - view.x).max(0.0)).max(0.0); + s.y = s.y.min((look.height - view.y).max(0.0)).max(0.0); + st.scroll = if s.x.is_finite() && s.y.is_finite() { s } else { Vec2::ZERO }; +} + +/// A look for tests: every character `cw` wide and `lh` tall (a square per visible one), lines +/// broken at `\n` and, with `wrap`, after as many characters as fit. +#[cfg(test)] +pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option) -> FieldLook { + let per = wrap.map(|w| ((w / cw).floor() as u32).max(1)); + let mut lines = Vec::new(); + let mut outline = Path::new(); + let (mut start, mut col, mut stops, mut width) = (0u32, 0u32, vec![(0u32, 0.0f32)], 0.0f32); + let mut i = 0u32; + for c in text.chars() { + if c == '\n' { + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + i += 1; + (start, col) = (i, 0); + stops.push((i, 0.0)); + continue; + } + if per.is_some_and(|p| col == p) { + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + (start, col) = (i, 0); + stops.push((i, 0.0)); + } + if !c.is_whitespace() { + let r = Path::rect(FIELD_GUTTER + col as f32 * cw + 1.0, FIELD_GUTTER + lines.len() as f32 * lh + 1.0, cw - 2.0, lh - 2.0); + outline.cmds.extend(r.cmds); + } + col += 1; + i += 1; + stops.push((i, col as f32 * cw)); + width = width.max(col as f32 * cw); + } + lines.push(CaretLine { start, end: i, stops }); + let n = lines.len(); + FieldLook { outline: Arc::new(outline), lines: lines.into(), line_height: lh, width, height: n as f32 * lh } +} + +#[cfg(test)] +#[path = "field_tests.rs"] +mod tests; diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs new file mode 100644 index 00000000..a1d8e5c4 --- /dev/null +++ b/crates/doc/src/field_tests.rs @@ -0,0 +1,182 @@ +use super::*; +use crate::{Rgba, TextAlign}; + +fn block(text: &str, f: TextField) -> TextBlock { + TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None } +} + +/// Runs edits on a field as the player does: each change of text lays it out again (10 px per +/// character, 10 px lines) and keeps the caret in view. +struct Rig { + block: TextBlock, + field: TextField, + st: FieldState, +} + +impl Rig { + fn new(text: &str, kind: TextKind, lines: LineType) -> Rig { + let field = TextField { lines, ..TextField::new(kind) }; + let mut r = Rig { block: block(text, field.clone()), field, st: FieldState::default() }; + r.relayout(); + r + } + fn relayout(&mut self) { + let shown = self.field.shown(self.st.value(&self.block)); + self.st.look = Some(Arc::new(mono_look(&shown, 10.0, 10.0, self.field.wrap_width(self.block.box_width)))); + scroll_to_caret(&self.block, &self.field, &mut self.st); + } + fn apply(&mut self, ch: Changed) { + if ch.text { + self.relayout(); + } else { + scroll_to_caret(&self.block, &self.field, &mut self.st); + } + } + fn ed(&mut self) -> (Editor<'_>, Option>) { + let look = self.st.look.clone(); + (Editor { block: &self.block, field: &self.field, st: &mut self.st }, look) + } + fn key(&mut self, e: Edit, shift: bool) -> &mut Self { + let (mut ed, look) = self.ed(); + let ch = ed.key(e, shift, look.as_deref()); + self.apply(ch); + self + } + fn typed(&mut self, s: &str) -> &mut Self { + for c in s.chars() { + let (mut ed, _) = self.ed(); + let ch = ed.insert(&c.to_string()); + self.apply(ch); + } + self + } + fn click(&mut self, x: f32, y: f32, extend: bool) -> &mut Self { + let (mut ed, look) = self.ed(); + let ch = ed.point(Vec2::new(x, y), extend, look.as_deref()); + self.apply(ch); + self + } + fn text(&self) -> &str { + self.st.value(&self.block) + } +} + +#[test] +fn typing_moves_the_caret_and_keys_edit_around_it() { + let mut r = Rig::new("", TextKind::Input, LineType::Single); + r.typed("hello"); + assert_eq!((r.text(), r.st.caret, r.st.anchor), ("hello", 5, 5)); + r.key(Edit::Left, false).key(Edit::Left, false).typed("X"); + assert_eq!((r.text(), r.st.caret), ("helXlo", 4)); + r.key(Edit::Backspace, false); + assert_eq!((r.text(), r.st.caret), ("hello", 3)); + r.key(Edit::Delete, false); + assert_eq!((r.text(), r.st.caret), ("helo", 3)); + r.key(Edit::Home, false); + assert_eq!(r.st.caret, 0); + r.key(Edit::Backspace, false); + assert_eq!(r.text(), "helo", "nothing before the caret"); + r.key(Edit::End, false).key(Edit::Delete, false); + assert_eq!((r.text(), r.st.caret), ("helo", 4), "nothing after it"); + // Enter types nothing in a one-line field; control characters never go in. + r.key(Edit::Enter, false).typed("\u{7}\t"); + assert_eq!(r.text(), "helo"); +} + +#[test] +fn shift_selects_and_typing_replaces_the_selection() { + let mut r = Rig::new("abcdef", TextKind::Input, LineType::Single); + r.click(20.0, 5.0, false); + assert_eq!(r.st.caret, 2, "a click puts the caret at the nearest boundary"); + r.key(Edit::Right, true).key(Edit::Right, true); + assert_eq!(r.st.selection(), (2, 4)); + assert_eq!(r.st.selected(&r.block), "cd"); + // An arrow without Shift collapses the selection to its side. + r.key(Edit::Left, false); + assert_eq!((r.st.caret, r.st.anchor), (2, 2)); + r.key(Edit::End, true); + assert_eq!(r.st.selection(), (2, 6)); + r.typed("Z"); + assert_eq!((r.text(), r.st.caret), ("abZ", 3)); + // Dragging extends from where the press was; Backspace deletes the selection. + r.click(0.0, 5.0, false).click(19.0, 5.0, true); + assert_eq!(r.st.selection(), (0, 2)); + r.key(Edit::Backspace, false); + assert_eq!((r.text(), r.st.caret), ("Z", 0)); + r.key(Edit::SelectAll, false); + assert_eq!(r.st.selection(), (0, 1)); +} + +#[test] +fn multiline_fields_take_enter_and_move_between_lines() { + let mut r = Rig::new("", TextKind::Input, LineType::MultilineNoWrap); + r.typed("abc").key(Edit::Enter, false).typed("de"); + assert_eq!(r.text(), "abc\nde"); + assert_eq!(r.st.caret, 6); + r.key(Edit::Up, false); + assert_eq!(r.st.caret, 2, "up keeps the column"); + r.key(Edit::End, false); + assert_eq!(r.st.caret, 3); + r.key(Edit::Down, false); + assert_eq!(r.st.caret, 6, "down to the shorter line's end"); + r.key(Edit::Down, false); + assert_eq!(r.st.caret, 6, "down from the last line goes to the end"); + r.key(Edit::Up, false).key(Edit::Up, false); + assert_eq!(r.st.caret, 0, "up from the first line goes to the start"); + // Clicking on the second line. + r.click(17.0, 14.0, false); + assert_eq!(r.st.caret, 6, "x 17 on line 2 is nearest the boundary after d"); +} + +#[test] +fn max_chars_and_passwords() { + let mut r = Rig::new("", TextKind::Input, LineType::Password); + r.field.max_chars = 4; + r.typed("secret"); + assert_eq!(r.text(), "secr", "at most max_chars"); + let shown = r.field.shown(r.text()); + assert_eq!(shown, "****"); + // A paste is cut to the room left, and single-line fields drop its line breaks. + let mut r = Rig::new("ab", TextKind::Input, LineType::Single); + r.field.max_chars = 6; + r.key(Edit::End, false); + let (mut ed, _) = r.ed(); + let ch = ed.insert("c\nd\nefgh"); + r.apply(ch); + assert_eq!(r.text(), "abcdef"); +} + +#[test] +fn dynamic_fields_select_but_never_change() { + let mut r = Rig::new("read only", TextKind::Dynamic, LineType::Single); + r.typed("x").key(Edit::Backspace, false).key(Edit::Delete, false); + assert_eq!(r.text(), "read only"); + assert!(r.st.text.is_none(), "untouched"); + r.key(Edit::SelectAll, false); + assert_eq!(r.st.selected(&r.block), "read only"); +} + +#[test] +fn one_line_fields_scroll_to_keep_the_caret_in_view() { + // The box shows 50 px of text (54 less the gutters): five characters. + let mut r = Rig::new("", TextKind::Input, LineType::Single); + r.typed("abcdefgh"); + assert_eq!(r.st.scroll.x, 30.0, "the caret at 80 px shows at the right edge"); + r.key(Edit::Home, false); + assert_eq!(r.st.scroll.x, 0.0); + // Multiline: lines wrap and it scrolls down instead (the box shows two 10 px lines). + let mut r = Rig::new("", TextKind::Input, LineType::Multiline); + r.typed("aaaaabbbbbccccc"); + assert_eq!(r.st.look.as_ref().map(|l| l.lines.len()), Some(3)); + assert_eq!((r.st.scroll.x, r.st.scroll.y), (0.0, 10.0)); +} + +#[test] +fn script_text_is_capped_and_takes_actionscript_line_ends() { + let f = TextField::new(TextKind::Dynamic); + assert_eq!(fit(&f, "a\rb\r\nc"), "a\nb\nc"); + assert_eq!(chars(&fit(&f, &"x".repeat(MAX_FIELD_CHARS + 10))), MAX_FIELD_CHARS as u32); + assert_eq!(slice("héllo", 1, 3), "él"); + assert_eq!(slice("héllo", 4, 99), "o"); + assert_eq!(byte_at("héllo", 2), 3); +} diff --git a/crates/doc/src/gradient_tests.rs b/crates/doc/src/gradient_tests.rs new file mode 100644 index 00000000..5ed9bbf2 --- /dev/null +++ b/crates/doc/src/gradient_tests.rs @@ -0,0 +1,131 @@ +//! Gradient options, fill frames and fitting (ADR 0074). + +use super::*; + +fn stops() -> Vec { + vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }] +} + +fn near(a: &Affine, b: &Affine) -> bool { + a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-4 * x.abs().max(y.abs()).max(1.0)) +} + +#[test] +fn spread_maps_positions_onto_the_ramp() { + for (t, pad, reflect, repeat) in [(-0.25, 0.0, 0.25, 0.75), (0.0, 0.0, 0.0, 0.0), (0.4, 0.4, 0.4, 0.4), (1.25, 1.0, 0.75, 0.25), (2.5, 1.0, 0.5, 0.5), (-1.5, 0.0, 0.5, 0.5)] { + assert!((Spread::Pad.apply(t) - pad).abs() < 1e-6, "pad {t}"); + assert!((Spread::Reflect.apply(t) - reflect).abs() < 1e-6, "reflect {t}"); + assert!((Spread::Repeat.apply(t) - repeat).abs() < 1e-6, "repeat {t}"); + } + for s in Spread::ALL { + assert_eq!(s.apply(f32::NAN), 0.0); + assert!((0.0..=1.0).contains(&s.apply(f32::INFINITY))); + assert_eq!(Spread::from_key(s.key()), Some(s)); + } + assert_eq!(Spread::from_key("pad"), Some(Spread::Pad)); + assert_eq!(Spread::from_key("mirror"), None); +} + +#[test] +fn frames_round_trip_for_every_fill_kind() { + // Linear: x from start to end, y square to it at the same length. + let lin = Paint::linear(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), stops()); + let f = lin.frame(None).unwrap(); + assert!(near(&f, &Affine { m: [10.0, 0.0, 0.0, 10.0, 20.0, 20.0] }), "{f:?}"); + assert_eq!(lin.with_frame(&f, None), lin); + // Radial: a circle stays a plain circle, with no matrix. + let rad = Paint::radial(Vec2::new(5.0, 6.0), 4.0, stops()); + let f = rad.frame(None).unwrap(); + assert!(near(&f, &Affine { m: [4.0, 0.0, 0.0, 4.0, 5.0, 6.0] })); + assert_eq!(rad.with_frame(&f, None), rad); + // A turned ellipse keeps its centre and its x axis's length as the radius. + let ell = Affine::translate(50.0, 40.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(30.0, 10.0)); + let p = rad.with_frame(&ell, None); + match &p { + Paint::Radial { center, radius, matrix, .. } => { + assert!(center.distance(Vec2::new(50.0, 40.0)) < 1e-4); + assert!((radius - 30.0).abs() < 1e-4); + assert!(near(&matrix.mul(&Affine::translate(center.x, center.y)), &Affine::translate(center.x, center.y).mul(&Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] })), "the matrix turns about the centre"); + } + other => panic!("{other:?}"), + } + assert!(near(&p.frame(None).unwrap(), &ell)); + // Bitmap: the box onto one copy of the image. + let bmp = Paint::Bitmap { bitmap: BitmapId(1), repeat: true, matrix: Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0)) }; + let f = bmp.frame(Some((10.0, 6.0))).unwrap(); + assert!(f.apply(Vec2::new(-1.0, -1.0)).distance(Vec2::new(3.0, 4.0)) < 1e-4, "top-left of the image"); + assert!(f.apply(Vec2::new(1.0, 1.0)).distance(Vec2::new(23.0, 16.0)) < 1e-4, "bottom-right"); + assert_eq!(bmp.frame(None), None, "a bitmap needs its size"); + assert!(near(&match bmp.with_frame(&f, Some((10.0, 6.0))) { + Paint::Bitmap { matrix, .. } => matrix, + _ => Affine::IDENTITY, + }, &Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0)))); + // Solid colours have no frame; a frame that isn't finite changes nothing. + assert_eq!(Paint::Solid(Rgba::WHITE).frame(None), None); + assert_eq!(rad.with_frame(&Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }, None), rad); +} + +#[test] +fn radial_gradients_follow_any_transform_exactly() { + // A skew turns the circle into a tilted ellipse: the frame is carried exactly, focal point + // and all. + let mut rad = Paint::radial(Vec2::new(10.0, 0.0), 5.0, stops()); + if let Paint::Radial { focal, .. } = &mut rad { + *focal = 0.5; + } + let skew = Affine { m: [1.0, 0.0, 0.7, 2.0, 3.0, -1.0] }; + let moved = rad.transformed(&skew); + assert!(near(&moved.frame(None).unwrap(), &skew.mul(&rad.frame(None).unwrap()))); + assert!(matches!(moved, Paint::Radial { focal, .. } if focal == 0.5)); + // A plain move keeps a plain circle. + assert!(matches!(rad.transformed(&Affine::translate(4.0, 4.0)), Paint::Radial { matrix, .. } if matrix == Affine::IDENTITY)); +} + +#[test] +fn fitting_places_a_fill_on_the_shape() { + let b = Rect { min: Vec2::new(0.0, 0.0), max: Vec2::new(200.0, 100.0) }; + match Paint::linear(Vec2::ZERO, Vec2::new(1.0, 1.0), stops()).fitted(&b) { + Paint::Linear { start, end, .. } => assert_eq!((start, end), (Vec2::new(0.0, 50.0), Vec2::new(200.0, 50.0))), + other => panic!("{other:?}"), + } + match Paint::radial(Vec2::ZERO, 1.0, stops()).fitted(&b) { + Paint::Radial { center, radius, matrix, .. } => assert_eq!((center, radius, matrix), (Vec2::new(100.0, 50.0), 100.0, Affine::IDENTITY)), + other => panic!("{other:?}"), + } + let bmp = Paint::Bitmap { bitmap: BitmapId(2), repeat: false, matrix: Affine::scale(3.0, 3.0) }; + assert_eq!(bmp.fitted(&b), Paint::Bitmap { bitmap: BitmapId(2), repeat: true, matrix: Affine::IDENTITY }); + // Stops and options stay; an empty box changes nothing. + let mut rep = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops()); + if let Paint::Linear { spread, linear_rgb, .. } = &mut rep { + *spread = Spread::Repeat; + *linear_rgb = true; + } + assert!(matches!(rep.fitted(&b), Paint::Linear { spread: Spread::Repeat, linear_rgb: true, .. })); + assert_eq!(rep.fitted(&Rect::EMPTY), rep); +} + +#[test] +fn older_files_open_and_plain_gradients_are_stored_as_before() { + let old = r#"{"Radial":{"center":{"x":1.0,"y":2.0},"radius":3.0,"stops":[{"offset":0.0,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0}}]}}"#; + let p: Paint = serde_json::from_str(old).unwrap(); + assert!(matches!(p, Paint::Radial { spread: Spread::Pad, linear_rgb: false, focal, matrix, .. } if focal == 0.0 && matrix == Affine::IDENTITY)); + let back = serde_json::to_string(&p).unwrap(); + assert!(!back.contains("spread") && !back.contains("focal") && !back.contains("matrix") && !back.contains("linear_rgb"), "{back}"); + // Set options are written, and read back. + let mut q = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops()); + if let Paint::Linear { spread, linear_rgb, .. } = &mut q { + *spread = Spread::Reflect; + *linear_rgb = true; + } + let text = serde_json::to_string(&q).unwrap(); + assert!(text.contains("\"spread\":\"reflect\"") && text.contains("\"linear_rgb\":true"), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), q); +} + +#[test] +fn radial_gradients_tween_through_their_frames() { + let a = Paint::radial(Vec2::ZERO, 10.0, stops()); + let b = a.with_frame(&Affine::translate(100.0, 0.0).mul(&Affine::scale(30.0, 10.0)), None); + let mid = a.lerp(&b, 0.5); + assert!(near(&mid.frame(None).unwrap(), &Affine { m: [20.0, 0.0, 0.0, 10.0, 50.0, 0.0] }), "{mid:?}"); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 258e5431..ec89df81 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -7,32 +7,45 @@ pub use anicraft_audio as audio; pub use anicraft_actions as actions; +pub mod aids; pub mod armature; +pub mod skin; +pub mod warp; mod bitmap; +mod color_effect; pub mod camera; mod filter; mod easing; mod eval; +pub mod field; mod hints; +pub mod nine_slice; pub mod library; pub mod motion; pub mod path_table; pub mod width; pub mod stroke_style; pub mod player; +pub mod publish; pub mod sample; +pub mod templates; pub mod sound; +pub mod swatch; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; -pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; +pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; pub use easing::Easing; +pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError}; -pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; +pub use motion::{MotionTween, OnPath, PROPERTIES, 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 swatch::{MAX_SWATCHES, Swatch, SwatchPaint}; +pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES}; +pub use nine_slice::symbol_box; 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, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; @@ -98,12 +111,103 @@ pub struct GradientStop { pub color: Rgba, } +/// What a gradient shows past its ends (Animate's Overflow / Flow, SVG's `spreadMethod`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Spread { + /// The end colours carry on (Animate's Extend, SVG's `pad`). + #[default] + Pad, + /// The ramp mirrors back and forth. + Reflect, + /// The ramp starts again. + Repeat, +} + +impl Spread { + pub const ALL: [Spread; 3] = [Spread::Pad, Spread::Reflect, Spread::Repeat]; + pub fn is_pad(&self) -> bool { + *self == Spread::Pad + } + /// The key commands and files use (`extend` is Animate's name for `pad`). + pub fn key(self) -> &'static str { + match self { + Spread::Pad => "extend", + Spread::Reflect => "reflect", + Spread::Repeat => "repeat", + } + } + pub fn from_key(s: &str) -> Option { + match s { + "extend" | "pad" => Some(Spread::Pad), + "reflect" => Some(Spread::Reflect), + "repeat" => Some(Spread::Repeat), + _ => None, + } + } + /// Gradient position `t` (0 at the start, 1 at the end) → where on the ramp, in `0..=1`. + /// Non-finite positions read the start. + pub fn apply(self, t: f32) -> f32 { + if !t.is_finite() { + return 0.0; + } + match self { + Spread::Pad => t.clamp(0.0, 1.0), + Spread::Repeat => { + let f = t.rem_euclid(1.0); + // `rem_euclid` can round up to exactly 1 for tiny negative values. + if f >= 1.0 { 0.0 } else { f } + } + Spread::Reflect => { + let m = t.rem_euclid(2.0); + (if m > 1.0 { 2.0 - m } else { m }).clamp(0.0, 1.0) + } + } + } +} + +/// Most stops a fill gradient may have (Animate allows 15). +pub const MAX_GRADIENT_STOPS: usize = 15; +/// How far the focal point may sit from the centre, as a share of the radius (a focal point on +/// the ring itself is undefined; Animate's focal ratio runs to ±1 too). +pub const MAX_FOCAL: f32 = 0.98; + /// How a region is painted. Gradient geometry is in the element's local space. +/// +/// Gradients may carry options that older files don't have (ADR 0074): what shows past the ends +/// (`spread`), interpolation in linear light (`linear_rgb`), and for a radial gradient a focal +/// point and a `matrix` that turns its circle into any ellipse. Each is written only when set, +/// so a plain gradient is stored as before. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Paint { Solid(Rgba), - Linear { start: Vec2, end: Vec2, stops: Vec }, - Radial { center: Vec2, radius: f32, stops: Vec }, + Linear { + start: Vec2, + end: Vec2, + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + /// Mix the stops in linear light (Animate's "Linear RGB"), not in sRGB. + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + }, + /// The circle of `radius` round `center`, carried by `matrix` (an ellipse at any angle). + Radial { + center: Vec2, + radius: f32, + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + /// Where the ramp starts, along the gradient's own x axis from the centre, as a share + /// of the radius in `-MAX_FOCAL..=MAX_FOCAL` (Animate's focal point ratio). + #[serde(default, skip_serializing_if = "is_zero")] + focal: f32, + /// Gradient space → shape space (identity: the plain circle). + #[serde(default, skip_serializing_if = "is_identity")] + matrix: Affine, + }, /// A bitmap, its pixel (x, y) at local `matrix · (x, y)`; `repeat` tiles it, otherwise it /// shows once (an imported image is a rectangle of exactly its size, with no matrix). Bitmap { @@ -120,7 +224,19 @@ fn is_identity(m: &Affine) -> bool { *m == Affine::IDENTITY } +/// The canonical box a fill's frame maps: `-1..=1` on both axes (Animate's gradient square). +pub const FRAME_BOX: Rect = Rect { min: Vec2 { x: -1.0, y: -1.0 }, max: Vec2 { x: 1.0, y: 1.0 } }; + impl Paint { + /// A linear gradient from `start` to `end`, with no options. + pub fn linear(start: Vec2, end: Vec2, stops: Vec) -> Paint { + Paint::Linear { start, end, stops, spread: Spread::Pad, linear_rgb: false } + } + /// A radial gradient: the circle of `radius` round `center`, with no options. + pub fn radial(center: Vec2, radius: f32, stops: Vec) -> Paint { + Paint::Radial { center, radius, stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0, matrix: Affine::IDENTITY } + } + /// A representative colour (first stop for gradients) for swatches and the properties panel. pub fn primary_color(&self) -> Rgba { match self { @@ -130,18 +246,119 @@ impl Paint { } } + /// A gradient's colour stops. + pub fn stops(&self) -> Option<&[GradientStop]> { + match self { + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops), + _ => None, + } + } + pub fn stops_mut(&mut self) -> Option<&mut Vec> { + match self { + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops), + _ => None, + } + } + pub fn is_gradient(&self) -> bool { + matches!(self, Paint::Linear { .. } | Paint::Radial { .. }) + } + /// The paint carried by `m` (its geometry moved from one space to another), so a shape in - /// the new space shows it where it was: gradient ends and centre are mapped, a radial - /// gradient's radius scales by the mean scale, a bitmap's matrix is composed. + /// the new space shows it where it was: gradient ends are mapped, a radial gradient's and a + /// bitmap's matrix is composed (exact under any transform). pub fn transformed(&self, m: &Affine) -> Paint { match self { Paint::Solid(_) => self.clone(), - Paint::Linear { start, end, stops } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone() }, - Paint::Radial { center, radius, stops } => Paint::Radial { center: m.apply(*center), radius: radius * m.mean_scale(), stops: stops.clone() }, + Paint::Linear { start, end, stops, spread, linear_rgb } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }, + Paint::Radial { .. } => match self.frame(None) { + Some(f) => self.with_frame(&m.mul(&f), None), + None => self.clone(), + }, Paint::Bitmap { bitmap, repeat, matrix } => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: m.mul(matrix) }, } } + /// The fill's frame: the map from [`FRAME_BOX`] to the paint's space, which the Gradient + /// Transform tool edits (ADR 0074). + /// + /// * Linear: x from −1 at the start to 1 at the end, y square to it at the same scale. + /// * Radial: the unit circle onto the gradient's ring (x is its own axis, where the focal + /// point sits). + /// * Bitmap: the box onto one copy of the image (`image` is its size in pixels). + /// + /// `None` for solid colours and a bitmap of unknown size. + pub fn frame(&self, image: Option<(f32, f32)>) -> Option { + match self { + Paint::Solid(_) => None, + Paint::Linear { start, end, .. } => { + let mid = start.lerp(*end, 0.5); + let h = (*end - *start) * 0.5; + Some(Affine { m: [h.x, h.y, -h.y, h.x, mid.x, mid.y] }) + } + Paint::Radial { center, radius, matrix, .. } => Some(matrix.mul(&Affine::translate(center.x, center.y)).mul(&Affine::scale(*radius, *radius))), + Paint::Bitmap { matrix, .. } => { + let (w, h) = image?; + Some(matrix.mul(&Affine::translate(w * 0.5, h * 0.5)).mul(&Affine::scale(w * 0.5, h * 0.5))) + } + } + } + + /// This paint with its frame set to `f` (see [`Paint::frame`]); the stops and options stay. + /// A linear gradient keeps only the frame's x axis. A radial gradient is stored as a + /// circle when `f` is one, else with a matrix about its centre. Solid colours (and bitmaps + /// without a size) are returned unchanged. + pub fn with_frame(&self, f: &Affine, image: Option<(f32, f32)>) -> Paint { + let finite = f.m.iter().all(|v| v.is_finite()); + if !finite { + return self.clone(); + } + match self { + Paint::Solid(_) => self.clone(), + Paint::Linear { stops, spread, linear_rgb, .. } => Paint::Linear { start: f.apply(Vec2::new(-1.0, 0.0)), end: f.apply(Vec2::new(1.0, 0.0)), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }, + Paint::Radial { stops, spread, linear_rgb, focal, .. } => { + let center = f.apply(Vec2::ZERO); + let [a, b, c, d, ..] = f.m; + let radius = Vec2::new(a, b).length(); + let (matrix, radius) = if radius > 1e-9 { + // The linear part with the x axis's length taken out, about the centre. + let l = Affine { m: [a / radius, b / radius, c / radius, d / radius, 0.0, 0.0] }; + let plain = (l.m[0] - 1.0).abs() < 1e-6 && l.m[1].abs() < 1e-6 && l.m[2].abs() < 1e-6 && (l.m[3] - 1.0).abs() < 1e-6; + if plain { (Affine::IDENTITY, radius) } else { (Affine::translate(center.x, center.y).mul(&l).mul(&Affine::translate(-center.x, -center.y)), radius) } + } else { + (Affine::IDENTITY, 0.0) + }; + Paint::Radial { center, radius, stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal, matrix } + } + Paint::Bitmap { bitmap, repeat, .. } => match image { + Some((w, h)) if w > 0.0 && h > 0.0 => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: f.mul(&Affine::scale(2.0 / w, 2.0 / h)).mul(&Affine::translate(-w * 0.5, -h * 0.5)) }, + _ => self.clone(), + }, + } + } + + /// This gradient or bitmap placed on `bounds` (shape space), as Animate pours an unlocked + /// fill: a linear gradient across the width, left to right; a radial one centred, its + /// ring touching the longer side; a bitmap tiled from the top-left at its own size. + /// The stops and options stay. + pub fn fitted(&self, bounds: &Rect) -> Paint { + if bounds.is_empty() || !(bounds.min.is_finite() && bounds.max.is_finite()) { + return self.clone(); + } + let c = bounds.center(); + match self { + Paint::Solid(_) => self.clone(), + Paint::Linear { .. } => { + let hw = (bounds.width() * 0.5).max(0.5); + self.with_frame(&Affine { m: [hw, 0.0, 0.0, hw, c.x, c.y] }, None) + } + Paint::Radial { .. } => { + let r = (bounds.width().max(bounds.height()) * 0.5).max(0.5); + self.with_frame(&Affine { m: [r, 0.0, 0.0, r, c.x, c.y] }, None) + } + Paint::Bitmap { bitmap, .. } => Paint::Bitmap { bitmap: *bitmap, repeat: true, matrix: Affine::translate(bounds.min.x, bounds.min.y) }, + } + } + pub fn lerp(&self, o: &Paint, t: f32) -> Paint { let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option> { (a.len() == b.len()).then(|| { @@ -150,13 +367,24 @@ impl Paint { }; match (self, o) { (Paint::Solid(a), Paint::Solid(b)) => Paint::Solid(a.lerp(*b, t)), - (Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => match lerp_stops(a, b) { - Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops }, + (Paint::Linear { start: s0, end: e0, stops: a, spread, linear_rgb }, Paint::Linear { start: s1, end: e1, stops: b, .. }) => match lerp_stops(a, b) { + Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops, spread: *spread, linear_rgb: *linear_rgb }, None => self.clone(), }, - (Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => match lerp_stops(a, b) { - Some(stops) => Paint::Radial { center: c0.lerp(*c1, t), radius: anicraft_geom::lerp(*r0, *r1, t), stops }, - None => self.clone(), + (Paint::Radial { stops: a, .. }, Paint::Radial { stops: b, focal: f1, .. }) => match (lerp_stops(a, b), self.frame(None), o.frame(None)) { + (Some(stops), Some(fa), Some(fb)) => { + let mut m = [0.0; 6]; + for (k, v) in m.iter_mut().enumerate() { + *v = anicraft_geom::lerp(fa.m[k], fb.m[k], t); + } + let mut p = self.with_frame(&Affine { m }, None); + if let Paint::Radial { stops: s, focal, .. } = &mut p { + *s = stops; + *focal = anicraft_geom::lerp(*focal, *f1, t); + } + p + } + _ => self.clone(), }, _ => self.clone(), } @@ -257,17 +485,30 @@ pub struct Shape { /// Otherwise a drawing object, which keeps to itself. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub merge: bool, + /// Asset Warp (ADR 0079): the mesh and pins that bend the outline (and a bitmap fill). The + /// path is the bent outline; the warp keeps the outline as drawn. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warp: Option>, } impl PartialEq for Shape { fn eq(&self, o: &Shape) -> bool { - arc_eq(&self.path, &o.path) && self.fill == o.fill && self.stroke == o.stroke && self.fill_rule == o.fill_rule && self.merge == o.merge + arc_eq(&self.path, &o.path) + && self.fill == o.fill + && self.stroke == o.stroke + && self.fill_rule == o.fill_rule + && self.merge == o.merge + && match (&self.warp, &o.warp) { + (Some(a), Some(b)) => arc_eq(a, b), + (None, None) => true, + _ => false, + } } } impl Shape { pub fn filled(path: Path, fill: Paint) -> Shape { - Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false } + Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false, warp: None } } pub fn with_stroke(mut self, color: Rgba, width: f32) -> Shape { self.stroke = Some(Stroke::new(color, width)); @@ -334,6 +575,71 @@ pub enum ElementKind { /// The camera, on a camera layer (ADR 0027): the element's transform is the camera on the /// stage and its tint colours the view. It draws nothing itself. Camera, + /// A group (Modify › Group, ADR 0073): elements kept together without a Library symbol. Its + /// members are a one-layer, one-frame timeline, so double-clicking it edits them in place + /// with every tool, and raw shapes inside merge only with each other. The group's transform + /// and colour effect apply to its members; it is always drawn at its members' frame 0. + Group { + #[serde(default)] + members: Timeline, + }, +} + +impl ElementKind { + /// A group of `elements` (ADR 0073), on one layer with id `layer`. + pub fn group(layer: LayerId, elements: Vec>) -> ElementKind { + let mut l = Layer::new(layer, "Layer 1"); + if let Some(k) = l.keyframe_mut(0) { + k.elements = elements; + } + ElementKind::Group { members: Timeline { layers: vec![Arc::new(l)] } } + } + + /// A group's members as they are drawn: every layer's elements at frame 0, bottom layer + /// first (back to front). Empty for anything else. + pub fn group_members(&self) -> Vec> { + match self { + ElementKind::Group { members } => members.layers.iter().rev().filter_map(|l| l.keyframe_at(0)).flat_map(|k| k.elements.iter().cloned()).collect(), + _ => Vec::new(), + } + } +} + +/// Groups nested deeper than this are not drawn, walked or kept (guards hostile files). +pub const MAX_GROUP_DEPTH: usize = 32; + +/// `elements` with every group replaced by its members, however deep (ADR 0073), in drawing +/// order, each placed and coloured as the group shows it (the group's transform and colour +/// effect composed into it); borrowed when there is no group. For walkers that look for what is +/// placed (symbol instances, sounds, the player's instances): members keep their own ids. +pub fn expand_groups(elements: &[Arc]) -> std::borrow::Cow<'_, [Arc]> { + if !elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. })) { + return std::borrow::Cow::Borrowed(elements); + } + fn walk(els: &[Arc], at: Option<(&Affine, &ColorEffect)>, depth: usize, out: &mut Vec>) { + for e in els { + let placed = |e: &Arc| match at { + None => e.clone(), + Some((xf, fx)) => { + let mut c = (**e).clone(); + c.transform = xf.mul(&e.transform); + c.color = fx.nested(&e.color); + Arc::new(c) + } + }; + match &e.kind { + ElementKind::Group { .. } if depth < MAX_GROUP_DEPTH => { + let g = placed(e); + walk(&e.kind.group_members(), Some((&g.transform, &g.color)), depth + 1, out); + } + ElementKind::Group { .. } => {} + _ => out.push(placed(e)), + } + } + } + let mut out = Vec::new(); + walk(elements, None, 0, &mut out); + std::borrow::Cow::Owned(out) } /// How an instance's pixels combine with what is below it, as Animate's Blending menu. Every @@ -461,43 +767,169 @@ pub struct TextBlock { /// The layout box. pub box_width: f32, pub box_height: f32, + /// A dynamic or input text field (ADR 0066); `None`: static text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field: Option, + /// Text on a path (ADR 0070): its baseline follows this path instead of running in lines; + /// `outline` holds the glyphs set along it. Static text only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub on_path: Option, } -/// Colour effect applied to an element and everything inside it. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ColorEffect { - /// Alpha multiplier `0..=1`. - pub alpha: f32, - /// Tint colour mixed in by `tint_amount`. - pub tint: Rgba, - pub tint_amount: f32, +/// The path a text block follows (ADR 0070), and where along it the text sits. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextPath { + /// The baseline's path, in the block's own space (its first subpath counts). + pub path: Path, + /// Where the text is anchored along the path (pixels from its start): the block's + /// alignment says how (left: starts there, centre: centred on it, right: ends there). + #[serde(default)] + pub offset: f32, + /// The text runs along the path backwards, on its other side. + #[serde(default, skip_serializing_if = "is_false")] + pub flip: bool, } -impl Default for ColorEffect { - fn default() -> Self { - ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 } +/// Longest stretch along a path a text's offset may be (pixels either way). +pub const MAX_PATH_OFFSET: f32 = 1_000_000.0; + +impl TextBlock { + /// What kind of text it is: static, dynamic or input. + pub fn kind(&self) -> TextKind { + self.field.as_ref().map_or(TextKind::Static, |f| f.kind) } } -impl ColorEffect { - /// Effect of `inner` nested inside `self`. - pub fn concat(&self, inner: &ColorEffect) -> ColorEffect { - // Tints compose by keeping the stronger one; alpha multiplies. - let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) }; - ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount } - } - pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { - ColorEffect { - alpha: anicraft_geom::lerp(self.alpha, o.alpha, t), - tint: self.tint.lerp(o.tint, t), - tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t), +/// Animate's three text types (ADR 0066). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TextKind { + /// Drawn as laid out; scripts can't reach it. + #[default] + Static, + /// Scripts set and read its text (`field.text`) while the movie plays. + Dynamic, + /// The viewer types into it while the movie plays; scripts read what was typed. + Input, +} + +impl TextKind { + pub const ALL: [TextKind; 3] = [TextKind::Static, TextKind::Dynamic, TextKind::Input]; + pub fn key(self) -> &'static str { + match self { + TextKind::Static => "static", + TextKind::Dynamic => "dynamic", + TextKind::Input => "input", } } - pub fn apply(&self, c: Rgba) -> Rgba { - let k = self.tint_amount.clamp(0.0, 1.0); - let mut out = c.lerp(self.tint.with_alpha(c.a), k); - out.a = c.a * self.alpha.clamp(0.0, 1.0); - out + pub fn from_key(s: &str) -> Option { + TextKind::ALL.into_iter().find(|k| k.key() == s.trim().to_ascii_lowercase()) + } +} + +/// A field's line type, as Animate's Properties name them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LineType { + /// One line: Enter types nothing, the text scrolls sideways to keep the caret in view. + #[default] + Single, + /// Lines wrap at the field's width. + Multiline, + /// Lines break only where the text does. + MultilineNoWrap, + /// One line, drawn as `*` (input fields). + Password, +} + +impl LineType { + pub const ALL: [LineType; 4] = [LineType::Single, LineType::Multiline, LineType::MultilineNoWrap, LineType::Password]; + pub fn key(self) -> &'static str { + match self { + LineType::Single => "single", + LineType::Multiline => "multiline", + LineType::MultilineNoWrap => "multiline_no_wrap", + LineType::Password => "password", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); + LineType::ALL.into_iter().find(|k| k.key() == s) + } + /// More than one line (Enter starts a new one). + pub fn multiline(self) -> bool { + matches!(self, LineType::Multiline | LineType::MultilineNoWrap) + } +} + +/// The inset of text in a field's box, on every side, in pixels (as Animate's fields have). +pub const FIELD_GUTTER: f32 = 2.0; +/// Longest text a field holds (characters). +pub const MAX_FIELD_CHARS: usize = 16_384; +/// Longest instance or variable name (characters). +pub const MAX_FIELD_NAME: usize = 256; + +/// A dynamic or input text field (ADR 0066): how it is drawn and how the viewer may use it. The +/// element's name is its instance name; the block's text is what it shows before a script or the +/// viewer changes it. Its box is the block's `box_width` × `box_height` (fixed, not the text's +/// size), and its outline is the shown text laid out [`FIELD_GUTTER`] inside the box, so +/// everything that draws or measures text works on fields unchanged. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextField { + pub kind: TextKind, + #[serde(default)] + pub lines: LineType, + /// The viewer can select its text (dynamic fields; input fields always can). + #[serde(default = "yes")] + pub selectable: bool, + /// A line around the box, and a fill behind the text. + #[serde(default)] + pub border: bool, + #[serde(default = "black")] + pub border_color: Rgba, + #[serde(default)] + pub background: bool, + #[serde(default = "white")] + pub background_color: Rgba, + /// Most characters the viewer may type (0: no limit). + #[serde(default)] + pub max_chars: u32, + /// The ActionScript 1/2 variable the field shows (kept from Animate documents, not run). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub variable: String, +} + +fn black() -> Rgba { + Rgba::BLACK +} +fn white() -> Rgba { + Rgba::WHITE +} + +impl TextField { + /// A single-line field of `kind`. + pub fn new(kind: TextKind) -> TextField { + TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new() } + } + + /// The width text wraps at in a box `box_width` wide, if its lines wrap. + pub fn wrap_width(&self, box_width: f32) -> Option { + (self.lines == LineType::Multiline).then(|| (box_width - 2.0 * FIELD_GUTTER).max(1.0)) + } + + /// What a field shows for `text`: `*` for each character of a password. + pub fn shown(&self, text: &str) -> String { + if self.lines == LineType::Password && self.kind == TextKind::Input { text.chars().map(|_| '*').collect() } else { text.to_string() } + } + + /// The viewer can focus it: an input field, or a selectable dynamic one. + pub fn focusable(&self) -> bool { + self.kind == TextKind::Input || (self.kind == TextKind::Dynamic && self.selectable) + } + + /// Values in range: names cut to length, at most [`MAX_FIELD_CHARS`] typed. + pub fn sanitized(&self) -> TextField { + TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), ..self.clone() } } } @@ -536,6 +968,13 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Re } ElementKind::Text(t) => Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0)).transformed(xf), ElementKind::Camera => Rect::EMPTY, + ElementKind::Group { .. } => { + let mut r = Rect::EMPTY; + for child in el.kind.group_members() { + r = r.union(&element_bounds(doc, &child, &xf.mul(&child.transform), depth + 1)); + } + r + } ElementKind::Symbol { symbol, .. } => { let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY }; let mut r = Rect::EMPTY; @@ -679,10 +1118,20 @@ pub struct Layer { pub visible: bool, #[serde(default)] pub locked: bool, + /// View as Outlines (ADR 0061): the stage draws the layer's artwork as hairlines in + /// [`Layer::color`]. Never in the movie or an export. #[serde(default)] pub outline: bool, #[serde(default = "default_layer_color")] pub color: Rgba, + /// Onion skin draws this layer's frames around the playhead (ADR 0061); off, only its + /// playhead frame shows. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub onion: bool, + /// Row height on the timeline as a multiple of a normal row (ADR 0061): 1, 2 or 3 (100, + /// 200 or 300 %), as Animate's Layer Properties offer. Read through [`Layer::height`]. + #[serde(default = "one", skip_serializing_if = "is_one", rename = "height")] + pub height_rows: u8, #[serde(default)] pub keyframes: Vec>, /// Layer depth (ADR 0027), pixels behind the stage (negative: in front): the camera's pans @@ -698,8 +1147,59 @@ pub struct Layer { /// 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>, + /// How a mask layer's artwork reveals what it masks (ADR 0070): its fill area (Animate's + /// masks), or its opacity or brightness (soft masks). Ignored on other kinds of layer. + #[serde(default, skip_serializing_if = "MaskMode::is_coverage")] + pub mask_mode: MaskMode, } +/// How a mask layer's artwork reveals the layers it masks (ADR 0070). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskMode { + /// Its fills' area, fully opaque: colours, opacity and strokes don't matter (as in Animate). + #[default] + Coverage, + /// Its artwork as drawn (fills, strokes, gradients, bitmaps, opacity): the artwork's + /// opacity reveals (Animate users get this with alpha-gradient masks; SVG `mask-type: alpha`). + Alpha, + /// Its artwork's brightness times its opacity reveals: white shows, black hides (SVG's + /// default `mask`). Luminance uses the sRGB coefficients 0.2125, 0.7154, 0.0721. + Luminance, +} + +impl MaskMode { + pub const ALL: [MaskMode; 3] = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance]; + pub fn is_coverage(&self) -> bool { + *self == MaskMode::Coverage + } + /// Whether the artwork's colours and opacity count (not just its area). + pub fn is_soft(self) -> bool { + self != MaskMode::Coverage + } + pub fn key(self) -> &'static str { + match self { + MaskMode::Coverage => "coverage", + MaskMode::Alpha => "alpha", + MaskMode::Luminance => "luminance", + } + } + pub fn from_key(k: &str) -> Option { + MaskMode::ALL.into_iter().find(|m| m.key() == k) + } + /// How much a premultiplied colour reveals in this mode, `0..=1`. + pub fn reveal(self, premul: [f32; 4]) -> f32 { + let v = match self { + MaskMode::Coverage | MaskMode::Alpha => premul[3], + MaskMode::Luminance => LUMA[0] * premul[0] + LUMA[1] * premul[1] + LUMA[2] * premul[2], + }; + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } + } +} + +/// The luminance coefficients of a luminance mask (SVG's `luminanceToAlpha`, on sRGB values). +pub const LUMA: [f32; 3] = [0.2125, 0.7154, 0.0721]; + fn is_zero(v: &f32) -> bool { *v == 0.0 } @@ -709,6 +1209,18 @@ fn full() -> f32 { fn is_full(v: &f32) -> bool { *v == 1.0 } +fn is_true(v: &bool) -> bool { + *v +} +fn one() -> u8 { + 1 +} +fn is_one(v: &u8) -> bool { + *v == 1 +} + +/// Tallest a layer's timeline row gets, in normal rows (300 %). +pub const MAX_LAYER_HEIGHT: u8 = 3; impl PartialEq for Layer { fn eq(&self, o: &Layer) -> bool { @@ -720,9 +1232,12 @@ impl PartialEq for Layer { && self.locked == o.locked && self.outline == o.outline && self.color == o.color + && self.onion == o.onion + && self.height_rows == o.height_rows && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted + && self.mask_mode == o.mask_mode && match (&self.armature, &o.armature) { (Some(a), Some(b)) => arc_eq(a, b), (a, b) => a.is_none() && b.is_none(), @@ -749,13 +1264,20 @@ impl Layer { locked: false, outline: false, color: default_layer_color(), + onion: true, + height_rows: 1, keyframes: vec![Arc::new(Keyframe::new(0, 1))], depth: 0.0, volume: 1.0, muted: false, armature: None, + mask_mode: MaskMode::Coverage, } } + /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. + pub fn height(&self) -> u8 { + self.height_rows.clamp(1, MAX_LAYER_HEIGHT) + } /// The gain this layer gives its sounds: its volume, or silence when muted. pub fn sound_gain(&self) -> f32 { if self.muted { @@ -1019,9 +1541,53 @@ pub struct Symbol { /// The class scripts know the symbol by (Animate's "linkage"), kept as text (ADR 0013). #[serde(default, skip_serializing_if = "Option::is_none")] pub linkage: Option, + /// Guides for 9-slice scaling (ADR 0055): an instance scaled keeps the corners outside them + /// unscaled. `None`: the symbol scales as a whole. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid: Option, + /// The guides as they were when 9-slice scaling was switched off (ADR 0057): switching it on + /// again brings them back where they were. Only kept, never drawn or applied. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid_kept: Option, pub timeline: Timeline, } +/// The four 9-slice guides of a symbol (ADR 0055), in the symbol's own space: two vertical +/// lines at `x = left` and `x = right`, two horizontal ones at `y = top` and `y = bottom`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ScaleGrid { + pub left: f32, + pub right: f32, + pub top: f32, + pub bottom: f32, +} + +impl ScaleGrid { + /// Guides a quarter of the way in from each edge of `bounds` (what turning guides on gives). + pub fn inset(bounds: &Rect) -> ScaleGrid { + let (w, h) = (bounds.width() * 0.25, bounds.height() * 0.25); + ScaleGrid { left: bounds.min.x + w, right: bounds.max.x - w, top: bounds.min.y + h, bottom: bounds.max.y - h } + } + + /// Whether the guides are usable: finite, within the format's range, and in order. + pub fn check(&self) -> Result<(), String> { + let v = [self.left, self.right, self.top, self.bottom]; + if !v.iter().all(|x| x.is_finite() && x.abs() <= MAX_GRID_COORD) { + return Err(format!("9-slice guides must be numbers within ±{MAX_GRID_COORD}")); + } + if self.left > self.right { + return Err("the left 9-slice guide must not be right of the right one".into()); + } + if self.top > self.bottom { + return Err("the top 9-slice guide must not be below the bottom one".into()); + } + Ok(()) + } +} + +/// Largest 9-slice guide coordinate accepted from files and commands. +pub const MAX_GRID_COORD: f32 = 1_000_000.0; + /// A symbol's script class: what scripts create it by, and the class it extends. Kept with /// the document and shown, never run (ADR 0013 tier 1). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -1069,11 +1635,15 @@ pub struct Scene { pub name: String, #[serde(default)] pub timeline: Timeline, + /// The scene's guides (View › Guides, ADR 0076), in stage pixels. Animate keeps guides per + /// scene too; they show on the stage only, never in a picture or an export. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub guides: Vec, } impl Scene { pub fn new(name: impl Into) -> Scene { - Scene { name: name.into(), timeline: Timeline::default() } + Scene { name: name.into(), timeline: Timeline::default(), guides: Vec::new() } } } @@ -1104,10 +1674,28 @@ pub struct Document { /// (ADR 0013 tier 1); empty when there is none. #[serde(default, skip_serializing_if = "String::is_empty")] pub document_class: String, + /// File › Publish Settings: the formats Publish writes and their options (ADR 0060). + #[serde(default, skip_serializing_if = "publish_is_default")] + pub publish: Arc, + /// The Swatches panel's colours and gradients (ADR 0078). A file without them opens with + /// the default set, which is written only once changed. + #[serde(default = "default_swatches", skip_serializing_if = "swatches_are_default")] + pub swatches: Arc>, + /// How the grid and the guides look (ADR 0076). + #[serde(default, skip_serializing_if = "aids_is_default")] + pub aids: Arc, /// Next free id for layers, elements and symbols. pub next_id: u64, } +fn default_swatches() -> Arc> { + Arc::new(swatch::default_set()) +} + +fn swatches_are_default(v: &Arc>) -> bool { + swatch::is_default_set(v) +} + /// What a document file may hold: `scenes`, or (files before scenes) a single `timeline`. #[derive(Deserialize)] struct DocumentFile { @@ -1127,6 +1715,12 @@ struct DocumentFile { library_tree: Arc, #[serde(default)] document_class: String, + #[serde(default)] + publish: Arc, + #[serde(default = "default_swatches")] + swatches: Arc>, + #[serde(default)] + aids: Arc, #[serde(default = "first_id")] next_id: u64, } @@ -1135,9 +1729,9 @@ impl From for Document { fn from(f: DocumentFile) -> Document { let mut scenes = f.scenes; if let Some(tl) = f.timeline { - scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl })); + scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl, guides: Vec::new() })); } - Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, next_id: f.next_id } + Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, next_id: f.next_id } } } @@ -1149,18 +1743,26 @@ fn library_tree_is_empty(t: &Arc) -> bool { t.is_empty() } +fn aids_is_default(a: &Arc) -> bool { + a.is_default() +} + +fn publish_is_default(p: &Arc) -> bool { + p.is_default() +} + /// What `timeline(i)` returns for a scene that does not exist (never for a sanitized document). static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() }; impl PartialEq for Document { fn eq(&self, o: &Document) -> bool { - self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) + self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches) } } impl Default for Document { fn default() -> Self { - let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1218,9 +1820,15 @@ impl Document { pub fn scene_start(&self, i: usize) -> u32 { self.scenes.iter().take(i).map(|s| s.timeline.frame_count()).fold(0u32, u32::saturating_add) } - /// Every timeline: the scenes', then the library symbols'. + /// Every timeline: the scenes', then the library symbols', then the groups' inside them (ADR + /// 0073), so whatever walks every timeline (Library uses, sounds, paths) sees inside groups. pub fn timelines(&self) -> impl Iterator { - self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) + let top: Vec<&Timeline> = self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)).collect(); + let mut all = top.clone(); + for tl in top { + group_timelines(tl, 0, &mut all); + } + all.into_iter() } /// Repairs a loaded document: ids, sizes and keyframe order. pub fn sanitize(&mut self) { @@ -1232,15 +1840,26 @@ impl Document { } s.fps = s.fps.clamp(1.0, 240.0); s.background = s.background.sanitized(); + let aids = self.aids.sanitized(); + if aids != *self.aids { + self.aids = Arc::new(aids); + } 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); + // A shape armature's joint nodes take ids from the same counter (ADR 0071). + *max_id = (*max_id).max(b.id.0).max(b.child.0).max(b.parent.0); } for k in &l.keyframes { for e in &k.elements { *max_id = (*max_id).max(e.id.0); + // Warp pins take ids from the same counter (ADR 0079). + if let ElementKind::Shape(s) = &e.kind { + for p in s.warp.iter().flat_map(|w| &w.pins) { + *max_id = (*max_id).max(p.id.0); + } + } } } }; @@ -1252,13 +1871,18 @@ impl Document { if scene.name.trim().is_empty() || scene.name.len() > 256 { Arc::make_mut(scene).name = format!("Scene {}", i + 1); } + if scene.guides.len() > MAX_GUIDES || scene.guides.iter().any(|g| !(g.at.is_finite() && g.at.abs() <= GUIDE_REACH)) { + aids::sanitize_guides(&mut Arc::make_mut(scene).guides); + } let tl = &mut Arc::make_mut(scene).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); sanitize_scripts(l); sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); + sanitize_groups(l, 0, &mut max_id); } tl.repair_masks(); } @@ -1266,11 +1890,29 @@ impl Document { if !self.document_class.is_empty() && !actions::valid_class_name(&self.document_class) { self.document_class.clear(); } + // Swatches that can't be repaired are dropped; at most MAX_SWATCHES are kept. + let swatches: Vec = self.swatches.iter().filter_map(Swatch::sanitized).take(MAX_SWATCHES).collect(); + if swatches != *self.swatches { + self.swatches = Arc::new(swatches); + } + let mut publish = (*self.publish).clone(); + publish.sanitize(); + if publish != *self.publish { + self.publish = Arc::new(publish); + } for sym in &mut self.library { max_id = max_id.max(sym.id.0); if sym.linkage.as_ref().is_some_and(|l| l.check().is_err()) { Arc::make_mut(sym).linkage = None; } + // 9-slice guides that aren't usable are dropped: the symbol scales as a whole. + if sym.scale_grid.as_ref().is_some_and(|g| g.check().is_err()) { + Arc::make_mut(sym).scale_grid = None; + } + // Kept guides (ADR 0057) only while 9-slice is off, and only usable ones. + if sym.scale_grid_kept.as_ref().is_some_and(|g| sym.scale_grid.is_some() || g.check().is_err()) { + Arc::make_mut(sym).scale_grid_kept = None; + } let tl = &mut Arc::make_mut(sym).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); @@ -1281,7 +1923,9 @@ impl Document { } sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); + sanitize_groups(l, 0, &mut max_id); } tl.repair_masks(); } @@ -1296,6 +1940,105 @@ impl Document { } } +/// The members' timelines of every group on `tl`'s keyframes, and of the groups inside them, in +/// order, up to [`MAX_GROUP_DEPTH`] deep. +fn group_timelines<'a>(tl: &'a Timeline, depth: usize, out: &mut Vec<&'a Timeline>) { + if depth >= MAX_GROUP_DEPTH { + return; + } + for e in tl.layers.iter().flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()) { + if let ElementKind::Group { members } = &e.kind { + out.push(members); + group_timelines(members, depth + 1, out); + } + } +} + +/// Repairs the groups on a loaded layer (ADR 0073), however deep: each group's members are one +/// frame of normal layers (a camera or armature layer inside one becomes a normal layer), every +/// layer at least one keyframe at frame 0, and groups past [`MAX_GROUP_DEPTH`] are dropped. Ids +/// inside count towards `max_id`. Touches only what needs it. +fn sanitize_groups(layer: &mut Arc, depth: usize, max_id: &mut u64) { + let has_groups = layer.keyframes.iter().any(|k| k.elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. }))); + if !has_groups { + return; + } + let l = Arc::make_mut(layer); + for k in &mut l.keyframes { + if !k.elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. })) { + continue; + } + let k = Arc::make_mut(k); + if depth >= MAX_GROUP_DEPTH { + k.elements.retain(|e| !matches!(e.kind, ElementKind::Group { .. })); + continue; + } + for e in &mut k.elements { + if !matches!(e.kind, ElementKind::Group { .. }) { + continue; + } + let ElementKind::Group { members } = &mut Arc::make_mut(e).kind else { continue }; + for gl in &mut members.layers { + *max_id = (*max_id).max(gl.id.0); + let bad_kind = matches!(gl.kind, LayerKind::Camera | LayerKind::Armature | LayerKind::Folder); + let bad_frames = gl.keyframes.len() != 1 || gl.keyframes.first().is_some_and(|k| k.start != 0 || k.duration != 1 || k.tween.is_some() || k.motion.is_some()); + if bad_kind || bad_frames { + let g = Arc::make_mut(gl); + if bad_kind { + g.kind = LayerKind::Normal; + g.armature = None; + } + if bad_frames { + // The frame a group shows (its first), as its only one. + let mut first = g.keyframes.iter().find(|k| k.start == 0).map_or_else(|| Keyframe::new(0, 1), |k| (**k).clone()); + first.duration = 1; + first.tween = None; + first.motion = None; + g.keyframes = vec![Arc::new(first)]; + } + } + for ge in gl.keyframes.iter().flat_map(|k| k.elements.iter()) { + *max_id = (*max_id).max(ge.id.0); + } + sanitize_groups(gl, depth + 1, max_id); + } + members.repair_masks(); + } + } +} + +/// Repairs the warps on a loaded layer's shapes (ADR 0079): a warp with nothing usable left +/// goes (the shape keeps the outline it shows), and hostile pins are dropped. Touches only what +/// needs it. +fn sanitize_warps(layer: &mut Arc) { + let bad = |e: &Element| match &e.kind { + ElementKind::Shape(Shape { warp: Some(w), .. }) => { + let mut x = (**w).clone(); + !x.sanitize() || x != **w + } + _ => false, + }; + if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| bad(e))) { + return; + } + for k in &mut Arc::make_mut(layer).keyframes { + if !k.elements.iter().any(|e| bad(e)) { + continue; + } + for e in &mut Arc::make_mut(k).elements { + if !bad(e) { + continue; + } + if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind + && let Some(w) = &s.warp + { + let mut x = (**w).clone(); + s.warp = x.sanitize().then(|| Arc::new(x)); + } + } + } +} + /// Keeps a loaded layer's depth finite and in range (touching it only if it isn't). fn sanitize_depth(layer: &mut Arc) { let d = camera::clamp_depth(layer.depth); @@ -1364,6 +2107,10 @@ fn sanitize_scripts(layer: &mut Arc) { } } +#[cfg(test)] +#[path = "gradient_tests.rs"] +mod gradient_tests; + #[cfg(test)] #[path = "camera_tests.rs"] mod camera_tests; diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 6d5f6b6e..d088d096 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -323,7 +323,8 @@ impl Document { /// symbols). Items used nowhere are left out. pub fn library_uses(&self) -> HashMap { let mut uses: HashMap = HashMap::new(); - for tl in self.timelines() { + // (Groups' timelines are walked by `visit_refs` itself.) + for tl in self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) { visit_refs(tl, |item| *uses.entry(item).or_default() += 1); } uses @@ -388,7 +389,7 @@ impl Document { let src = self.library.get(at)?.clone(); let new_id = SymbolId(self.alloc_id()); let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id()); - let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, timeline }; + let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, scale_grid_kept: src.scale_grid_kept, scale_grid: src.scale_grid, timeline }; self.library.insert(at + 1, Arc::new(copy)); if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() { Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f); @@ -453,8 +454,15 @@ impl Document { } /// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap -/// fills and the keyframe's sound. +/// fills and the keyframe's sound, inside groups too (ADR 0073). pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) { + visit_refs_in(tl, &mut f, 0); +} + +fn visit_refs_in(tl: &Timeline, f: &mut impl FnMut(LibraryItem), depth: usize) { + if depth > crate::MAX_GROUP_DEPTH { + return; + } for l in &tl.layers { for k in &l.keyframes { for e in &k.elements { @@ -465,6 +473,7 @@ pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) { f(LibraryItem::Bitmap(*bitmap)); } } + ElementKind::Group { members } => visit_refs_in(members, f, depth + 1), ElementKind::Text(_) | ElementKind::Camera => {} } } diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs index f5a66bbe..d737b7ab 100644 --- a/crates/doc/src/library_tests.rs +++ b/crates/doc/src/library_tests.rs @@ -19,7 +19,7 @@ fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId { if let Some(k) = layer.keyframe_mut(0) { k.elements = els; } - d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); id } diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index bbe806a3..75c6beab 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -2,7 +2,7 @@ //! //! A classic tween interpolates a whole keyframe into the next one. A motion tween instead //! belongs to one keyframe span and one object in it (its *target*). Each property (x, y, -//! scale, rotation, skew, alpha, tint) may have a [`Track`] of property keyframes anywhere in +//! scale, rotation, skew, and the colour effect's alpha, brightness, tint and advanced values) may have a [`Track`] of property keyframes anywhere in //! the span; between two keys the value follows the segment's [`Easing`], which may be a custom //! cubic Bézier. A property without a track keeps the target's own value (its *base*: how it //! looks on the span's first frame). Evaluation is pure: [`MotionTween::apply`] maps the base @@ -21,7 +21,7 @@ //! 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 crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, Easing, Rgba}; use anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; @@ -35,7 +35,7 @@ pub const MAX_KEYS: usize = 10_000; pub const MAX_PATH_SEGMENTS: usize = 1_000; /// A property a motion tween animates. Values are in the units the Motion Editor shows: -/// pixels, percent and degrees. +/// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Property { @@ -49,13 +49,64 @@ pub enum Property { Rotation, /// Degrees of horizontal skew, within ±89. Skew, - /// Colour effect: opacity and tint amount, percent. + /// Colour effect (ADR 0056), by style. Alpha: opacity, percent. Alpha, + /// Brightness, −100..=100 %. + Brightness, + /// Tint amount, percent, and the tint colour's channels, 0–255. Tint, + TintRed, + TintGreen, + TintBlue, + /// Advanced: each channel's multiplier, −100..=100 %, and offset, −255..=255. + RedMultiplier, + GreenMultiplier, + BlueMultiplier, + AlphaMultiplier, + RedOffset, + GreenOffset, + BlueOffset, + AlphaOffset, } +/// How many properties there are. +pub const PROPERTIES: usize = 20; + impl Property { - pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint]; + pub const ALL: [Property; PROPERTIES] = [ + Property::X, + Property::Y, + Property::ScaleX, + Property::ScaleY, + Property::Rotation, + Property::Skew, + Property::Alpha, + Property::Brightness, + Property::Tint, + Property::TintRed, + Property::TintGreen, + Property::TintBlue, + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; + + /// The Advanced properties: multipliers then offsets, red first. + pub const ADVANCED: [Property; 8] = [ + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; /// The name used in files and commands (`x`, `scale_x`, `alpha`…). pub fn key(self) -> &'static str { @@ -67,7 +118,19 @@ impl Property { Property::Rotation => "rotation", Property::Skew => "skew", Property::Alpha => "alpha", + Property::Brightness => "brightness", Property::Tint => "tint", + Property::TintRed => "tint_red", + Property::TintGreen => "tint_green", + Property::TintBlue => "tint_blue", + Property::RedMultiplier => "red_multiplier", + Property::GreenMultiplier => "green_multiplier", + Property::BlueMultiplier => "blue_multiplier", + Property::AlphaMultiplier => "alpha_multiplier", + Property::RedOffset => "red_offset", + Property::GreenOffset => "green_offset", + Property::BlueOffset => "blue_offset", + Property::AlphaOffset => "alpha_offset", } } @@ -80,24 +143,49 @@ impl Property { Property::Rotation => "Rotation", Property::Skew => "Skew", Property::Alpha => "Alpha", + Property::Brightness => "Brightness", Property::Tint => "Tint", + Property::TintRed => "Tint red", + Property::TintGreen => "Tint green", + Property::TintBlue => "Tint blue", + Property::RedMultiplier => "Red multiplier", + Property::GreenMultiplier => "Green multiplier", + Property::BlueMultiplier => "Blue multiplier", + Property::AlphaMultiplier => "Alpha multiplier", + Property::RedOffset => "Red offset", + Property::GreenOffset => "Green offset", + Property::BlueOffset => "Blue offset", + Property::AlphaOffset => "Alpha offset", } } pub fn unit(self) -> &'static str { match self { Property::X | Property::Y => "px", - Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%", + Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Brightness | Property::Tint => "%", + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => "%", Property::Rotation | Property::Skew => "°", + Property::TintRed | Property::TintGreen | Property::TintBlue | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => "", } } /// The Motion Editor's groups: Position, Transform, Colour effect. pub fn group(self) -> &'static str { + match self.style() { + None if matches!(self, Property::X | Property::Y) => "Position", + None => "Transform", + Some(_) => "Colour effect", + } + } + + /// The colour effect style a colour property belongs to (`None` for position and transform). + pub fn style(self) -> Option { match self { - Property::X | Property::Y => "Position", - Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform", - Property::Alpha | Property::Tint => "Colour effect", + Property::X | Property::Y | Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => None, + Property::Alpha => Some(ColorStyle::Alpha), + Property::Brightness => Some(ColorStyle::Brightness), + Property::Tint | Property::TintRed | Property::TintGreen | Property::TintBlue => Some(ColorStyle::Tint), + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => Some(ColorStyle::Advanced), } } @@ -108,6 +196,7 @@ impl Property { "scaley" => "scale_y", "rotate" => "rotation", "opacity" => "alpha", + "tint_amount" => "tint", other => other, }; Property::ALL.into_iter().find(|p| p.key() == s) @@ -121,6 +210,9 @@ impl Property { Property::Rotation => -100_000.0..=100_000.0, Property::Skew => -89.0..=89.0, Property::Alpha | Property::Tint => 0.0..=100.0, + Property::Brightness | Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => -100.0..=100.0, + Property::TintRed | Property::TintGreen | Property::TintBlue => 0.0..=255.0, + Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => -255.0..=255.0, } } @@ -129,7 +221,7 @@ impl Property { } fn is_transform(self) -> bool { - !matches!(self, Property::Alpha | Property::Tint) + self.style().is_none() } fn clamp(self, v: f32) -> f32 { @@ -140,13 +232,57 @@ impl Property { /// Every property's value, indexed like [`Property::ALL`]. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct Props(pub [f32; 8]); +pub struct Props(pub [f32; PROPERTIES]); impl Props { - /// An element's own values. + /// An element's own values. Colour properties come from its colour effect's style; the + /// other styles' properties hold their rest values (alpha 100 %, brightness 0, tint 0 % of + /// white, Advanced 100 % and 0). pub fn of(el: &Element) -> Props { let d = el.transform.decompose(); - Props([d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees(), d.skew.atan().to_degrees(), el.color.alpha * 100.0, el.color.tint_amount * 100.0]) + let mut p = Props([0.0; PROPERTIES]); + for (q, v) in [(Property::X, d.tx), (Property::Y, d.ty), (Property::ScaleX, d.sx * 100.0), (Property::ScaleY, d.sy * 100.0), (Property::Rotation, d.rotation.to_degrees()), (Property::Skew, d.skew.atan().to_degrees())] { + p.set(q, v); + } + p.set_colour(&el.color); + p + } + + /// Sets the colour properties from `fx`, as [`Props::of`] does. + fn set_colour(&mut self, fx: &ColorEffect) { + let (mut alpha, mut bright, mut tint, mut rgb, mut adv) = (1.0, 0.0, 0.0, Rgba::WHITE, ColorTransform::IDENTITY); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => alpha = a, + ColorEffect::Brightness(b) => bright = b, + ColorEffect::Tint { color, amount } => (tint, rgb) = (amount, color), + ColorEffect::Advanced(t) => adv = t, + } + self.set(Property::Alpha, alpha * 100.0); + self.set(Property::Brightness, bright * 100.0); + self.set(Property::Tint, tint * 100.0); + self.set(Property::TintRed, rgb.r * 255.0); + self.set(Property::TintGreen, rgb.g * 255.0); + self.set(Property::TintBlue, rgb.b * 255.0); + let values = adv.mul.iter().map(|m| m * 100.0).chain(adv.add.iter().map(|a| a * 255.0)); + for (q, v) in Property::ADVANCED.into_iter().zip(values) { + self.set(q, v); + } + } + + /// The colour effect of the styles in `styles` from these values (the other styles' values + /// are left out): one style alone is that style; several compose into Advanced (ADR 0056). + pub fn color_effect(&self, styles: &[ColorStyle]) -> ColorEffect { + let v = |p: Property| p.clamp(self.get(p)); + let on = |s: ColorStyle| styles.contains(&s); + let alpha = on(ColorStyle::Alpha).then(|| v(Property::Alpha) / 100.0); + let bright = on(ColorStyle::Brightness).then(|| v(Property::Brightness) / 100.0); + let tint = on(ColorStyle::Tint).then(|| (Rgba::new(v(Property::TintRed) / 255.0, v(Property::TintGreen) / 255.0, v(Property::TintBlue) / 255.0, 1.0), v(Property::Tint) / 100.0)); + let adv = on(ColorStyle::Advanced).then(|| { + let [rm, gm, bm, am, ro, go, bo, ao] = Property::ADVANCED.map(v); + ColorTransform { mul: [rm, gm, bm, am].map(|m| m / 100.0), add: [ro, go, bo, ao].map(|a| a / 255.0) } + }); + ColorEffect::compose(alpha, bright, tint, adv).sanitized() } pub fn get(&self, p: Property) -> f32 { self.0.get(p.index()).copied().unwrap_or(0.0) @@ -891,15 +1027,29 @@ impl MotionTween { el.transform = m; } } - if let Some(t) = self.track(Property::Alpha).and_then(|t| t.value_at(frame)) { - el.color.alpha = (t / 100.0).clamp(0.0, 1.0); - } - if let Some(t) = self.track(Property::Tint).and_then(|t| t.value_at(frame)) { - el.color.tint_amount = (t / 100.0).clamp(0.0, 1.0); + // Colour: the styles keyed here and the target's own, composed (ADR 0056). + if self.tracks.iter().any(|t| !t.property.is_transform()) { + el.color = props.color_effect(&self.colour_styles(&base.color)); } el } + /// The colour effect styles the target shows over the span. As in Animate, a motion tween + /// has one colour effect: the style its colour properties are keyed in, replacing the + /// target's own (which shows while none are keyed). Keys in several styles (older files + /// keyed alpha and tint together) compose into Advanced. + pub fn colour_styles(&self, own: &ColorEffect) -> Vec { + let mut out: Vec = Vec::new(); + let keyed = self.tracks.iter().filter_map(|t| t.property.style()); + let own = (own.style() != ColorStyle::None && !self.tracks.iter().any(|t| t.property.style().is_some())).then_some(own.style()); + for s in keyed.chain(own) { + if !out.contains(&s) { + out.push(s); + } + } + out + } + /// Sets property `p`'s key at `frame`. A property's first key also gets a key on the span's /// first frame holding `base` (its value until now), so the rest of the span is unchanged. pub fn set_key(&mut self, p: Property, frame: u32, value: f32, base: f32) { @@ -1083,7 +1233,7 @@ mod tests { m.set_key(Property::Alpha, 10, 0.0, 100.0); let at5 = m.apply(&base, 5.0); assert_eq!(at5.transform, base.transform, "colour-only tween keeps the transform bit for bit"); - assert!((at5.color.alpha - 0.5).abs() < 1e-6); + assert!((at5.color.alpha() - 0.5).abs() < 1e-6 && at5.color.style() == ColorStyle::Alpha); } #[test] @@ -1167,7 +1317,7 @@ mod tests { fn property_keys_round_trip() { for p in Property::ALL { assert_eq!(Property::from_key(p.key()), Some(p)); - assert!(!p.label().is_empty() && !p.unit().is_empty() && !p.group().is_empty()); + assert!(!p.label().is_empty() && (!p.unit().is_empty() || p.range() == (0.0..=255.0) || p.range() == (-255.0..=255.0)) && !p.group().is_empty()); } assert_eq!(Property::from_key("Scale X"), Some(Property::ScaleX)); assert_eq!(Property::from_key("nope"), None); diff --git a/crates/doc/src/nine_slice.rs b/crates/doc/src/nine_slice.rs new file mode 100644 index 00000000..e9e3d7be --- /dev/null +++ b/crates/doc/src/nine_slice.rs @@ -0,0 +1,84 @@ +//! 9-slice scaling of symbol instances (ADR 0055), as part of evaluation. +//! +//! A symbol with a [`ScaleGrid`] is drawn so that scaling an instance keeps the corners outside +//! its guides unscaled: the instance's transform is decomposed (`T · R · Skew · S`), and instead +//! of `S` the symbol's own shapes go through the 9-slice map of its box scaled by `S` +//! ([`anicraft_geom::slice`]); translation, rotation and skew apply after. Strokes keep their +//! width. Nested symbols, text and bitmap fills inside scale normally, as in Animate. + +use crate::{Document, ElementKind, LayerKind, ScaleGrid, Symbol}; +use anicraft_geom::slice::{Axis, Slice9}; +use anicraft_geom::{Affine, Rect}; + +/// How a sliced instance's shapes are drawn (see the module docs). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Slicing { + /// Symbol space to sliced space. + pub map: Slice9, + /// The instance's transform without its scale: sliced space to the parent's space. + pub post: Affine, + /// The scale left out of `post` (what plain scaling would have applied). + pub scale: Affine, +} + +/// Instance scale this close to 1 on both axes draws the symbol as it is. +const UNSCALED: f32 = 1e-4; + +/// The box 9-slice scaling divides: the control-point bounds of everything on the symbol's +/// keyframes (guide layers left out), so the box doesn't move as the symbol plays. Strokes don't +/// widen it: they keep their width. +pub fn symbol_box(doc: &Document, sym: &Symbol) -> Rect { + let mut r = Rect::EMPTY; + for layer in sym.timeline.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) { + for k in &layer.keyframes { + for e in &k.elements { + let b = match &e.kind { + ElementKind::Shape(s) => s.path.bounds().transformed(&e.transform), + _ => e.bounds(doc), + }; + if b.min.x.is_finite() && b.max.x.is_finite() && b.min.y.is_finite() && b.max.y.is_finite() { + r = r.union(&b); + } + } + } + } + r +} + +/// The slicing of an instance of `sym` placed by `transform`, or `None` when it draws normally: +/// no guides, no scale to absorb, or nothing to divide. +pub(crate) fn slicing(doc: &Document, sym: &Symbol, transform: &Affine) -> Option { + let grid = sym.scale_grid.filter(|g| g.check().is_ok())?; + let d = transform.decompose(); + let (sx, sy) = (d.sx, d.sy.abs()); + if ((sx - 1.0).abs() < UNSCALED && (sy - 1.0).abs() < UNSCALED) || !sx.is_finite() || !sy.is_finite() { + return None; + } + let b = symbol_box(doc, sym); + if b.is_empty() { + return None; + } + map_for(&grid, &b, sx, sy).map(|map| { + // `transform` is T·R·K·S; S = scale(sx, ±sy). Keep a flip in `post` (sliced magnitudes). + let flip = if d.sy < 0.0 { -1.0 } else { 1.0 }; + let rest = anicraft_geom::Decomposed { sx: 1.0, sy: flip, ..d }.compose(); + Slicing { map, post: rest, scale: Affine::scale(sx, sy) } + }) +} + +/// Whether an instance of `sym` placed by `transform` is drawn 9-sliced (exporters that place +/// symbols themselves say when they can't). +pub fn slices(doc: &Document, sym: &Symbol, transform: &Affine) -> bool { + slicing(doc, sym, transform).is_some() +} + +/// The 9-slice map of box `b` with guides `grid`, scaled by `sx`, `sy` (both at least 0). An +/// axis with no extent (a symbol only a line high) scales plainly. +pub fn map_for(grid: &ScaleGrid, b: &Rect, sx: f32, sy: f32) -> Option { + let axis = |lo: f32, a: f32, c: f32, hi: f32, k: f32| if hi > lo { Axis::new(lo, a, c, hi, k) } else { Axis::new(lo, lo, lo + 1.0, lo + 1.0, k) }; + Some(Slice9 { x: axis(b.min.x, grid.left, grid.right, b.max.x, sx)?, y: axis(b.min.y, grid.top, grid.bottom, b.max.y, sy)? }) +} + +#[cfg(test)] +#[path = "nine_slice_tests.rs"] +mod tests; diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs new file mode 100644 index 00000000..79029bc3 --- /dev/null +++ b/crates/doc/src/nine_slice_tests.rs @@ -0,0 +1,171 @@ +//! 9-slice scaling (ADR 0055), analytically: what evaluation draws for a scaled instance. + +use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, ScaleGrid, Shape, Symbol, SymbolId, SymbolKind, Timeline, evaluate}; +use anicraft_geom::{Affine, Path, Vec2}; +use std::sync::Arc; + +const SYM: SymbolId = SymbolId(900); + +fn el(id: u64, transform: Affine, kind: ElementKind) -> Element { + Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind } +} + +fn instance(of: SymbolId, transform: Affine) -> Element { + el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }) +} + +/// A 100×40 rounded rectangle (corner radius 10) at the symbol's origin, guides 10 in from each +/// edge, with `extra` inside it, and one instance of it on the stage placed by `xf`. +fn doc(xf: Affine, grid: Option, extra: Vec) -> Document { + let mut d = Document::default(); + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 100.0, 40.0, 10.0), Paint::Solid(Rgba::BLACK)); + shape.stroke = Some(crate::Stroke::new(Rgba::WHITE, 2.0)); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(el(2, Affine::IDENTITY, ElementKind::Shape(shape)))); + k.elements.extend(extra.into_iter().map(Arc::new)); + let mut layer = Layer::new(LayerId(901), "art"); + layer.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(instance(SYM, xf))); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)]; + d +} + +const GRID: ScaleGrid = ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 }; + +/// The stage-space outline of the first item, finely flattened. +fn outline(d: &Document) -> Vec { + let dl = evaluate(d, 0); + let it = &dl.items[0]; + it.path.flatten(&it.transform, 0.005).into_iter().flat_map(|l| l.points).collect() +} + +/// How far `p` is from the polyline `pts` (closed). +fn dist(pts: &[Vec2], p: Vec2) -> f32 { + let n = pts.len(); + (0..n).map(|i| anicraft_geom::segment_distance(p, pts[i], pts[(i + 1) % n])).fold(f32::INFINITY, f32::min) +} + +/// A point on the source corner arc of the rounded rectangle, `a` radians round the corner +/// centred at `c`. +fn arc(c: Vec2, a: f32) -> Vec2 { + c + Vec2::new(a.cos(), a.sin()) * 10.0 +} + +#[test] +fn a_rounded_rect_scaled_3x_keeps_its_corner_radii_exact() { + let d = doc(Affine::scale(3.0, 3.0), Some(GRID), Vec::new()); + let pts = outline(&d); + // The box lands where plain scaling puts it: 0..300 by 0..120. + let (lo, hi) = pts.iter().fold((Vec2::new(f32::MAX, f32::MAX), Vec2::new(f32::MIN, f32::MIN)), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))); + assert!((lo.x).abs() < 1e-3 && (lo.y).abs() < 1e-3 && (hi.x - 300.0).abs() < 1e-3 && (hi.y - 120.0).abs() < 1e-3, "{lo:?} {hi:?}"); + // Each corner is the same radius-10 arc, moved to its corner of the bigger box. + let corners = [(Vec2::new(10.0, 10.0), Vec2::ZERO, 180.0f32), (Vec2::new(90.0, 10.0), Vec2::new(200.0, 0.0), 270.0), (Vec2::new(90.0, 30.0), Vec2::new(200.0, 80.0), 0.0), (Vec2::new(10.0, 30.0), Vec2::new(0.0, 80.0), 90.0)]; + for (c, shift, from) in corners { + for i in 0..=8 { + let a = (from + i as f32 * 90.0 / 8.0).to_radians(); + let want = arc(c, a) + shift; + let d = dist(&pts, want); + assert!(d < 0.02, "corner at {c:?}, {i}/8: {d}"); + // And the arc's centre is still 10 from it: the radius is exact, not stretched. + assert!(((want - (c + shift)).length() - 10.0).abs() < 1e-3); + } + } + // Without guides, the same instance is a plain 3× scale (corners radius 30). + let plain = evaluate(&doc(Affine::scale(3.0, 3.0), None, Vec::new()), 0); + assert_eq!(plain.items[0].transform, Affine::scale(3.0, 3.0)); +} + +#[test] +fn the_centre_scales_by_the_remainder_and_edges_one_way() { + // 2× wide, 1.5× high: 200 × 60. The centre is 200 − 20 = 180 wide (80 → 180) and + // 60 − 20 = 40 high (20 → 40). + let d = doc(Affine::scale(2.0, 1.5), Some(GRID), Vec::new()); + let it = &evaluate(&d, 0).items[0]; + let map = |p: Vec2| it.transform.apply(p); + let pts = outline(&d); + // The middle of the top edge (50, 0) lands at (100, 0); of the left edge (0, 20) at (0, 30). + assert!(dist(&pts, Vec2::new(100.0, 0.0)) < 1e-3); + assert!(dist(&pts, Vec2::new(0.0, 30.0)) < 1e-3); + // The straight top edge runs from x = 10 to x = 190 (the corners are 10 each). + assert!(dist(&pts, Vec2::new(10.0, 0.0)) < 1e-3 && dist(&pts, Vec2::new(190.0, 0.0)) < 1e-3); + // The stroke keeps its width (no scale is left in the item's transform). + assert_eq!(map(Vec2::new(1.0, 0.0)) - map(Vec2::ZERO), Vec2::new(1.0, 0.0)); + assert_eq!(it.stroke.as_ref().map(|s| s.width), Some(2.0)); +} + +#[test] +fn no_spare_space_clamps_the_corners_and_closes_the_centre() { + // 0.1× wide: 10 across, less than the corners' 20. They share it (5 each) and the centre is + // a line; nothing turns inside out. + let d = doc(Affine::scale(0.1, 1.0), Some(GRID), Vec::new()); + let pts = outline(&d); + assert!(pts.iter().all(|p| p.x >= -1e-3 && p.x <= 10.0 + 1e-3), "{pts:?}"); + assert!(dist(&pts, Vec2::new(5.0, 0.0)) < 1e-3); + // Exactly no spare space (0.2× → 20 across): corners full size, the centre a line. + let pts = outline(&doc(Affine::scale(0.2, 1.0), Some(GRID), Vec::new())); + assert!(dist(&pts, arc(Vec2::new(10.0, 10.0), 225f32.to_radians())) < 0.02); + assert!(pts.iter().all(|p| p.x <= 20.0 + 1e-3)); + // Zero scale: everything on one line, still finite. + let pts = outline(&doc(Affine::scale(0.0, 1.0), Some(GRID), Vec::new())); + assert!(pts.iter().all(|p| p.x.abs() < 1e-3 && p.y.is_finite())); +} + +#[test] +fn rotation_skew_and_flips_apply_after_slicing() { + let rot = 30f32.to_radians(); + let xf = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)).mul(&Affine::scale(3.0, 3.0)); + let d = doc(xf, Some(GRID), Vec::new()); + let it = &evaluate(&d, 0).items[0]; + // The item's transform is the instance's translation and rotation, with no scale. + let expect = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)); + assert!(it.transform.m.iter().zip(expect.m).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", it.transform); + // The sliced corner (the top-right arc, moved by 200) turns with the instance. + let pts = outline(&d); + let want = expect.apply(arc(Vec2::new(90.0, 10.0), 315f32.to_radians()) + Vec2::new(200.0, 0.0)); + assert!(dist(&pts, want) < 0.02); + // A horizontal flip slices by the magnitude, then mirrors. + let flip = doc(Affine::scale(3.0, -3.0), Some(GRID), Vec::new()); + let it = &evaluate(&flip, 0).items[0]; + assert!((it.transform.determinant() + 1.0).abs() < 1e-4); + let pts = outline(&flip); + assert!(dist(&pts, Vec2::new(300.0, -120.0)).is_finite() && pts.iter().all(|p| p.y <= 1e-3 && p.y >= -120.0 - 1e-3)); +} + +#[test] +fn unscaled_instances_and_nested_symbols_draw_as_they_are() { + // At scale 1 nothing is cut: the symbol's own path is drawn, shared. + let d = doc(Affine::translate(5.0, 5.0), Some(GRID), Vec::new()); + let dl = evaluate(&d, 0); + let ElementKind::Shape(s) = &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind else { panic!("the panel is a shape") }; + let sym_path = s.path.clone(); + assert!(Arc::ptr_eq(&dl.items[0].path, &sym_path)); + // A nested symbol inside scales normally: its item carries the whole 3× scale. + let mut d = doc(Affine::scale(3.0, 3.0), Some(GRID), vec![instance(SymbolId(950), Affine::translate(50.0, 20.0))]); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(el(3, Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::WHITE)))))); + let mut l = Layer::new(LayerId(951), "dot"); + l.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } })); + let dl = evaluate(&d, 0); + let dot = dl.items.iter().find(|i| i.path.bounds().width() == 4.0).unwrap(); + assert_eq!(dot.transform, Affine::scale(3.0, 3.0).mul(&Affine::translate(50.0, 20.0))); +} + +#[test] +fn hostile_guides_and_scales_never_break_evaluation() { + for grid in [ + ScaleGrid { left: 90.0, right: 10.0, top: 10.0, bottom: 30.0 }, + ScaleGrid { left: f32::NAN, right: 10.0, top: 10.0, bottom: 30.0 }, + ScaleGrid { left: -1e9, right: 1e9, top: -5.0, bottom: 500.0 }, + ScaleGrid { left: 50.0, right: 50.0, top: 20.0, bottom: 20.0 }, + ] { + for xf in [Affine::scale(3.0, 3.0), Affine::scale(1e-30, 1e30), Affine::scale(f32::INFINITY, 1.0), Affine { m: [0.0, 0.0, 0.0, 0.0, 1.0, 1.0] }] { + let dl = evaluate(&doc(xf, Some(grid), Vec::new()), 0); + for it in &dl.items { + let _ = it.path.flatten(&it.transform, 0.25); + } + } + } +} diff --git a/crates/doc/src/path_table.rs b/crates/doc/src/path_table.rs index 8ea7105a..5ce8d324 100644 --- a/crates/doc/src/path_table.rs +++ b/crates/doc/src/path_table.rs @@ -41,10 +41,17 @@ pub fn build_table(doc: &Document) -> Vec> { for layer in &tl.layers { for k in &layer.keyframes { for e in &k.elements { + // A warped shape's outline as drawn (ADR 0079) is written once too. + if let ElementKind::Shape(s) = &e.kind + && let Some(w) = &s.warp + && seen.insert(Arc::as_ptr(&w.rest) as usize, ()).is_none() + { + out.push(w.rest.clone()); + } let path = match &e.kind { ElementKind::Shape(s) => &s.path, ElementKind::Text(t) => &t.outline, - ElementKind::Symbol { .. } | ElementKind::Camera => continue, + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => continue, }; if seen.insert(Arc::as_ptr(path) as usize, ()).is_none() { out.push(path.clone()); diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index e3170648..8e00dc67 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -14,11 +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::as3::ir::{Base, Function, ListenEvent, Place, Prop, Value}; +use crate::actions::as3::run::{self, Stop, World}; +use crate::actions::as3::{Compiled, Decls, Problem}; use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target}; use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk}; +use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret}; use crate::sound::Started; -use crate::{Document, Element, ElementId, ElementKind, LayerKind, MAX_SYMBOL_DEPTH, SymbolId, SymbolKind, Timeline}; +use crate::{BlendMode, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, FIELD_GUTTER, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, TextBlock, TextField, TextKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -40,6 +43,13 @@ pub const MAX_OUTPUT_PER_STEP: usize = 1_000; pub const MAX_EVENTS_PER_STEP: usize = 256; /// Most listeners scripts add to one instance. pub const MAX_LISTENERS_PER_INSTANCE: usize = 16; +/// Most listeners scripts add to the stage. +pub const MAX_STAGE_LISTENERS: usize = 64; +/// Script fuel one step may use, all scripts and listeners together (each run has at most +/// [`run::FUEL_PER_RUN`]). +pub const MAX_FUEL_PER_STEP: u64 = 1_000_000; +/// The random generator's seed when none is given. +pub const DEFAULT_SEED: u64 = 0; /// A timeline's playhead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -102,22 +112,60 @@ impl Overrides { } } if let Some(a) = self.alpha { - e.color.alpha = a; + e.color = e.color.with_alpha(a); } e } } -/// 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. +/// A listener a script added to an instance or the stage (ADR 0013 tiers 2 and 2.5): 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 event: ListenEvent, + /// The timeline whose script added it: the function runs there. pub owner: InstancePath, /// The function's name: the same function for the same event is added once. pub function: String, - pub actions: Arc>, + pub func: Arc, + /// When it was added (enter-frame listeners run in this order). + pub seq: u64, +} + +/// The movie's random numbers (`Math.random()`): Marsaglia's xorshift128, seeded, so a movie +/// with the same seed and input always plays the same. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rng(pub [u32; 4]); + +impl Rng { + pub fn seeded(seed: u64) -> Rng { + let lo = (seed & 0xffff_ffff) as u32; + let hi = (seed >> 32) as u32; + let mut s = [lo ^ 0x9e37_79b9, hi ^ 0x243f_6a88, 0xb7e1_5162, 0x3c6e_f372]; + if s == [0; 4] { + s[0] = 1; + } + Rng(s) + } + fn next_u32(&mut self) -> u32 { + let [x, y, z, w] = self.0; + let t = x ^ (x << 11); + let w2 = w ^ (w >> 19) ^ (t ^ (t >> 8)); + self.0 = [y, z, w, w2]; + w2 + } + /// The next number in [0, 1), from 53 random bits. + pub fn next_f64(&mut self) -> f64 { + let a = f64::from(self.next_u32() >> 5); + let b = f64::from(self.next_u32() >> 6); + (a * 67_108_864.0 + b) / 9_007_199_254_740_992.0 + } +} + +impl Default for Rng { + fn default() -> Self { + Rng::seeded(DEFAULT_SEED) + } } /// Everything that changes while a movie plays. @@ -130,8 +178,18 @@ pub struct PlayerState { pub clips: BTreeMap, /// Properties actions have set, per instance. pub props: BTreeMap, - /// Mouse listeners scripts added, per instance, in the order added. + /// Listeners scripts added, per instance, in the order added. pub listeners: BTreeMap>, + /// Listeners on the stage (keyboard and enter-frame), in the order added. + pub stage: Vec, + /// Each timeline instance's variables (ADR 0052), by name. + pub vars: BTreeMap>, + /// The random generator. + pub rng: Rng, + /// The last pointer position seen (`mouseX`/`mouseY` keep it when the pointer leaves). + pub mouse: Vec2, + /// Listeners added so far (each one's `seq`). + pub seq: u64, /// The pointer in stage space (`None` when it is outside the movie), and whether it is down. pub pointer: Option, pub down: bool, @@ -141,9 +199,22 @@ pub struct PlayerState { pub pressed: Option, /// Steps taken since the start. pub tick: u64, + /// Each text field a script or the viewer has touched (ADR 0066), by instance path. + pub fields: BTreeMap, + /// The field that has the keyboard (an input field, or a selectable dynamic one). + pub focus: Option, + /// Shift is held (key code 16 down): caret moves extend the selection. + pub shift: bool, + /// The pointer went down in the focused field and is selecting as it drags. + pub selecting: bool, } impl PlayerState { + /// A state before the first frame, with the random generator seeded. + pub fn seeded(seed: u64) -> PlayerState { + PlayerState { rng: Rng::seeded(seed), ..PlayerState::default() } + } + /// The frame a movie clip instance shows (`len` frames long). pub fn clip_frame(&self, path: &[ElementId], len: u32) -> u32 { self.clips.get(path).map_or(0, |c| c.frame).min(len.max(1) - 1) @@ -152,21 +223,63 @@ impl PlayerState { /// The frame a button shows: Up (0), Over (1) under the pointer, Down (2) while pressed on /// it; a button whose timeline is shorter shows its last frame. pub fn button_frame(&self, path: &[ElementId], len: u32) -> u32 { - let over = self.hover.as_deref() == Some(path); - let f = match (over, self.down && self.pressed.as_deref() == Some(path)) { - (true, true) => 2, - (true, false) => 1, - (false, _) => 0, + let f = match self.button_state(path) { + ButtonState::Down => 2, + ButtonState::Over => 1, + ButtonState::Up | ButtonState::OutDown => 0, }; f.min(len.max(1) - 1) } + /// Where the pointer leaves a button: [`ButtonState`]. + pub fn button_state(&self, path: &[ElementId]) -> ButtonState { + ButtonState::of(self.hover.as_deref(), self.pressed.as_deref(), self.down, path) + } + /// A timeline's playhead: the main timeline's for the empty path. pub fn playhead(&self, path: &[ElementId]) -> Option { if path.is_empty() { Some(self.root) } else { self.clips.get(path).copied() } } } +/// Where the pointer is for one button, as the SWF file format names a button's states: away +/// (Up), over it (Over), pressed on it (Down), or pressed on it and dragged off (shown Up). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ButtonState { + Up, + Over, + Down, + OutDown, +} + +impl ButtonState { + /// The state of the button at `path` with the pointer over `hover`, pressed on `pressed`, + /// and down or not. + pub fn of(hover: Option<&[ElementId]>, pressed: Option<&[ElementId]>, down: bool, path: &[ElementId]) -> ButtonState { + match (hover == Some(path), down && pressed == Some(path)) { + (true, true) => ButtonState::Down, + (true, false) => ButtonState::Over, + (false, true) => ButtonState::OutDown, + (false, false) => ButtonState::Up, + } + } +} + +/// The frame of a button whose sound plays when the button goes from state `from` to `to` +/// (ADR 0057), as the SWF format's button sounds are kept: the Over frame's going over it, the +/// Up frame's leaving it, the Down frame's pressing it, and the Hit frame's letting go over it. +/// Dragging off a pressed button and back plays nothing. +pub fn button_sound_frame(from: ButtonState, to: ButtonState) -> Option { + use ButtonState::*; + match (from, to) { + (Up, Over) => Some(1), + (Over, Up) => Some(0), + (Over, Down) => Some(2), + (Down, Over) => Some(3), + _ => None, + } +} + /// A pointer event, in stage coordinates. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Event { @@ -175,6 +288,13 @@ pub enum Event { Up(Vec2), /// The pointer left the movie. Leave, + /// A key went down (or repeats) and came up, by its ActionScript key code. + KeyDown(u32), + KeyUp(u32), + /// A character typed (or pasted) into the focused input field (ADR 0066). + Char(char), + /// Select All in the focused field. + SelectAll, } /// The state after a step, what the movie wrote to the Output panel (traces, and why an @@ -196,6 +316,8 @@ pub enum NodeKind { Graphic, MovieClip, Button, + /// A dynamic or input text field (ADR 0066). + Text, } /// One symbol instance on the stage (or the main timeline), as the player sees it at a state. @@ -215,11 +337,25 @@ pub struct Node { pub frames: u32, /// Local → stage. pub xf: Affine, + /// The instance's own transform and alpha in its parent, as the timeline gives them (before + /// properties scripts set). + pub local: Affine, + pub alpha: f32, /// Pointer events can reach it (visible, not mask artwork). pub hittable: bool, pub events: Vec, /// The volume its sounds get: the layers holding it, from the main timeline down. pub gain: f32, + /// A text field's block (its style, box and authored text). + pub text: Option>, +} + +impl Node { + /// A text field's block and field settings. + pub fn field(&self) -> Option<(&TextBlock, &TextField)> { + let t = self.text.as_deref()?; + Some((t, t.field.as_ref()?)) + } } /// Runs plug-in frame scripts for the player (the engine implements it over the plug-in host). @@ -228,6 +364,13 @@ pub trait ScriptHost { fn begin_step(&mut self) {} /// Runs `script` for the timeline described by `cx`; returns the actions it emitted. fn run(&mut self, script: &PluginScript, cx: &ScriptContext<'_>) -> ScriptRun; + /// Lays out `shown` (a field's text as it is drawn) in `block`'s style and box (ADR 0066): + /// the fonts live above this crate. `None`: it can't, and the field keeps its authored + /// outline until its text changes (then it draws only its box). + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + let _ = (block, shown); + None + } } /// What a frame script sees. @@ -261,8 +404,13 @@ impl ScriptHost for NoScripts { /// The movie at its first frame, with the first frame's actions run. pub fn start(doc: &Document, host: &mut dyn ScriptHost) -> Step { + start_seeded(doc, DEFAULT_SEED, host) +} + +/// [`start`], with `Math.random()` seeded by `seed`. +pub fn start_seeded(doc: &Document, seed: u64, host: &mut dyn ScriptHost) -> Step { host.begin_step(); - let mut r = Run::new(doc, PlayerState::default(), host); + let mut r = Run::new(doc, PlayerState::seeded(seed), host); r.refresh(); r.pending.push_front(Vec::new()); r.settle(); @@ -278,6 +426,9 @@ pub fn step(doc: &Document, state: &PlayerState, events: &[Event], host: &mut dy r.refresh(); r.remember_graphics(); r.advance(); + // Enter-frame listeners hear the new frame before its frame scripts run (as ActionScript + // dispatches `enterFrame` before frame scripts). + r.enter_frame(); r.settle(); for e in events.iter().take(MAX_EVENTS_PER_STEP) { r.event(*e); @@ -303,7 +454,7 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d /// drawing order (parents before their contents). pub fn tree(doc: &Document, st: &PlayerState) -> Vec { let tl = doc.timeline(st.scene); - let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, hittable: true, events: Vec::new(), gain: 1.0 }]; + let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0, text: None }]; // The main timeline is seen through its camera (ADR 0027): instances are where the pointer // sees them. let camera = tl.camera_at(st.root.frame, &doc.stage); @@ -316,6 +467,86 @@ pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option { hit_in(doc, st, &tree(doc, st), p) } +/// The text field at stage point `p` the viewer can click into, topmost first (ADR 0066): what +/// a window shows a text cursor over. +pub fn field_at(doc: &Document, st: &PlayerState, p: Vec2) -> Option { + field_hit(&tree(doc, st), p).map(|(_, path)| path) +} + +/// The topmost focusable field node at `p`, with its index. +fn field_hit(nodes: &[Node], p: Vec2) -> Option<(usize, InstancePath)> { + for (i, n) in nodes.iter().enumerate().rev() { + if n.kind != NodeKind::Text || !n.hittable { + continue; + } + let Some((t, f)) = n.field() else { continue }; + if !f.focusable() { + continue; + } + let Some(q) = n.xf.inverse().map(|m| m.apply(p)) else { continue }; + if q.x >= 0.0 && q.y >= 0.0 && q.x <= t.box_width && q.y <= t.box_height { + return Some((i, n.path.clone())); + } + } + None +} + +/// The frame of a button's timeline, `len` frames long, that answers the pointer: the Hit +/// frame (the fourth) when it has one, otherwise the Up frame. +pub fn hit_frame(len: u32) -> u32 { + if len > 3 { 3 } else { 0 } +} + +/// The area of a button with timeline `tl` that answers the pointer, placed by `xf`: its +/// [`hit_frame`]'s artwork without guides and mask artwork (masks don't cut hit areas, and +/// shapes count however faint they are drawn). The hit test and Test Movie's hit-area overlay +/// both use it. +pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList { + let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None); + dl.items.retain(|i| !i.guide && i.masks.is_none()); + for i in &mut dl.items { + i.clip = None; + } + for g in &mut dl.groups { + g.clip = None; + } + dl +} + +/// `dl` drawn as one translucent area: every item filled and stroked in `tint` at full +/// strength, composited together and laid over what is below at `alpha`, so overlapping shapes +/// don't darken each other. +pub fn tinted(dl: DisplayList, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }; + out.groups.push(Group { parent: None, alpha, blend: BlendMode::default(), filters: Arc::from(Vec::new()), clip: None }); + out.append(dl); + for g in out.groups.iter_mut().skip(1) { + g.alpha = 1.0; + g.blend = BlendMode::default(); + g.filters = Arc::from(Vec::new()); + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in &mut out.items { + it.color = ColorTransform::tint(tint, 1.0); + it.outline = None; + it.group = Some(it.group.unwrap_or(0)); + } + out +} + +/// Every button's hit area at `st`, each a translucent area in `tint` (Test Movie's Show Hit +/// Areas): where the pointer finds the buttons, drawn over the movie. +pub fn hit_overlay(doc: &Document, st: &PlayerState, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + for n in tree(doc, st).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) { + if let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) { + out.append(tinted(hit_area(doc, &sym.timeline, n.xf), tint, alpha)); + } + } + out +} + /// Whether timeline layer `index` takes part in playback: shown, not a folder or guide, not in /// a hidden folder (what is drawn is what plays). fn plays(tl: &Timeline, index: usize) -> bool { @@ -338,10 +569,25 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi let path_walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame)); let Some((kf_start, els)) = evaluate_guided(layer, frame, path_walk.as_ref()) else { continue }; let layer_xf = camera.map_or(xf, |c| c.view(&doc.stage, layer.depth)); + // Instances inside a group belong to the group's timeline (ADR 0073). + let els = crate::expand_groups(&els).into_owned(); for el in els.iter() { if out.len() >= MAX_NODES { return; } + // Dynamic and input text fields are instances scripts can name (static text isn't). + if let ElementKind::Text(t) = &el.kind + && t.field.is_some() + { + let mut path = base.clone(); + path.push(el.id); + let ov = st.props.get(&path); + let shown = ov.is_none_or(Overrides::shown); + let set = ov.map(|o| o.apply(el)); + let e: &Element = set.as_ref().unwrap_or(el); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: None, kind: NodeKind::Text, frame: 0, frames: 0, xf: layer_xf.mul(&e.transform), local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: Vec::new(), gain, text: Some(t.clone()) }); + continue; + } let ElementKind::Symbol { symbol, loop_mode, first_frame, events, .. } = &el.kind else { continue }; let Some(sym) = doc.symbol(*symbol) else { continue }; let mut path = base.clone(); @@ -358,7 +604,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi }; let idx = out.len(); let node_xf = layer_xf.mul(&e.transform); - out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, hittable: hit && shown, events: events.clone(), gain }); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: events.clone(), gain, text: None }); // Names inside a movie clip (or a button's states) are its own; a graphic's // contents belong to the timeline the graphic is on. let inner_owner = if kind == NodeKind::Graphic { owner } else { idx }; @@ -375,9 +621,7 @@ fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option 3 { 3 } else { 0 }; - evaluate_symbol(doc, &sym.timeline, f, n.xf, None) + hit_area(doc, &sym.timeline, n.xf) } else { evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() })) }; @@ -423,11 +667,16 @@ struct Run<'a, 'h> { /// The frame each graphic showed when the step began: one that shows another frame at /// its end has entered it (and starts its sounds). graphics: BTreeMap, + /// Each timeline's declarations (ADR 0052), made the first time a script there + /// needs them. + decls: BTreeMap>, + /// Script fuel left this step. + fuel: u64, } impl<'a, 'h> Run<'a, 'h> { fn new(doc: &'a Document, st: PlayerState, host: &'h mut dyn ScriptHost) -> Self { - Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new() } + Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP } } fn remember_graphics(&mut self) { @@ -437,12 +686,55 @@ impl<'a, 'h> Run<'a, 'h> { /// The sounds on keyframes of `tl` starting at `frame` (every layer but guides, as the /// soundtrack has them), at volume `gain` times their layer's. fn sounds_at(&mut self, tl: &Timeline, frame: u32, gain: f32) { + self.sounds_on(tl, frame, gain, false); + } + + /// [`Run::sounds_at`]; on a button's frame (`button`) a stream sound plays as an event, + /// since a button's frame has no span to stream over (ADR 0057). + fn sounds_on(&mut self, tl: &Timeline, frame: u32, gain: f32, button: bool) { for layer in tl.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) { let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframes.get(i)) else { continue }; if let Some(fs) = &k.sound && self.sounds.len() < MAX_SOUNDS_PER_STEP { - self.sounds.push(Started { sound: fs.clone(), gain: gain * layer.sound_gain(), span: k.duration }); + let mut sound = fs.clone(); + if button && sound.sync == SoundSync::Stream { + sound.sync = SoundSync::Event; + } + self.sounds.push(Started { sound, gain: gain * layer.sound_gain(), span: k.duration }); + } + } + } + + /// Where the pointer is, for [`Run::button_sounds`]: what it is over, what it went down + /// on, and whether it is down. + fn pointer_now(&self) -> (Option, Option, bool) { + (self.st.hover.clone(), self.st.pressed.clone(), self.st.down) + } + + /// Starts the sounds of the buttons whose state changed since `before` ([`pointer_now`] + /// then): the frame [`button_sound_frame`] gives for each change. + /// + /// [`pointer_now`]: Run::pointer_now + fn button_sounds(&mut self, before: (Option, Option, bool)) { + if before == self.pointer_now() { + return; + } + self.refresh(); + let (h, p, d) = &before; + let mut paths: Vec = Vec::new(); + for path in [h, p, &self.st.hover, &self.st.pressed].into_iter().flatten() { + if !paths.contains(path) { + paths.push(path.clone()); + } + } + for path in paths { + let from = ButtonState::of(h.as_deref(), p.as_deref(), *d, &path); + let Some(frame) = button_sound_frame(from, self.st.button_state(&path)) else { continue }; + let Some(n) = self.index_of(&path).and_then(|i| self.nodes.get(i)).filter(|n| n.kind == NodeKind::Button) else { continue }; + let (gain, symbol) = (n.gain, n.symbol); + if let Some(sym) = symbol.and_then(|s| self.doc.symbol(s)) { + self.sounds_on(&sym.timeline, frame, gain, true); } } } @@ -492,6 +784,14 @@ impl<'a, 'h> Run<'a, 'h> { list.retain(|l| all.contains(&l.owner)); all.contains(p) && !list.is_empty() }); + self.st.stage.retain(|l| all.contains(&l.owner)); + // A timeline's variables go with its instance, and a field's text with the field. + self.st.vars.retain(|p, _| all.contains(p)); + self.st.fields.retain(|p, _| all.contains(p)); + if self.st.focus.as_ref().is_some_and(|p| !all.contains(p)) { + self.st.focus = None; + self.st.selecting = false; + } for slot in [&mut self.st.hover, &mut self.st.pressed] { if slot.as_ref().is_some_and(|p| !all.contains(p)) { *slot = None; @@ -568,7 +868,7 @@ impl<'a, 'h> Run<'a, 'h> { match n.kind { NodeKind::Root => Some(self.doc.timeline(self.st.scene)), NodeKind::MovieClip => n.symbol.and_then(|s| self.doc.symbol(s)).map(|s| &s.timeline), - NodeKind::Graphic | NodeKind::Button => None, + NodeKind::Graphic | NodeKind::Button | NodeKind::Text => None, } } @@ -600,7 +900,7 @@ impl<'a, 'h> Run<'a, 'h> { // than a line every time the playhead passes. FrameScript::Source(src) => { if let Ok(c) = src.compiled() { - self.run_ops(path, &c.ops); + self.run_script(path, frame, c); } } } @@ -630,43 +930,260 @@ impl<'a, 'h> Run<'a, 'h> { } } - /// 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() { + /// The declarations of the timeline node `i` is (the main timeline's span every scene). + fn decls_of(&mut self, i: usize) -> Arc { + let key = match self.nodes.get(i) { + Some(Node { kind: NodeKind::MovieClip, symbol: Some(s), .. }) => TimelineRef::Symbol(*s), + _ => TimelineRef::Root, + }; + let doc = self.doc; + self.decls.entry(key).or_insert_with(|| Arc::new(decls(doc, key))).clone() + } + + /// Runs a compiled frame script on timeline `owner` (ADR 0052): when every name + /// it takes from other frames is there, its statements run with the fuel the step has left. + fn run_script(&mut self, owner: &[ElementId], frame: u32, c: &'a Compiled) { + let Some(i) = self.index_of(owner) else { return }; + let d = self.decls_of(i); + // A script whose names don't link doesn't run (Test Movie lists why at the start). + if !d.problems(c).is_empty() { + return; + } + let where_ = format!("Script on frame {} of {}", u64::from(frame) + 1, self.timeline_name(i)); + self.run_code(owner, d, None, &where_, |w, fuel| run::run_script(w, &c.body, &c.inner, fuel)); + } + + /// Runs code on timeline `owner` with this step's fuel; writes why it stopped early. + fn run_code(&mut self, owner: &[ElementId], decls: Arc, ev: Option, where_: &str, go: impl FnOnce(&mut dyn World, u64) -> (u64, Result<(), Stop>)) { + if self.halted { + return; + } + if self.fuel == 0 { + self.halt(&format!("scripts ran more than {MAX_FUEL_PER_STEP} steps")); + return; + } + let fuel = self.fuel.min(run::FUEL_PER_RUN); + let mut w = Script { r: self, owner: owner.to_vec(), decls, ev }; + let (used, r) = go(&mut w, fuel); + self.fuel = self.fuel.saturating_sub(used); + match r { + Ok(()) | Err(Stop::Halt) => {} + Err(e) => self.out(format!("{where_} stopped: {}", e.describe())), + } + } + + /// How Output names a timeline: the main timeline, or the instance-name path of a clip. + fn timeline_name(&self, i: usize) -> String { + if i == 0 { + return "the main timeline".into(); + } + let mut names = Vec::new(); + let mut cur = i; + for _ in 0..=MAX_SYMBOL_DEPTH { + let Some(n) = self.nodes.get(cur) else { break }; + if n.kind == NodeKind::Root { + break; + } + names.push(if n.name.is_empty() { "?" } else { n.name.as_str() }); + cur = n.owner; + } + names.reverse(); + names.join(".") + } + + /// Calls listener `l` with the event. + fn call_listener(&mut self, l: &Listening, ev: EventInfo) { + self.refresh(); + let Some(i) = self.index_of(&l.owner) else { return }; + let d = self.decls_of(i); + let f = l.func.clone(); + let where_ = format!("Listener {}", l.function); + self.run_code(&l.owner, d, Some(ev), &where_, |w, fuel| run::run_listener(w, &f, fuel)); + } + + /// Every enter-frame listener, in the order they were added. + fn enter_frame(&mut self) { + self.refresh(); + let mut all: Vec<(Option, Listening)> = self.st.listeners.iter().flat_map(|(p, list)| list.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (Some(p.clone()), l.clone()))).collect(); + all.extend(self.st.stage.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (None, l.clone()))); + all.sort_by_key(|(_, l)| l.seq); + for (at, l) in all { + if self.halted { return; } - match op { - ScriptOp::Action(a) => self.exec(owner, a, true), - ScriptOp::Listen(l) => self.listen(owner, l), + self.call_listener(&l, EventInfo { key: None, target: at.clone(), current: at }); + self.settle(); + } + } + + /// A key event: the stage's listeners for it, in the order added. + fn key(&mut self, event: ListenEvent, code: u32) { + let list: Vec = self.st.stage.iter().filter(|l| l.event == event).cloned().collect(); + for l in list { + if self.halted { + return; + } + self.call_listener(&l, EventInfo { key: Some(code), target: None, current: None }); + self.settle(); + } + } + + /// The node an instance name stands for, from timeline node `from` (`Ok(None)`: the stage). + fn place(&self, from: usize, ev: Option<&EventInfo>, at: &Place) -> Result, String> { + let base = match at.base { + Base::This => from, + Base::Stage => { + return if at.path.is_this() { Ok(None) } else { Err("instances on the stage are named from the main timeline (root)".into()) }; + } + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if at.base == Base::Target { &ev.target } else { &ev.current }; + match p { + None if at.path.is_this() => return Ok(None), + None => return Err("the event's target is the stage".into()), + Some(p) => self.index_of(p).ok_or("the event's target has left the stage")?, + } + } + }; + self.resolve(base, &at.path).map(Some) + } + + /// The path of the node `base` starts from (for actions on the event's target). + fn base_path(&self, owner: &[ElementId], ev: Option<&EventInfo>, base: Base) -> Result { + match base { + Base::This => Ok(owner.to_vec()), + Base::Stage => Err("the stage has no playhead".into()), + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if base == Base::Target { &ev.target } else { &ev.current }; + p.clone().ok_or_else(|| "the event's target is the stage".into()) } } } - /// `addEventListener`: the instance the listener's target names gets it (once per - /// function and event). - fn listen(&mut self, owner: &[ElementId], l: &Listener) { + /// A property of node `i` (`None`: the stage). + fn property(&self, i: Option, p: Prop) -> Result { + let num = |v: f64| Ok(Value::Num(v)); + let Some(i) = i else { + return match p { + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + _ => Err(format!("the stage's `{}` isn't supported here", p.name())), + }; + }; + let Some(n) = self.nodes.get(i) else { return Err("the instance is gone".into()) }; + if n.kind == NodeKind::Root { + return match p { + Prop::X | Prop::Y | Prop::Rotation => num(0.0), + Prop::Alpha | Prop::ScaleX | Prop::ScaleY => num(1.0), + Prop::Visible => Ok(Value::Bool(true)), + Prop::CurrentFrame => num(f64::from(self.st.root.frame) + 1.0), + Prop::TotalFrames => num(self.doc.scenes.iter().map(|s| f64::from(s.timeline.frame_count())).sum()), + Prop::CurrentLabel => Ok(current_label(self.doc.timeline(self.st.scene), self.st.root.frame)), + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + Prop::Name => Ok(Value::str("root1")), + Prop::Text | Prop::Length => Err("the main timeline isn't a text field".into()), + }; + } + if matches!(p, Prop::Text | Prop::Length) { + let Some((t, _)) = n.field() else { return Err(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))) }; + let v = self.st.fields.get(&n.path).map_or(t.text.as_str(), |f| f.value(t)); + return Ok(if p == Prop::Text { Value::str(v) } else { Value::Num(crate::actions::as3::ir::text_len(v) as f64) }); + } + let ov = self.st.props.get(&n.path).copied().unwrap_or_default(); + let d = decompose64(&n.local); + let deg = 180.0 / std::f64::consts::PI; + let pick = |o: Option, v: f64| num(o.map_or(fround_short(v), short)); + match p { + Prop::X => pick(ov.x, d[0]), + Prop::Y => pick(ov.y, d[1]), + Prop::ScaleX => pick(ov.scale_x, d[2]), + Prop::ScaleY => pick(ov.scale_y, d[3]), + Prop::Rotation => pick(ov.rotation, d[4] * deg), + Prop::Alpha => num(short(ov.alpha.unwrap_or(n.alpha))), + Prop::Visible => Ok(Value::Bool(ov.visible != Some(false))), + Prop::Name => Ok(Value::str(&n.name)), + Prop::MouseX | Prop::MouseY => { + let m = n.xf.m.map(f64::from); + let det = m[0] * m[3] - m[1] * m[2]; + if det == 0.0 || !det.is_finite() { + return num(0.0); + } + let (x, y) = (f64::from(self.st.mouse.x) - m[4], f64::from(self.st.mouse.y) - m[5]); + let v = if p == Prop::MouseX { (m[3] * x - m[2] * y) / det } else { (m[0] * y - m[1] * x) / det }; + num(fround_short(v)) + } + Prop::Text | Prop::Length => Err("not a text field".into()), + Prop::CurrentFrame | Prop::TotalFrames | Prop::CurrentLabel => { + if n.kind != NodeKind::MovieClip { + return Err(format!("“{}” is {}; only movie clips and the main timeline have frames", n.name, kind_name(n.kind))); + } + match p { + Prop::CurrentFrame => num(f64::from(n.frame) + 1.0), + Prop::TotalFrames => num(f64::from(n.frames)), + _ => Ok(n.symbol.and_then(|s| self.doc.symbol(s)).map_or(Value::Null, |s| current_label(&s.timeline, n.frame))), + } + } + } + } + + /// `addEventListener` / `removeEventListener` from timeline `owner`. + fn listen(&mut self, owner: &[ElementId], ev: Option<&EventInfo>, at: &Place, event: ListenEvent, f: &Arc, add: bool) { 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) { + let what = format!("{} for {} ({at})", if add { "Listen" } else { "Stop listening" }, event.key()); + let i = match self.place(from, ev, at) { Ok(i) => i, Err(e) => return self.out(format!("{what}: {e}")), }; + let seq = self.st.seq; + let item = Listening { event, owner: owner.to_vec(), function: f.name.clone(), func: f.clone(), seq }; + let same = |x: &Listening| x.event == event && x.owner == owner && x.function == f.name; + let Some(i) = i else { + // The stage: keyboard and enter-frame listeners. + if add { + if self.st.stage.iter().any(same) { + return; + } + if self.st.stage.len() >= MAX_STAGE_LISTENERS { + return self.out(format!("{what}: the stage already has {MAX_STAGE_LISTENERS} listeners")); + } + self.st.seq += 1; + self.st.stage.push(item); + } else { + self.st.stage.retain(|x| !same(x)); + } + return; + }; 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) }; + let ok = match event { + ListenEvent::EnterFrame => node.kind != NodeKind::Graphic, + _ => matches!(node.kind, NodeKind::Button | NodeKind::MovieClip), + }; + if !ok { + let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is {}; only buttons and movie clips get pointer events", node.name, kind_name(node.kind)) }; return self.out(format!("{what}: {why}")); } let (path, name) = (node.path.clone(), node.name.clone()); + if !add { + if let Some(list) = self.st.listeners.get_mut(&path) { + list.retain(|x| !same(x)); + if list.is_empty() { + self.st.listeners.remove(&path); + } + } + return; + } 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) { + if list.iter().any(same) { 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() }); + list.push(item); + self.st.seq += 1; } /// The node `target` names, seen from timeline node `from`. @@ -719,8 +1236,7 @@ impl<'a, 'h> Run<'a, 'h> { }; let Some(node) = self.nodes.get(i) else { return }; if !matches!(node.kind, NodeKind::Root | NodeKind::MovieClip) { - let what = if node.kind == NodeKind::Button { "a button" } else { "a graphic" }; - return self.out(format!("{}: “{}” is {what}; only movie clips and the main timeline have a playhead", a.describe(), node.name)); + return self.out(format!("{}: “{}” is {}; only movie clips and the main timeline have a playhead", a.describe(), node.name, kind_name(node.kind))); } let (path, frame, frames) = (node.path.clone(), node.frame, node.frames.max(1)); match a { @@ -813,21 +1329,54 @@ impl<'a, 'h> Run<'a, 'h> { fn event(&mut self, e: Event) { self.refresh(); match e { - Event::Move(p) => self.pointer(Some(p)), + Event::Move(p) => { + self.pointer(Some(p)); + // Dragging in the focused field selects. + if self.st.selecting && self.st.down { + self.point_field(p, true); + } + } Event::Down(p) => { self.pointer(Some(p)); + // A field the viewer can use takes the press (unless a button is above it): it + // gets the keyboard and the caret goes where it was clicked. Anywhere else the + // focused field loses the keyboard. + let hover_at = self.st.hover.as_ref().and_then(|h| self.index_of(h)); + match self.field_at(p).filter(|(i, _)| hover_at.is_none_or(|h| *i > h)) { + Some((_, path)) => { + self.st.focus = Some(path); + self.st.down = true; + self.st.selecting = true; + self.point_field(p, false); + return; + } + None => { + self.st.focus = None; + self.st.selecting = false; + } + } + let before = self.pointer_now(); self.st.down = true; self.st.pressed = self.st.hover.clone(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Press); } } Event::Up(p) => { + if self.st.selecting { + self.st.selecting = false; + self.st.down = false; + self.pointer(Some(p)); + return; + } self.pointer(Some(p)); + let before = self.pointer_now(); self.st.down = false; let pressed = self.st.pressed.take(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Release); if pressed.as_ref() == Some(&h) { @@ -836,17 +1385,130 @@ impl<'a, 'h> Run<'a, 'h> { } } Event::Leave => self.pointer(None), + // Keys edit the focused field, then go to the stage's listeners as well (as they + // reach the stage from a focused field in ActionScript). + Event::KeyDown(k) => { + if k == SHIFT { + self.st.shift = true; + } + self.field_key(k); + self.key(ListenEvent::KeyDown, k); + } + Event::KeyUp(k) => { + if k == SHIFT { + self.st.shift = false; + } + self.key(ListenEvent::KeyUp, k); + } + Event::Char(c) => { + let mut b = [0u8; 4]; + let s: &str = c.encode_utf8(&mut b); + self.edit_field(|ed, _| ed.insert(s)); + } + Event::SelectAll => self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)), } } + /// The topmost field at stage point `p` the viewer can use, with its node's index. + fn field_at(&self, p: Vec2) -> Option<(usize, InstancePath)> { + field_hit(&self.nodes, p) + } + + /// Field `path`'s block and its place on the stage. + fn field_node(&self, path: &[ElementId]) -> Option<(Arc, Affine)> { + let n = self.index_of(path).and_then(|i| self.nodes.get(i))?; + let t = n.text.clone().filter(|t| t.field.is_some())?; + Some((t, n.xf)) + } + + /// Lays field `path`'s text out as it is now (with the host's fonts) and keeps the caret + /// in the text and in view. + fn relayout(&mut self, path: &[ElementId]) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + let st = self.st.fields.entry(path.to_vec()).or_default(); + let shown = f.shown(st.value(&t)); + st.look = self.host.lay_out_field(&t, &shown).map(Arc::new); + let len = chars(st.value(&t)); + st.caret = st.caret.min(len); + st.anchor = st.anchor.min(len); + scroll_to_caret(&t, f, st); + } + + /// A script sets field `path`'s text. + fn set_field_text(&mut self, path: &[ElementId], text: &str) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + self.st.fields.entry(path.to_vec()).or_default().text = Some(fit(f, text)); + self.relayout(path); + } + + /// Runs an edit on the focused field (laying it out first if it never was). + fn edit_field(&mut self, go: impl FnOnce(&mut Editor<'_>, Option<&FieldLook>) -> Changed) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((t, _)) = self.field_node(&path) else { return }; + let Some(f) = t.field.clone() else { return }; + if self.st.fields.get(&path).is_none_or(|s| s.look.is_none()) { + self.relayout(&path); + } + let st = self.st.fields.entry(path.clone()).or_default(); + let look = st.look.clone(); + let changed = go(&mut Editor { block: &t, field: &f, st }, look.as_deref()); + if changed.text { + self.relayout(&path); + } else if changed.caret { + scroll_to_caret(&t, &f, self.st.fields.entry(path).or_default()); + } + } + + /// The pointer at stage point `p` in the focused field: places the caret (`extend`: moves + /// it, keeping the selection's other end). + fn point_field(&mut self, p: Vec2, extend: bool) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((_, xf)) = self.field_node(&path) else { return }; + let Some(q) = xf.inverse().map(|m| m.apply(p)) else { return }; + let q = Vec2::new(q.x - FIELD_GUTTER, q.y - FIELD_GUTTER); + self.edit_field(|ed, look| ed.point(q, extend, look)); + } + + /// A key down for the focused field: an edit, or Tab to the next input field. + fn field_key(&mut self, code: u32) { + if self.st.focus.is_none() { + return; + } + if code == TAB { + let inputs: Vec = self.nodes.iter().filter(|n| n.hittable && n.field().is_some_and(|(_, f)| f.kind == TextKind::Input)).map(|n| n.path.clone()).collect(); + let at = inputs.iter().position(|p| Some(p) == self.st.focus.as_ref()); + let n = inputs.len(); + if n > 0 { + let next = match at { + Some(i) if self.st.shift => (i + n - 1) % n, + Some(i) => (i + 1) % n, + None => 0, + }; + self.st.focus = inputs.get(next).cloned(); + self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)); + } + return; + } + let Some(e) = Edit::from_key(code) else { return }; + let shift = self.st.shift; + self.edit_field(|ed, look| ed.key(e, shift, look)); + } + /// Moves the pointer: what it leaves gets Out, what it reaches gets Over. fn pointer(&mut self, p: Option) { self.refresh(); self.st.pointer = p; + if let Some(p) = p { + self.st.mouse = p; + } let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p)); if now != self.st.hover { + let before = self.pointer_now(); let old = std::mem::replace(&mut self.st.hover, now.clone()); self.dirty = true; + self.button_sounds(before); if let Some(o) = old { self.fire(&o, ButtonEvent::Out); } @@ -863,15 +1525,16 @@ impl<'a, 'h> Run<'a, 'h> { let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return }; 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>)> = 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(); + let le = ListenEvent::from_mouse(event); + let listeners: Vec = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == le).cloned().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); + for l in listeners { + self.call_listener(&l, EventInfo { key: None, target: Some(path.to_vec()), current: Some(path.to_vec()) }); } self.settle(); } @@ -899,6 +1562,223 @@ impl<'a, 'h> Run<'a, 'h> { } } +/// The key codes of Shift and Tab. +const SHIFT: u32 = 16; +const TAB: u32 = 9; + +/// How messages name a kind of instance. +fn kind_name(k: NodeKind) -> &'static str { + match k { + NodeKind::Root => "the main timeline", + NodeKind::Graphic => "a graphic", + NodeKind::MovieClip => "a movie clip", + NodeKind::Button => "a button", + NodeKind::Text => "a text field", + } +} + +/// The event a listener is handling: the key code of a keyboard event, and its target and +/// current target (`None`: the stage). +#[derive(Clone, Debug, PartialEq)] +struct EventInfo { + key: Option, + target: Option, + current: Option, +} + +/// A timeline whose scripts share declarations: the main timeline (every scene) or a movie +/// clip symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum TimelineRef { + Root, + Symbol(SymbolId), +} + +/// The compiled frame scripts of a timeline that plays them, in frame order (top layer first +/// within a frame). +pub fn timeline_scripts(tl: &Timeline) -> Vec<(u32, usize, &Compiled)> { + let mut out = Vec::new(); + for (index, layer) in tl.layers.iter().enumerate() { + if !plays(tl, index) { + continue; + } + for k in &layer.keyframes { + if let Some(FrameScript::Source(src)) = &k.script + && let Ok(c) = src.compiled() + { + out.push((k.start, index, c)); + } + } + } + out.sort_by_key(|(f, l, _)| (*f, *l)); + out +} + +/// A timeline's declarations: every function and variable its frame scripts declare (the main +/// timeline's from every scene, in scene order). +pub fn decls(doc: &Document, which: TimelineRef) -> Decls { + match which { + TimelineRef::Root => Decls::build(doc.scenes.iter().flat_map(|s| timeline_scripts(&s.timeline)).map(|(_, _, c)| c)), + TimelineRef::Symbol(id) => match doc.symbol(id) { + Some(s) if s.kind == SymbolKind::MovieClip => Decls::build(timeline_scripts(&s.timeline).into_iter().map(|(_, _, c)| c)), + _ => Decls::default(), + }, + } +} + +/// Why a compiled script on timeline `which` doesn't run there: names it takes from other +/// frames that the timeline doesn't declare, and declarations that clash. +pub fn link_problems(doc: &Document, which: TimelineRef, c: &Compiled) -> Vec { + decls(doc, which).problems(c) +} + +/// The label at or before `frame` (ActionScript's `currentLabel`), or `null`. +fn current_label(tl: &Timeline, frame: u32) -> Value { + let mut firsts: BTreeMap<&str, u32> = BTreeMap::new(); + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()).filter(|k| !k.label.is_empty()) { + let e = firsts.entry(k.label.as_str()).or_insert(k.start); + *e = (*e).min(k.start); + } + let mut best: Option<(&str, u32)> = None; + for (l, f) in firsts { + if f <= frame && best.is_none_or(|(_, b)| f > b) { + best = Some((l, f)); + } + } + best.map_or(Value::Null, |(l, _)| Value::str(l)) +} + +/// An `f32` as the shortest decimal that reads back as it (what the HTML player sees after +/// the export writes it as JSON): reads give `0.1`, not `0.10000000149011612`. +fn short(v: f32) -> f64 { + if !v.is_finite() { + return f64::from(v); + } + format!("{v}").parse().unwrap_or(f64::from(v)) +} + +/// A computed value at `f32` precision, written shortest. +fn fround_short(v: f64) -> f64 { + short(v as f32) +} + +/// `[tx, ty, sx, sy, rotation]` of a transform in `f64` (the same steps as `Affine::decompose` +/// and the HTML player's `decompose`), from its components written shortest. +fn decompose64(m: &Affine) -> [f64; 5] { + let [a, b, c, d, e, f] = m.m.map(short); + let sx = (a * a + b * b).sqrt(); + let r = b.atan2(a); + let det = a * d - b * c; + let sy = if sx > 1e-12 { det / sx } else { (c * c + d * d).sqrt() }; + [e, f, sx, sy, r] +} + +/// A running script's view of the movie (ADR 0052). +struct Script<'r, 'a, 'h> { + r: &'r mut Run<'a, 'h>, + /// The timeline the script belongs to. + owner: InstancePath, + decls: Arc, + ev: Option, +} + +impl Script<'_, '_, '_> { + fn from(&mut self) -> Result { + self.r.refresh(); + self.r.index_of(&self.owner).ok_or_else(|| "the script's timeline has left the stage".into()) + } +} + +impl World for Script<'_, '_, '_> { + fn act(&mut self, base: Base, action: &Action) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let path = self.r.base_path(&self.owner, self.ev.as_ref(), base).map_err(Some)?; + self.r.exec(&path, action, true); + if self.r.halted { Err(None) } else { Ok(()) } + } + + fn get(&mut self, at: &Place, p: Prop) -> Result { + let from = self.from()?; + let i = self.r.place(from, self.ev.as_ref(), at)?; + self.r.property(i, p) + } + + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option> { + if at.base == Base::Stage { + return Err(Some("the stage's properties can't be set here".into())); + } + // In range (as the property keeps it), and never -0, so messages read the same here + // and in the HTML player. + let (lo, hi) = p.range(); + let v = v.clamp(lo, hi) + 0.0; + self.act(at.base, &Action::SetProperty { target: at.path.clone(), property: p, value: v }) + } + + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let from = self.from().map_err(Some)?; + let i = self.r.place(from, self.ev.as_ref(), at).map_err(Some)?; + let Some(n) = i.and_then(|i| self.r.nodes.get(i)) else { return Err(Some("the stage isn't a text field".into())) }; + if n.field().is_none() { + return Err(Some(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind)))); + } + let path = n.path.clone(); + self.r.set_field_text(&path, &text); + Ok(()) + } + + fn trace(&mut self, line: String) { + if self.r.budget() { + self.r.out(line); + } + } + + fn read(&mut self, name: &str) -> Result { + if let Some(v) = self.r.st.vars.get(&self.owner).and_then(|m| m.get(name)) { + return Ok(v.clone()); + } + self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't a variable of this timeline")) + } + + fn write(&mut self, name: &str, v: Value) -> Result<(), String> { + let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't a variable of this timeline"))?; + self.r.st.vars.entry(self.owner.clone()).or_default().insert(name.to_string(), t.coerce(v)); + Ok(()) + } + + fn function(&mut self, name: &str) -> Option> { + self.decls.functions.get(name).cloned() + } + + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let owner = self.owner.clone(); + self.r.listen(&owner, self.ev.as_ref(), at, ev, f, add); + Ok(()) + } + + fn random(&mut self) -> f64 { + self.r.st.rng.next_f64() + } + + fn same(&mut self, a: &Place, b: &Place) -> Result { + let from = self.from()?; + let x = self.r.place(from, self.ev.as_ref(), a)?; + let y = self.r.place(from, self.ev.as_ref(), b)?; + Ok(x == y) + } + + fn key_code(&mut self) -> Result { + self.ev.as_ref().and_then(|e| e.key).map(f64::from).ok_or_else(|| "this isn't a keyboard event".into()) + } +} + #[cfg(test)] #[path = "player_tests.rs"] mod tests; diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 6720e447..2114efba 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, timeline: Timeline { layers } }) + Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers } }) } fn doc(root: Vec>, library: Vec>) -> Document { @@ -342,6 +342,97 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]); } +// ----- Sounds on button frames (ADR 0057) -------------------------------------------------------- + +/// [`button_doc`] with a sound on each state frame (ids 10 Up, 11 Over, 12 Down, 13 Hit; Over's +/// a stream), on a layer at half volume, the button on a layer at half volume too. +fn sounding_button() -> Document { + use crate::SoundSync::{Event, Stream}; + let mut d = button_doc(); + let art = |id| vec![rect(id, 0.0, 0.0, 10.0, 10.0)]; + let mut sounds = (*layer(34, vec![with_sound(kf(0, 1, vec![], vec![], ""), 10, Event), with_sound(kf(1, 1, vec![], vec![], ""), 11, Stream), with_sound(kf(2, 1, vec![], vec![], ""), 12, Event), with_sound(kf(3, 1, vec![], vec![], ""), 13, Event)])).clone(); + sounds.volume = 0.5; + let states = layer(31, vec![kf(0, 1, art(32), vec![], ""), kf(1, 1, art(32), vec![], ""), kf(2, 1, art(32), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0)], vec![], "")]); + d.library = vec![symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states])]; + Arc::make_mut(&mut d.timeline_mut(0).layers[1]).volume = 0.5; + let tone: Vec = (0..800).map(|i| (i as f32 * 0.1).sin() * 0.5).collect(); + for id in 10..14 { + let data = anicraft_audio::wav::encode(8000, 1, &tone, anicraft_audio::wav::Bits::Float32); + d.sounds.push(Arc::new(crate::Sound::from_data(crate::SoundId(id), format!("s{id}.wav"), data).expect("a WAV"))); + } + d +} + +#[test] +fn a_button_plays_the_sound_of_the_state_it_enters() { + let d = sounding_button(); + let at = |x, y| Vec2::new(x, y); + let s = start(&d, &mut NoScripts); + assert!(s.sounds.is_empty(), "a button on the stage is silent until the pointer comes"); + // Over: the Over frame's sound, as an event (a button frame has no span to stream over), at + // the volumes of both layers. + let s = step(&d, &s.state, &[Event::Move(at(150.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25)]); + assert_eq!(s.sounds[0].sound.sync, crate::SoundSync::Event); + // Moving about inside it plays nothing more. + let s = step(&d, &s.state, &[Event::Move(at(160.0, 150.0))], &mut NoScripts); + assert!(s.sounds.is_empty()); + // Pressed: Down's. Released over it: Hit's (the SWF format's Down → Over sound). + let s = input(&d, &s.state, &[Event::Down(at(160.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(12, 0.25)]); + let s = input(&d, &s.state, &[Event::Up(at(160.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(13, 0.25)]); + // Left: Up's. + let s = step(&d, &s.state, &[Event::Leave], &mut NoScripts); + assert_eq!(started(&s), vec![(10, 0.25)]); + // Arriving and pressing in one event: Over's, then Down's. + let s = input(&d, &s.state, &[Event::Down(at(150.0, 150.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25), (12, 0.25)]); + // Dragged off while pressed, back on and released off: nothing (no state with a sound). + let s = input(&d, &s.state, &[Event::Move(at(400.0, 400.0)), Event::Move(at(150.0, 150.0)), Event::Move(at(400.0, 400.0)), Event::Up(at(400.0, 400.0))], &mut NoScripts); + assert!(s.sounds.is_empty(), "{:?}", started(&s)); +} + +#[test] +fn button_sounds_follow_the_frames_a_button_has_and_stay_out_of_the_soundtrack() { + // A two-frame button (Up and Over): pressing it shows Over still, and plays nothing. + let mut d = sounding_button(); + let short = Timeline { layers: d.library[0].timeline.layers.iter().map(|l| { + let mut l = (**l).clone(); + l.keyframes.truncate(2); + Arc::new(l) + }).collect() }; + Arc::make_mut(&mut d.library[0]).timeline = short; + let s = start(&d, &mut NoScripts); + // Its Up frame is its hit area (10 × 10 at 100, 100). + let s = input(&d, &s.state, &[Event::Move(Vec2::new(105.0, 105.0)), Event::Down(Vec2::new(105.0, 105.0))], &mut NoScripts); + assert_eq!(started(&s), vec![(11, 0.25)]); + // The mix and every export leave buttons out: they only sound under the pointer. + assert!(crate::sound::voices(&sounding_button(), 48_000).is_empty()); +} + +#[test] +fn the_hit_overlay_is_the_area_the_pointer_finds() { + let d = button_doc(); + let s = start(&d, &mut NoScripts); + let tint = Rgba::new(1.0, 0.0, 0.0, 1.0); + let dl = hit_overlay(&d, &s.state, tint, 0.4); + // One area: the Hit frame's 100 × 100 square at (100, 100), tinted, in one group at 40 %. + assert_eq!(dl.items.len(), 1); + assert_eq!(dl.groups.first().map(|g| g.alpha), Some(0.4)); + let i = &dl.items[0]; + assert_eq!((i.color, i.group), (ColorTransform::tint(tint, 1.0), Some(0))); + assert_eq!(i.color.apply(Rgba::new(0.1, 0.6, 0.9, 0.8)), Rgba::new(1.0, 0.0, 0.0, 0.8), "every colour becomes the tint, its alpha kept"); + for p in [Vec2::new(101.0, 101.0), Vec2::new(199.0, 150.0), Vec2::new(50.0, 50.0), Vec2::new(201.0, 150.0)] { + assert_eq!(i.path.contains(p, &i.transform, i.fill_rule), hit(&d, &s.state, p).is_some(), "{p:?}"); + } + // A hidden button has no area; a movie without buttons none at all. + assert!(hit_overlay(&doc(vec![], vec![]), &PlayerState::default(), tint, 0.4).items.is_empty()); + assert_eq!(hit_frame(4), 3); + assert_eq!(hit_frame(3), 0); + assert_eq!(hit_frame(0), 0); +} + // ----- ActionScript (ADR 0013 tier 2) ----------------------------------------------------------- /// `k` with a kept ActionScript 3.0 script in place of its actions. @@ -353,7 +444,7 @@ fn as3(k: Arc, src: &str) -> Arc { /// The state without the listeners scripts add (hand-made actions use handlers instead). fn lean(st: &PlayerState) -> PlayerState { - PlayerState { listeners: BTreeMap::new(), ..st.clone() } + PlayerState { listeners: BTreeMap::new(), seq: 0, ..st.clone() } } /// Plays both documents through the same pointer events and asserts the same movie: state and @@ -403,7 +494,7 @@ fn actionscript_and_hand_made_actions_play_the_same_movie() { #[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 d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nswitch (1) { }")])], 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); @@ -448,3 +539,275 @@ fn next_scene_in_a_movie_clip_script_stays_in_its_clip() { 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"]); } + +// ----- ActionScript small logic (ADR 0052) --------------------------------------------- + +/// A one-layer main timeline of `frames` frames with scripts on some of them, and `extra` layers. +fn scripted(frames: u32, scripts: &[(u32, &str)], extra: Vec>, library: Vec>) -> Document { + let mut keys = Vec::new(); + let mut starts: Vec = scripts.iter().map(|(f, _)| *f).collect(); + starts.push(frames); + for (i, (f, src)) in scripts.iter().enumerate() { + let end = starts.get(i + 1).copied().unwrap_or(frames); + keys.push(if src.is_empty() { kf(*f, end - f, vec![], vec![], "") } else { as3(kf(*f, end - f, vec![], vec![], ""), src) }); + } + let mut layers = vec![layer(1, keys)]; + layers.extend(extra); + doc(layers, library) +} + +fn outputs(d: &Document, steps: usize) -> Vec { + let mut s = start(d, &mut NoScripts); + let mut out = s.output.clone(); + for _ in 0..steps { + s = step(d, &s.state, &[], &mut NoScripts); + out.extend(s.output.iter().cloned()); + } + out +} + +#[test] +fn timeline_variables_and_functions_live_across_frames() { + let d = scripted(4, &[(0, "var score:int = 10;\nfunction bump(k:int):int { score += k; return score; }\ntrace(\"start \" + score + \" \" + level);"), (2, "trace(bump(5), bump(1.9), level);\nlevel = \"two\";"), (3, "trace(level);\nvar level:String = \"one\"; trace(level); stop();")], vec![], vec![]); + // `level` is declared on frame 4 but is the timeline's from the start (null until set). + assert_eq!(outputs(&d, 5), ["start 10 null", "15 16 null", "two", "one"]); + let s = run(&d, 5); + assert_eq!(s.state.vars.get(&Vec::new()).and_then(|v| v.get("score")), Some(&Value::Num(16.0))); + // A script that uses a name no frame declares doesn't run at all. + let d = scripted(3, &[(0, "trace(\"one\");"), (1, "trace(\"two\"); trace(nobody);")], vec![], vec![]); + assert_eq!(outputs(&d, 2), ["one"]); + assert_eq!(link_problems(&d, TimelineRef::Root, d.scenes[0].timeline.layers[0].keyframes[1].script.as_ref().and_then(FrameScript::source).unwrap().compiled().as_ref().unwrap())[0].message, "`nobody` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)"); +} + +#[test] +fn each_movie_clip_instance_keeps_its_own_variables() { + // A two-frame clip counts its loops; two instances count apart, and one that leaves the + // stage and comes back starts again. + 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![], ""), "var n:int; n++; trace(name + \" \" + n);")])]); + let a = layer(2, vec![kf(0, 8, vec![inst(3, 100, "a", 0.0, 0.0, vec![])], vec![], "")]); + let b = layer(3, vec![kf(0, 3, vec![inst(4, 100, "b", 50.0, 0.0, vec![])], vec![], ""), kf(3, 2, vec![], vec![], ""), kf(5, 3, vec![inst(5, 100, "b", 50.0, 0.0, vec![])], vec![], "")]); + let d = scripted(8, &[(0, "")], vec![a, b], vec![clip]); + let out = outputs(&d, 6); + assert_eq!(out, ["a 1", "b 1", "a 2", "b 2", "a 3", "b 1", "a 4"], "{out:?}"); +} + +#[test] +fn enter_frame_listeners_run_every_frame_until_removed() { + let src = "var t:int = 0;\nstop();\naddEventListener(Event.ENTER_FRAME, tick);\nfunction tick(e:Event):void {\n t++;\n trace(\"tick \" + t + \" on \" + currentFrame + \" of \" + totalFrames);\n if (t == 3) { removeEventListener(Event.ENTER_FRAME, tick); gotoAndStop(2); }\n}"; + let d = scripted(3, &[(0, src), (1, "trace(\"frame 2 runs after the listener\");")], vec![], vec![]); + assert_eq!(outputs(&d, 5), ["tick 1 on 1 of 3", "tick 2 on 1 of 3", "tick 3 on 1 of 3", "frame 2 runs after the listener"]); + assert!(run(&d, 5).state.listeners.is_empty()); +} + +#[test] +fn keys_reach_the_stage_listeners_with_their_codes() { + let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "")])]); + let src = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, down);\nstage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode); });\nfunction down(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.RIGHT) hero.x += 10;\n else if (e.keyCode == Keyboard.LEFT) hero.x -= 10;\n trace(e.keyCode, hero.x, e.target == stage);\n}"; + let d = scripted(2, &[(0, src)], vec![layer(2, vec![kf(0, 2, vec![inst(3, 100, "hero", 30.0, 40.0, vec![])], vec![], "")])], vec![clip]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.state.stage.len(), 2); + let s = step(&d, &s.state, &[Event::KeyDown(39), Event::KeyDown(39), Event::KeyUp(39)], &mut NoScripts); + assert_eq!(s.output, ["39 40 true", "39 50 true", "up 39"]); + // Between frames too. + let s = input(&d, &s.state, &[Event::KeyDown(37)], &mut NoScripts); + assert_eq!(s.output, ["37 40 true"]); + assert_eq!(s.state.props.get(&vec![ElementId(3)]).and_then(|o| o.x), Some(40.0)); +} + +#[test] +fn scripts_read_instance_and_timeline_properties() { + let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 3, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "walk")])]); + let mut hero = (*inst(3, 100, "hero", 30.0, 40.0, vec![])).clone(); + hero.transform = Affine::translate(30.25, 40.0).mul(&Affine::scale(2.0, 0.5)); + hero.color = crate::ColorEffect::Alpha(0.3); + let src = "stop();\ntrace(hero.x, hero.y, hero.scaleX, hero.scaleY, hero.rotation, hero.alpha, hero.visible, hero.name);\ntrace(hero.currentFrame, hero.totalFrames, hero.currentLabel, currentFrame, totalFrames, currentLabel, this.name);\nhero.x = 0.1; hero.alpha = hero.alpha + 0.2; hero.visible = false;\ntrace(hero.x, hero.alpha, hero.visible);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(mouseX, mouseY, hero.mouseX, stage.mouseY); });"; + let k = as3(kf(0, 2, vec![], vec![], "intro"), src); + let mut hk = Keyframe::new(0, 2); + hk.elements = vec![Arc::new(hero)]; + let d = doc(vec![layer(1, vec![k]), layer(2, vec![Arc::new(hk)])], vec![clip]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.output, ["30.25 40 2 0.5 0 0.3 true hero", "1 3 walk 1 2 intro root1", "0.1 0.5 false"]); + let s = input(&d, &s.state, &[Event::Move(Vec2::new(50.5, 60.0)), Event::Leave, Event::KeyDown(32)], &mut NoScripts); + // The pointer's last place stays after it leaves; a clip sees it in its own space. + assert_eq!(s.output, ["50.5 60 25.2 60"]); +} + +#[test] +fn random_numbers_are_seeded_and_repeat() { + let src = "trace(Math.random(), Math.floor(Math.random() * 6) + 1);"; + let d = scripted(2, &[(0, src)], vec![], vec![]); + let a = start_seeded(&d, 7, &mut NoScripts).output; + let b = start_seeded(&d, 7, &mut NoScripts).output; + let c = start_seeded(&d, 8, &mut NoScripts).output; + assert_eq!(a, b); + assert_ne!(a, c); + // The generator itself: in [0, 1), and spread out. + let mut r = Rng::seeded(DEFAULT_SEED); + let v: Vec = (0..10_000).map(|_| r.next_f64()).collect(); + assert!(v.iter().all(|x| (0.0..1.0).contains(x))); + let mean = v.iter().sum::() / v.len() as f64; + assert!((mean - 0.5).abs() < 0.02, "{mean}"); + assert_eq!(start(&d, &mut NoScripts).output, start_seeded(&d, DEFAULT_SEED, &mut NoScripts).output); +} + +#[test] +fn an_endless_loop_stops_its_script_and_the_movie_plays_on() { + let d = scripted(3, &[(0, "trace(\"a\");\nwhile (true) { }\ntrace(\"never\");"), (1, "trace(\"frame 2\");")], vec![], vec![]); + let s = start(&d, &mut NoScripts); + assert_eq!(s.output, ["a", "Script on frame 1 of the main timeline stopped: it ran more than 100000 steps (an endless loop?)"]); + let s = step(&d, &s.state, &[], &mut NoScripts); + assert_eq!((s.state.root.frame, s.output.as_slice()), (1, ["frame 2".to_string()].as_slice())); + // A runtime error stops only its script. + let d = scripted(2, &[(0, "trace(\"x\");\ntrace(ghost.x);\ntrace(\"y\");")], vec![], vec![]); + assert_eq!(start(&d, &mut NoScripts).output, ["x", "Script on frame 1 of the main timeline stopped: line 2: no instance named “ghost” here"]); + // Many listeners that each loop share one step's fuel; the step ends with one message. + let mut src = String::from("stop();\n"); + for i in 0..15 { + src.push_str(&format!("addEventListener(Event.ENTER_FRAME, function (e:Event):void {{ var n:int = {i}; while (true) n++; }});\n")); + } + let d = scripted(2, &[(0, &src)], vec![], vec![]); + let s = step(&d, &start(&d, &mut NoScripts).state, &[], &mut NoScripts); + assert_eq!(s.output.iter().filter(|l| l.ends_with("(an endless loop?)")).count(), 10, "{:?}", s.output); + assert!(s.output.last().is_some_and(|l| l.starts_with("Stopped running actions this frame: scripts ran more than 1000000 steps")), "{:?}", s.output); +} + +#[test] +fn listeners_know_their_target_and_current_target() { + let mut d = button_doc(); + { + let tl = d.timeline_mut(0); + let l0 = Arc::make_mut(&mut tl.layers[0]); + l0.keyframes[0] = as3(l0.keyframes[0].clone(), "stop();\ngo.addEventListener(MouseEvent.CLICK, clicked);\nfunction clicked(e:MouseEvent):void { trace(e.target.name, e.currentTarget == go, e.target != stage, e.currentTarget.x); report(e); }\nfunction report(ev:MouseEvent):void { trace(\"from \" + ev.currentTarget.name); }"); + let k = Arc::make_mut(&mut Arc::make_mut(&mut tl.layers[1]).keyframes[0]); + if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind { + events.clear(); + } + } + let p = Vec2::new(150.0, 150.0); + let s = step(&d, &start(&d, &mut NoScripts).state, &[Event::Move(p), Event::Down(p), Event::Up(p)], &mut NoScripts); + assert_eq!(s.output, ["go true true 100", "from go"]); +} + +#[test] +fn scripted_play_is_deterministic() { + let src = "var n:Number = 0;\naddEventListener(Event.ENTER_FRAME, function (e:Event):void { n += Math.random(); if (n > 2) { trace(n); n = 0; } });"; + let d = scripted(4, &[(0, src)], vec![], vec![]); + let play = || { + let mut s = start_seeded(&d, 3, &mut NoScripts); + let mut out = Vec::new(); + for _ in 0..40 { + s = step(&d, &s.state, &[Event::KeyDown(65)], &mut NoScripts); + out.extend(s.output.clone()); + } + (s.state, out) + }; + let (a, b) = (play(), play()); + assert!(!a.1.is_empty()); + assert_eq!(a, b); +} + +// ----- text fields (ADR 0066) --------------------------------------------------------------- + +/// A host that lays fields out in a 10 px monospace (the fonts live above this crate). +struct Mono; + +impl ScriptHost for Mono { + fn run(&mut self, _: &PluginScript, _: &ScriptContext<'_>) -> ScriptRun { + ScriptRun::default() + } + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + let f = block.field.as_ref()?; + Some(crate::field::mono_look(shown, 10.0, 10.0, f.wrap_width(block.box_width))) + } +} + +fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc { + let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None }; + Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }) +} + +fn field_doc(script: &str) -> Document { + let fields = vec![field(5, "score_txt", "0", TextKind::Dynamic, 10.0, 10.0), field(6, "name_txt", "", TextKind::Input, 10.0, 50.0), field(7, "", "", TextKind::Input, 10.0, 90.0)]; + doc(vec![layer(1, vec![as3(kf(0, 1, fields, vec![], ""), script)])], vec![]) +} + +fn text_of(st: &PlayerState, id: u64) -> Option { + st.fields.get(&vec![ElementId(id)]).and_then(|f| f.text.clone()) +} + +#[test] +fn scripts_set_and_read_dynamic_text() { + let d = field_doc("stop();\nvar n:int = 0;\nscore_txt.text = \"Score: \" + n;\nscore_txt.appendText(\"!\");\ntrace(score_txt.text, score_txt.length, name_txt.text == \"\");\nscore_txt.x = 20;\nghost_txt.text = \"x\";"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 0!")); + assert!(s.output.contains(&"Score: 0! 9 true".to_string()), "{:?}", s.output); + assert!(s.output.iter().any(|l| l.contains("no instance named “ghost_txt”")), "{:?}", s.output); + // Laid out by the host, drawn in place of the authored outline, where the script moved it. + let look = s.state.fields.get(&vec![ElementId(5)]).and_then(|f| f.look.clone()).expect("laid out"); + assert_eq!(look.lines[0].end, 9); + let dl = evaluate_player(&d, &s.state); + assert!(dl.items.iter().any(|i| Arc::ptr_eq(&i.path, &look.outline) && i.transform.m[4] == 20.0)); + // Without a host that can lay out, the text is still set and read; it draws only its box. + let s2 = start(&d, &mut NoScripts); + assert_eq!(text_of(&s2.state, 5).as_deref(), Some("Score: 0!")); + // Static text and other instances aren't fields. + let d = field_doc("hero.text = \"x\";"); + assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("no instance named “hero”"))); +} + +#[test] +fn the_viewer_types_into_input_fields_and_scripts_read_it() { + let d = field_doc("stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hello, \" + name_txt.text; }\n}"); + let mut h = Mono; + let s = start(&d, &mut h); + // A click in the input field gives it the keyboard; typing goes in, editing keys edit. + let mut ev = vec![Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0))]; + ev.extend("Adx".chars().map(Event::Char)); + ev.extend([Event::KeyDown(8), Event::KeyDown(37), Event::Char('a'), Event::KeyDown(35), Event::Char('!')]); + let s = input(&d, &s.state, &ev, &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(6)])); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Aad!")); + // Shift+Home selects; typing replaces it; Enter reaches the stage's key listener too. + let s = input(&d, &s.state, &[Event::KeyDown(16), Event::KeyDown(36), Event::KeyUp(16), Event::Char('B'), Event::Char('o'), Event::KeyDown(13)], &mut h); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo")); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo")); + // The focused field draws its caret; a click elsewhere takes the keyboard away. + let caret = |st: &PlayerState| evaluate_player(&d, st).items.iter().filter(|i| i.fill.is_some() && i.masks.is_none() && i.path.bounds().width() <= 1.01 && i.path.bounds().height() > 5.0).count(); + assert_eq!(caret(&s.state), 1); + let s = input(&d, &s.state, &[Event::Down(Vec2::new(300.0, 300.0)), Event::Up(Vec2::new(300.0, 300.0)), Event::Char('z')], &mut h); + assert_eq!(s.state.focus, None); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"), "no field, no typing"); + assert_eq!(caret(&s.state), 0); + // A dynamic field takes no typing; Tab goes from input field to input field. + let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 15.0)), Event::Up(Vec2::new(20.0, 15.0)), Event::Char('q')], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(5)]), "a selectable dynamic field can be focused"); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo")); + let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(9)], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(7)])); + let s = input(&d, &s.state, &[Event::KeyDown(9)], &mut h); + assert_eq!(s.state.focus, Some(vec![ElementId(6)]), "Tab wraps round"); + assert_eq!(s.state.fields.get(&vec![ElementId(6)]).map(|f| f.selection()), Some((0, 2)), "and selects the field's text"); +} + +#[test] +fn fields_draw_their_box_and_the_authored_text_everywhere() { + let d = field_doc(""); + // The authoring frame and the player draw the authored outline, a border, inside a clip. + for dl in [evaluate(&d, 0), evaluate_player(&d, &start(&d, &mut NoScripts).state)] { + let texts = dl.items.iter().filter(|i| i.path.bounds() == Path::rect(2.0, 2.0, 8.0, 8.0).bounds() && i.masks.is_none()).count(); + assert_eq!(texts, 3); + assert_eq!(dl.items.iter().filter(|i| i.stroke.is_some()).count(), 3, "three borders"); + assert_eq!(dl.items.iter().filter(|i| i.masks.is_some()).count(), 3, "each box clips its text"); + assert_eq!(dl.clip_parents.len(), 3); + } +} + +#[test] +fn typing_is_deterministic() { + let d = field_doc("stop();"); + let ev: Vec = [Event::Down(Vec2::new(30.0, 55.0)), Event::Up(Vec2::new(30.0, 55.0))].into_iter().chain("deterministic".chars().map(Event::Char)).chain([Event::KeyDown(16), Event::KeyDown(37), Event::KeyDown(37), Event::Char('X')]).collect(); + let a = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono); + let b = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono); + assert_eq!(a, b); + assert_eq!(text_of(&a.state, 6).as_deref(), Some("deterministX")); +} diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs new file mode 100644 index 00000000..701ee881 --- /dev/null +++ b/crates/doc/src/publish.rs @@ -0,0 +1,422 @@ +//! Publish Settings (ADR 0060): which formats File › Publish writes, each with its options and +//! output name, kept in the document as Animate keeps them. +//! +//! Every format is always present, in the fixed order Publish runs them; a format is on or off. +//! Outputs are templates relative to the document's folder: `{name}` is the document's file name +//! without its extension. A file written before publish settings existed has none and gets +//! [`PublishProfile::default`] (the HTML canvas page on, the rest off) the first time it opens. + +use serde::{Deserialize, Serialize}; + +/// The formats File › Publish can write, in the order it writes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PublishFormat { + Html, + Gif, + Apng, + Webp, + Video, + Lottie, + SpriteSheet, + PngSequence, + Png, + Svg, + Audio, +} + +impl PublishFormat { + /// Every format, in the order Publish runs them. + pub const ALL: [PublishFormat; 11] = [ + PublishFormat::Html, + PublishFormat::Gif, + PublishFormat::Apng, + PublishFormat::Webp, + PublishFormat::Video, + PublishFormat::Lottie, + PublishFormat::SpriteSheet, + PublishFormat::PngSequence, + PublishFormat::Png, + PublishFormat::Svg, + PublishFormat::Audio, + ]; + + /// The stable key used by commands and the file format. + pub fn key(self) -> &'static str { + match self { + PublishFormat::Html => "html", + PublishFormat::Gif => "gif", + PublishFormat::Apng => "apng", + PublishFormat::Webp => "webp", + PublishFormat::Video => "video", + PublishFormat::Lottie => "lottie", + PublishFormat::SpriteSheet => "sprite_sheet", + PublishFormat::PngSequence => "png_sequence", + PublishFormat::Png => "png", + PublishFormat::Svg => "svg", + PublishFormat::Audio => "audio", + } + } + + pub fn from_key(key: &str) -> Option { + PublishFormat::ALL.into_iter().find(|f| f.key() == key) + } + + /// The English name of the format (translated where it is drawn). + pub fn label(self) -> &'static str { + match self { + PublishFormat::Html => "HTML canvas", + PublishFormat::Gif => "Animated GIF", + PublishFormat::Apng => "Animated PNG", + PublishFormat::Webp => "Animated WebP", + PublishFormat::Video => "Video", + PublishFormat::Lottie => "Lottie", + PublishFormat::SpriteSheet => "Sprite sheet", + PublishFormat::PngSequence => "PNG sequence", + PublishFormat::Png => "PNG image", + PublishFormat::Svg => "SVG image", + PublishFormat::Audio => "Audio", + } + } + + /// The output a new profile gives the format. + pub fn default_output(self) -> &'static str { + match self { + PublishFormat::Html => "{name}.html", + PublishFormat::Gif => "{name}.gif", + // Not {name}.png: the PNG image has that. + PublishFormat::Apng => "{name}_animated.png", + PublishFormat::Webp => "{name}.webp", + PublishFormat::Video => "{name}.webm", + PublishFormat::Lottie => "{name}.json", + PublishFormat::SpriteSheet => "{name}_sheet.png", + PublishFormat::PngSequence => "{name}_frames", + PublishFormat::Png => "{name}.png", + PublishFormat::Svg => "{name}.svg", + PublishFormat::Audio => "{name}.wav", + } + } + + /// The file extensions the output may end in (none for the PNG sequence: a folder). + pub fn extensions(self) -> &'static [&'static str] { + match self { + PublishFormat::Html => &["html", "htm"], + PublishFormat::Gif => &["gif"], + PublishFormat::Apng => &["png", "apng"], + PublishFormat::Webp => &["webp"], + PublishFormat::Video => &["webm", "mp4"], + PublishFormat::Lottie => &["json"], + PublishFormat::SpriteSheet | PublishFormat::Png => &["png"], + PublishFormat::PngSequence => &[], + PublishFormat::Svg => &["svg"], + PublishFormat::Audio => &["wav"], + } + } +} + +/// Longest output template, in characters. +pub const MAX_OUTPUT_CHARS: usize = 512; +/// Longest HTML page title, in characters. +pub const MAX_TITLE_CHARS: usize = 256; +/// Largest export scale. +pub const MAX_PUBLISH_SCALE: f32 = 8.0; +/// Most plays an animated PNG or WebP's loop count says (WebP stores it in 16 bits). +pub const MAX_PLAYS: u32 = 65_535; + +/// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct FrameRange { + #[serde(skip_serializing_if = "Option::is_none")] + pub from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub to: Option, +} + +macro_rules! format_settings { + ($(#[$meta:meta])* $name:ident, $format:expr, $enabled:expr, { $($(#[$fmeta:meta])* $field:ident : $ty:ty = $default:expr),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] + #[serde(default)] + pub struct $name { + /// Publish writes this format. + pub enabled: bool, + /// A path relative to the document's folder; `{name}` is the document's name. + pub output: String, + $($(#[$fmeta])* pub $field: $ty,)* + } + impl Default for $name { + fn default() -> Self { + $name { enabled: $enabled, output: $format.default_output().to_string(), $($field: $default,)* } + } + } + }; +} + +format_settings!( + /// The movie as one web page (`file.export_html`, ADR 0028). + HtmlSettings, PublishFormat::Html, true, { + /// The page's title; empty: the output's file name. + title: String = String::new(), + sound: bool = true, + fit: bool = true, + } +); +format_settings!( + /// An animated GIF (`file.export_gif`). + GifSettings, PublishFormat::Gif, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + #[serde(rename = "loop")] + looping: bool = true, + } +); +format_settings!( + /// An animated PNG: full colour, real alpha (`file.export_apng`, ADR 0063). + ApngSettings, PublishFormat::Apng, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); +format_settings!( + /// An animated WebP, lossless (`file.export_webp`, ADR 0063). + WebpSettings, PublishFormat::Webp, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); +format_settings!( + /// WebM or MP4 through the user's ffmpeg (`file.export_video`). + VideoSettings, PublishFormat::Video, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + audio: bool = true, + } +); +format_settings!( + /// A Lottie animation (`file.export_lottie`). + LottieSettings, PublishFormat::Lottie, false, { + range: FrameRange = FrameRange::default(), + background: bool = false, + } +); +format_settings!( + /// A sprite sheet and its JSON frame map (`file.export_sprite_sheet`). + SpriteSheetSettings, PublishFormat::SpriteSheet, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// 0: as square as it can be. + columns: u32 = 0, + padding: u32 = 0, + background: bool = false, + } +); +format_settings!( + /// One PNG per frame in a folder (`file.export_png_sequence`). + PngSequenceSettings, PublishFormat::PngSequence, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + } +); +format_settings!( + /// One frame as a PNG (`file.export_png`). + PngSettings, PublishFormat::Png, false, { + /// The movie frame (0-based, every scene in order). + frame: u32 = 0, + scale: f32 = 1.0, + } +); +format_settings!( + /// One frame as an SVG (`file.export_svg`). + SvgSettings, PublishFormat::Svg, false, { + /// The movie frame (0-based, every scene in order). + frame: u32 = 0, + } +); +format_settings!( + /// The movie's soundtrack as a WAV (`file.export_audio`). + AudioSettings, PublishFormat::Audio, false, { + range: FrameRange = FrameRange::default(), + rate: u32 = 44_100, + /// 16, 24, or 32 (float). + bits: u32 = 16, + } +); + +/// What File › Publish writes: every format with its options (ADR 0060). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PublishProfile { + pub html: HtmlSettings, + pub gif: GifSettings, + pub apng: ApngSettings, + pub webp: WebpSettings, + pub video: VideoSettings, + pub lottie: LottieSettings, + pub sprite_sheet: SpriteSheetSettings, + pub png_sequence: PngSequenceSettings, + pub png: PngSettings, + pub svg: SvgSettings, + pub audio: AudioSettings, +} + +fn clean_scale(s: f32) -> f32 { + if s.is_finite() && s > 0.0 { s.min(MAX_PUBLISH_SCALE) } else { 1.0 } +} + +fn clip(s: &mut String, max: usize) { + if s.chars().count() > max { + *s = s.chars().take(max).collect(); + } +} + +impl PublishProfile { + pub fn is_default(&self) -> bool { + *self == PublishProfile::default() + } + + /// Whether Publish writes `f`, and its output template. + pub fn target(&self, f: PublishFormat) -> (bool, &str) { + match f { + PublishFormat::Html => (self.html.enabled, &self.html.output), + PublishFormat::Gif => (self.gif.enabled, &self.gif.output), + PublishFormat::Apng => (self.apng.enabled, &self.apng.output), + PublishFormat::Webp => (self.webp.enabled, &self.webp.output), + PublishFormat::Video => (self.video.enabled, &self.video.output), + PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output), + PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output), + PublishFormat::PngSequence => (self.png_sequence.enabled, &self.png_sequence.output), + PublishFormat::Png => (self.png.enabled, &self.png.output), + PublishFormat::Svg => (self.svg.enabled, &self.svg.output), + PublishFormat::Audio => (self.audio.enabled, &self.audio.output), + } + } + + /// `f`'s on/off switch and output template, to change. + pub fn target_mut(&mut self, f: PublishFormat) -> (&mut bool, &mut String) { + match f { + PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output), + PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output), + PublishFormat::Apng => (&mut self.apng.enabled, &mut self.apng.output), + PublishFormat::Webp => (&mut self.webp.enabled, &mut self.webp.output), + PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output), + PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output), + PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output), + PublishFormat::PngSequence => (&mut self.png_sequence.enabled, &mut self.png_sequence.output), + PublishFormat::Png => (&mut self.png.enabled, &mut self.png.output), + PublishFormat::Svg => (&mut self.svg.enabled, &mut self.svg.output), + PublishFormat::Audio => (&mut self.audio.enabled, &mut self.audio.output), + } + } + + /// The formats that are on, in publishing order. + pub fn enabled(&self) -> Vec { + PublishFormat::ALL.into_iter().filter(|f| self.target(*f).0).collect() + } + + /// Brings every value into range, so whatever a file holds, publishing can run: scales in + /// (0, 8], a known sample rate and bit depth, bounded text. + pub fn sanitize(&mut self) { + for f in PublishFormat::ALL { + let (_, output) = self.target_mut(f); + clip(output, MAX_OUTPUT_CHARS); + if output.trim().is_empty() { + *output = f.default_output().to_string(); + } + } + clip(&mut self.html.title, MAX_TITLE_CHARS); + for s in [&mut self.gif.scale, &mut self.apng.scale, &mut self.webp.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { + *s = clean_scale(*s); + } + self.sprite_sheet.padding = self.sprite_sheet.padding.min(256); + self.apng.plays = self.apng.plays.min(MAX_PLAYS); + self.webp.plays = self.webp.plays.min(MAX_PLAYS); + self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000); + self.audio.rate = self.audio.rate.clamp(8_000, 192_000); + if !matches!(self.audio.bits, 16 | 24 | 32) { + self.audio.bits = 16; + } + for r in [&mut self.gif.range, &mut self.apng.range, &mut self.webp.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { + if let (Some(a), Some(b)) = (r.from, r.to) + && b < a + { + *r = FrameRange { from: Some(b), to: Some(a) }; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_round_trip_and_defaults_are_distinct() { + for f in PublishFormat::ALL { + assert_eq!(PublishFormat::from_key(f.key()), Some(f)); + } + let p = PublishProfile::default(); + assert_eq!(p.enabled(), vec![PublishFormat::Html], "a new document publishes its web page"); + let mut outs: Vec<&str> = PublishFormat::ALL.iter().map(|f| p.target(*f).1).collect(); + outs.sort_unstable(); + outs.dedup(); + assert_eq!(outs.len(), PublishFormat::ALL.len(), "no two formats write the same file by default"); + } + + #[test] + fn profile_round_trips_and_missing_fields_default() { + let mut p = PublishProfile::default(); + p.gif.enabled = true; + p.gif.scale = 0.5; + p.gif.looping = false; + p.gif.range = FrameRange { from: Some(2), to: Some(9) }; + p.html.title = "Walk".into(); + p.audio.bits = 24; + let text = serde_json::to_string(&p).unwrap(); + assert!(text.contains("\"loop\":false") && text.contains("\"enabled\":true"), "{text}"); + let back: PublishProfile = serde_json::from_str(&text).unwrap(); + assert_eq!(back, p); + // A profile from an older build, with fields and formats missing. + let partial: PublishProfile = serde_json::from_str(r#"{"gif": {"enabled": true}}"#).unwrap(); + assert!(partial.gif.enabled && partial.html.enabled); + assert_eq!(partial.gif.output, "{name}.gif"); + assert_eq!(partial.gif.scale, 1.0); + assert_eq!((partial.apng.plays, partial.webp.background, partial.webp.enabled), (0, false, false), "formats newer than the file get their defaults"); + let mut q = PublishProfile::default(); + q.apng.plays = 3; + q.webp.background = true; + let text = serde_json::to_string(&q).unwrap(); + assert!(text.contains("\"apng\"") && text.contains("\"loop\":3"), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), q); + } + + #[test] + fn sanitize_brings_everything_into_range() { + let mut p = PublishProfile::default(); + p.gif.scale = f32::NAN; + p.png.scale = 1e9; + p.audio.rate = 5; + p.audio.bits = 7; + p.sprite_sheet.padding = u32::MAX; + p.webp.plays = u32::MAX; + p.video.output = " ".into(); + p.html.title = "x".repeat(10_000); + p.lottie.range = FrameRange { from: Some(9), to: Some(2) }; + p.sanitize(); + assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256)); + assert_eq!(p.video.output, "{name}.webm"); + assert_eq!(p.webp.plays, MAX_PLAYS); + assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS); + assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) }); + } +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 4633a16b..2ebf2d77 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -41,19 +41,19 @@ fn key(start: u32, duration: u32, elements: Vec>, tween: Option Document { - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; let (w, h) = (1280.0, 720.0); // --- library ------------------------------------------------------------------------- let ball_id = SymbolId(d.alloc_id()); let ball_shape = Shape::filled( Path::ellipse(0.0, 0.0, 48.0, 48.0), - Paint::Radial { center: Vec2::new(-16.0, -18.0), radius: 70.0, stops: stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)]) }, + Paint::radial(Vec2::new(-16.0, -18.0), 70.0, stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)])), ) .with_stroke(Rgba::hex(0x5a1410), 3.0); let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape)); let ball_layer = layer(d.alloc_id(), "body", 0x4fa3ff, vec![key(0, 1, vec![ball_el], None)]); - d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![ball_layer] } })); + d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![ball_layer] } })); let star_id = SymbolId(d.alloc_id()); let star_shape = Shape::filled(Path::star(0.0, 0.0, 60.0, 26.0, 5), Paint::Solid(Rgba::hex(0xfff6a8))).with_stroke(Rgba::hex(0xe0a400), 2.5); @@ -67,7 +67,7 @@ pub fn demo() -> Document { }) .collect(); let star_layer = layer(d.alloc_id(), "spin", 0x4fa3ff, star_keys); - d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![star_layer] } })); + d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![star_layer] } })); // --- main timeline (index 0 = top) --------------------------------------------------- const LEN: u32 = 48; @@ -101,7 +101,7 @@ pub fn demo() -> Document { // Sun: pulses with an ease in-out. let sun_layer_id = d.alloc_id(); let sun_inst = ElementId(d.alloc_id()); - let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::Radial { center: Vec2::ZERO, radius: 90.0, stops: stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)]) }); + let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::radial(Vec2::ZERO, 90.0, stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)]))); let sun_keys = [(0u32, 24u32, 1.0f32), (24, 23, 1.15), (47, 1, 1.0)] .into_iter() .enumerate() @@ -132,7 +132,7 @@ pub fn demo() -> Document { Affine::IDENTITY, ElementKind::Shape(Shape::filled( Path::rect(0.0, 0.0, w, h), - Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(0.0, h), stops: stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)]) }, + Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(0.0, h), stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)])), )), ); let mut sky = layer(sky_id, "Sky", 0x7e57c2, vec![key(0, LEN, vec![sky_el], None)]); @@ -147,7 +147,7 @@ pub fn demo() -> Document { /// whose last frame traces a line and goes back to the menu. pub fn interactive() -> Document { use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target}; - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; const LEN: u32 = 36; let solid = |c: u32| Paint::Solid(Rgba::hex(c)); @@ -161,7 +161,7 @@ pub fn interactive() -> Document { let (up, over, down) = (face(&mut d, 0x3d8bfd), face(&mut d, 0x6aa8ff), face(&mut d, 0x2a64c0)); let hit_area = el(&mut d, "hit", Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(-120.0, -50.0, 240.0, 100.0), solid(0x000000)))); let states = layer(d.alloc_id(), "states", 0x4fa3ff, vec![key(0, 1, up, None), key(1, 1, over, None), key(2, 1, down, None), key(3, 1, vec![hit_area], None)]); - d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, timeline: Timeline { layers: vec![states] } })); + d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![states] } })); // A movie clip that spins on its own timeline. let spinner_id = SymbolId(d.alloc_id()); @@ -175,7 +175,7 @@ pub fn interactive() -> Document { }) .collect(); let spin = layer(d.alloc_id(), "spin", 0xffd54a, spin_keys); - d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![spin] } })); + d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![spin] } })); // Main timeline: actions on top, then the button (menu frame), the show, the backdrop. let mut menu = key(0, 1, Vec::new(), None); @@ -211,7 +211,7 @@ pub fn interactive() -> Document { /// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens. /// Every element keeps one `Arc` across its keyframes, as a real tweened shape does. pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { - let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000)); let mut seed = 0x2545_f491_u32; let mut rnd = move || { @@ -249,7 +249,7 @@ pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { name: String::new(), transform: pose(x + dx, y + dy, 1.0, 1.0, phase * 20.0), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default(), merge: false }), + kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default(), merge: false, warp: None }), }) }) .collect(); diff --git a/crates/doc/src/skin.rs b/crates/doc/src/skin.rs new file mode 100644 index 00000000..6af97ef6 --- /dev/null +++ b/crates/doc/src/skin.rs @@ -0,0 +1,334 @@ +//! Shape armatures (ADR 0071): bones drawn inside one shape, whose outline bends with them. +//! +//! A shape armature is an [`Armature`] with a [`Skin`]. Its bones join *joint nodes* instead of +//! symbol instances: the root bones start on the shape itself (its element id) and every other +//! bone starts on the node of the bone it hangs from. A node is a frame that the bone into it +//! turns; at rest every node's frame is the shape's own local space, so a bone's head and tail +//! are points of the shape as it was drawn, and a node's transform under a pose is the bone's +//! **skinning matrix**. Forward and inverse kinematics are ADR 0043's ([`crate::armature::place`], +//! [`crate::armature::solve`]): nothing about posing is new. +//! +//! The skin keeps the outline as it was drawn (`rest`) and one [`Binding`] per anchor of it +//! (every `MoveTo`, `LineTo`, `QuadTo` and `CubicTo` end, in path order): the bones the anchor +//! follows and how much. Automatic binding ([`auto_binding`]) weighs each bone by the inverse +//! fourth power of the anchor's distance to the bone's segment, keeps the strongest +//! [`MAX_INFLUENCES`] and normalises them to sum to 1; the Bind tool (`bone.bind`) overrides +//! anchors by hand. The posed outline ([`deform`]) is linear blend skinning: each anchor moves +//! by the weighted sum of its bones' matrices, and each handle by the blend of the anchor it +//! belongs to, so curves stay smooth through a bend. Stroke width is drawn after the outline +//! (the shape's own transform is untouched), so strokes keep their width. +//! +//! Linear blend skinning is the standard method (N. Magnenat-Thalmann, R. Laperrière and +//! D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*, +//! Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*, +//! SIGGRAPH 2000, §2, which names it skeleton subspace deformation). + +use crate::armature::{Armature, BoneId, Pose}; +use crate::{Element, ElementId, ElementKind}; +use anicraft_geom::{Affine, Path, PathCmd, Vec2, segment_distance}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::Arc; + +/// Most bones one anchor follows. +pub const MAX_INFLUENCES: usize = 4; +/// Most anchors a shape with bones may have (a hand-drawn shape has tens to a few thousand). +pub const MAX_SKIN_POINTS: usize = 20_000; +/// Distances below this count as this (px), so an anchor on a bone has a finite weight. +const NEAR: f32 = 0.5; +/// A bone whose share is below this after normalising is dropped from the anchor. +const FAINT: f32 = 0.01; + +/// One bone's share of an anchor: `[bone, weight]` in files. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Influence(pub BoneId, pub f32); + +/// The bones one anchor follows. Weights are positive and sum to 1; an anchor with none stays +/// where it was drawn. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Binding { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bones: Vec, + /// Set with the Bind tool: automatic binding (after adding or removing a bone) leaves it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub manual: bool, +} + +impl Binding { + /// The share bone `b` has of this anchor (0 when it doesn't follow it). + pub fn weight(&self, b: BoneId) -> f32 { + self.bones.iter().find(|i| i.0 == b).map_or(0.0, |i| i.1) + } + + /// Keeps positive, finite weights of bones in `keep` (one each, the strongest + /// [`MAX_INFLUENCES`]) and scales them to sum to 1. Returns whether anything changed. + pub fn normalize(&mut self, keep: impl Fn(BoneId) -> bool) -> bool { + let before = self.bones.clone(); + let mut seen = Vec::with_capacity(self.bones.len()); + self.bones.retain(|i| i.1.is_finite() && i.1 > 0.0 && keep(i.0) && !seen.contains(&i.0) && { + seen.push(i.0); + true + }); + self.bones.sort_by(|a, b| b.1.total_cmp(&a.1)); + self.bones.truncate(MAX_INFLUENCES); + let sum: f32 = self.bones.iter().map(|i| i.1).sum(); + if sum > 0.0 && sum.is_finite() { + for i in &mut self.bones { + i.1 /= sum; + } + } else { + self.bones.clear(); + } + self.bones != before + } +} + +/// How a shape is bound to its armature's bones. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Skin { + /// The shape the bones are inside (an element of the armature layer's keyframes). + pub shape: ElementId, + /// The outline as it was drawn, in the shape's local space: the pose of every bone at 0. + pub rest: Arc, + /// One per anchor of `rest`, in path order. + #[serde(default)] + pub points: Vec, +} + +impl Skin { + /// A skin for `shape` drawn as `rest`, its anchors not yet bound. + pub fn new(shape: ElementId, rest: Arc) -> Skin { + let points = vec![Binding::default(); anchors(&rest).len()]; + Skin { shape, rest, points } + } +} + +/// The anchors of `path` in order: every command's end point. +pub fn anchors(path: &Path) -> Vec { + path.cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p), + PathCmd::Close => None, + }) + .collect() +} + +/// Where every bone of a shape armature lies as drawn, in the shape's space: its joint and end. +pub fn rest_segments(arm: &Armature) -> Vec<(BoneId, Vec2, Vec2)> { + // Every node's rest frame is the shape's space (`rest` is the identity for shape bones), so + // composing the rests places each bone; a hand-edited file with other rests still works. + let mut node: HashMap = HashMap::new(); + let root = arm.skin.as_ref().map(|s| s.shape); + arm.bones + .iter() + .filter_map(|b| { + let wp = if Some(b.parent) == root { Affine::IDENTITY } else { *node.get(&b.parent)? }; + let wc = wp.mul(&b.rest); + node.insert(b.child, wc); + Some((b.id, wp.apply(b.head), wc.apply(b.tail))) + }) + .collect() +} + +/// Automatic binding of an anchor at `p` (the shape's space, as drawn): each bone weighs +/// `1 / max(d, 0.5)⁴` where `d` is the distance from `p` to the bone's segment; the strongest +/// [`MAX_INFLUENCES`] are kept, faint ones (under 1 %) dropped, and the rest sum to 1. An anchor +/// near one bone follows it alone; one near a joint shares it between the bones that meet +/// there, so the outline bends smoothly. Empty only without bones. +pub fn auto_binding(segments: &[(BoneId, Vec2, Vec2)], p: Vec2) -> Binding { + let mut bones: Vec = segments + .iter() + .map(|&(id, a, b)| { + let d = segment_distance(p, a, b).max(NEAR); + Influence(id, 1.0 / (d * d * d * d)) + }) + .filter(|i| i.1.is_finite() && i.1 > 0.0) + .collect(); + // Weighed relative to the nearest bone, so a far-away shape keeps finite numbers. + let top = bones.iter().map(|i| i.1).fold(0.0f32, f32::max); + if top > 0.0 { + for i in &mut bones { + i.1 /= top; + } + } + let mut out = Binding { bones, manual: false }; + out.normalize(|_| true); + let before = out.bones.len(); + out.bones.retain(|i| i.1 >= FAINT); + if out.bones.len() != before { + out.normalize(|_| true); + } + out +} + +/// Binds every anchor not bound by hand afresh (after the bones changed), and repairs the hand +/// bound ones: bones that went away leave them, and one left with none goes back to automatic +/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor. +pub fn rebind(arm: &mut Armature) { + let segments = rest_segments(arm); + let ids: Vec = arm.bones.iter().map(|b| b.id).collect(); + let Some(skin) = arm.skin.as_mut() else { return }; + let pts = anchors(&skin.rest); + skin.points.resize(pts.len(), Binding::default()); + for (b, &p) in skin.points.iter_mut().zip(&pts) { + if b.manual { + let had = !b.bones.is_empty(); + b.normalize(|id| ids.contains(&id)); + if !had || !b.bones.is_empty() { + continue; + } + } + *b = auto_binding(&segments, p); + } +} + +/// Every bone's skinning matrix under `pose`: how the pose moves the shape's space near it (the +/// identity at rest, exactly). +pub fn matrices(arm: &Armature, pose: &Pose) -> HashMap { + let Some(skin) = &arm.skin else { return HashMap::new() }; + let mut node: HashMap = HashMap::new(); + node.insert(skin.shape, Affine::IDENTITY); + let mut out = HashMap::with_capacity(arm.bones.len()); + for b in &arm.bones { + let Some(wp) = node.get(&b.parent).copied() else { continue }; + let a = b.allow(pose.angle(b.id)); + let wc = if a == 0.0 { wp.mul(&b.rest) } else { crate::armature::turn_about(wp.apply(b.head), a).mul(&wp.mul(&b.rest)) }; + if wc.is_finite() { + node.insert(b.child, wc); + out.insert(b.id, wc); + } + } + out +} + +/// The blend of `binding`'s bone matrices; `None` when it doesn't move (no bones, or every one +/// of them at rest), so a point at rest is kept bit for bit. +fn blend(binding: &Binding, m: &HashMap) -> Option { + let mut moved = false; + let mut acc = [0.0f32; 6]; + let mut total = 0.0f32; + for &Influence(b, w) in &binding.bones { + let x = m.get(&b).copied().unwrap_or(Affine::IDENTITY); + moved |= x != Affine::IDENTITY; + for (a, v) in acc.iter_mut().zip(x.m) { + *a += w * v; + } + total += w; + } + if !moved || total <= 0.0 { + return None; + } + // Weights sum to 1; dividing keeps a hand-edited file's rounding from scaling the shape. + Some(Affine { m: acc.map(|v| v / total) }) +} + +fn mix(a: Option, b: Option) -> Option { + match (a, b) { + (None, None) => None, + (a, b) => { + let (a, b) = (a.unwrap_or(Affine::IDENTITY), b.unwrap_or(Affine::IDENTITY)); + let mut m = [0.0f32; 6]; + for (i, v) in m.iter_mut().enumerate() { + *v = 0.5 * (a.m.get(i).copied().unwrap_or(0.0) + b.m.get(i).copied().unwrap_or(0.0)); + } + Some(Affine { m }) + } + } +} + +/// The outline `pose` bends the skin's shape into (the shape's space): linear blend skinning of +/// every anchor, each cubic handle moving with the anchor it leaves or enters and a quadratic's +/// control with the mean of its two ends. At rest (or where no bound bone turned) points are +/// exactly as drawn. +pub fn deform(arm: &Armature, pose: &Pose) -> Option> { + let skin = arm.skin.as_ref()?; + let m = matrices(arm, pose); + if m.values().all(|x| *x == Affine::IDENTITY) { + return Some(skin.rest.clone()); + } + let none = Binding::default(); + let mut idx = 0usize; + let at = |i: usize| blend(skin.points.get(i).unwrap_or(&none), &m); + let on = |x: Option, p: Vec2| x.map_or(p, |x| x.apply(p)); + let mut prev: Option = None; + let mut cmds = Vec::with_capacity(skin.rest.cmds.len()); + for c in &skin.rest.cmds { + let next = match *c { + PathCmd::Close => { + cmds.push(PathCmd::Close); + continue; + } + _ => at(idx), + }; + idx += 1; + cmds.push(match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(on(next, p)), + PathCmd::LineTo(p) => PathCmd::LineTo(on(next, p)), + PathCmd::QuadTo(q, p) => PathCmd::QuadTo(on(mix(prev, next), q), on(next, p)), + PathCmd::CubicTo(c1, c2, p) => PathCmd::CubicTo(on(prev, c1), on(next, c2), on(next, p)), + PathCmd::Close => PathCmd::Close, + }); + prev = next; + } + Some(Arc::new(Path { cmds })) +} + +/// Puts the skin's shape in `elements` in the outline `pose` bends it into (copy-on-write). +/// Returns whether it changed. +pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { + let Some(skin) = &arm.skin else { return false }; + let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { return false }; + let ElementKind::Shape(s) = &e.kind else { return false }; + let Some(path) = deform(arm, pose) else { return false }; + if Arc::ptr_eq(&s.path, &path) || *s.path == *path { + return false; + } + if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind { + s.path = path; + } + true +} + +/// The points of a shape armature's shape in `elements` (evaluated: posed), in point order, in +/// the layer's space: the anchors of its outline as it shows. +pub fn points_shown(arm: &Armature, elements: &[Arc]) -> Vec { + let Some(skin) = &arm.skin else { return Vec::new() }; + elements + .iter() + .find(|e| e.id == skin.shape) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()), + _ => None, + }) + .unwrap_or_default() +} + +/// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`] +/// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive +/// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed. +pub fn sanitize(arm: &mut Armature) -> bool { + let Some(skin) = &arm.skin else { return false }; + let n = anchors(&skin.rest).len(); + if n > MAX_SKIN_POINTS || arm.bones.iter().any(|b| b.child == skin.shape) { + arm.skin = None; + return true; + } + let before = arm.skin.clone(); + let ids: Vec = arm.bones.iter().map(|b| b.id).collect(); + let segments = rest_segments(arm); + let Some(skin) = arm.skin.as_mut() else { return false }; + let pts = anchors(&skin.rest); + skin.points.resize(n, Binding::default()); + for (b, &p) in skin.points.iter_mut().zip(&pts) { + b.normalize(|id| ids.contains(&id)); + if b.bones.is_empty() && !b.manual { + *b = auto_binding(&segments, p); + } + } + arm.skin != before +} + +#[cfg(test)] +#[path = "skin_tests.rs"] +mod tests; diff --git a/crates/doc/src/skin_tests.rs b/crates/doc/src/skin_tests.rs new file mode 100644 index 00000000..d5d3a025 --- /dev/null +++ b/crates/doc/src/skin_tests.rs @@ -0,0 +1,301 @@ +//! Shape armatures: binding, skinning, posing and files (ADR 0071). + +use super::*; +use crate::armature::{Bone, place, pose_at, solve}; +use crate::{ColorEffect, Document, Easing, Keyframe, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Tween, evaluate, evaluate_layer_elements}; +use std::f32::consts::FRAC_PI_2; + +const TAIL: ElementId = ElementId(10); +const B1: BoneId = BoneId(20); +const B2: BoneId = BoneId(21); +const N1: ElementId = ElementId(30); +const N2: ElementId = ElementId(31); + +fn bone(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2) -> Bone { + Bone { id, name: String::new(), parent, child, head, tail, rest: Affine::IDENTITY, limits: None, pinned: false } +} + +/// A tail 200 px long and 20 px thick along y = 0 (anchors every 25 px along both edges), with +/// a cubic tip, drawn at (100, 100) on the stage; two bones along its middle meet at x = 100. +fn outline() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..=8 { + p.line_to(Vec2::new(25.0 * i as f32, -10.0)); + } + p.cubic_to(Vec2::new(215.0, -10.0), Vec2::new(215.0, 10.0), Vec2::new(200.0, 10.0)); + for i in (0..8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + p +} + +fn rig() -> (Armature, Vec>) { + let path = Arc::new(outline()); + let mut arm = Armature { + bones: vec![bone(B1, TAIL, N1, Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)), bone(B2, N1, N2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0))], + skin: Some(Skin::new(TAIL, path.clone())), + }; + rebind(&mut arm); + let shape = Shape { path, ..Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)) }.with_stroke(Rgba::BLACK, 3.0); + let el = Arc::new(Element { id: TAIL, name: String::new(), transform: Affine::translate(100.0, 100.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + (arm, vec![el]) +} + +fn path_of(els: &[Arc]) -> Arc { + match &els[0].kind { + ElementKind::Shape(s) => s.path.clone(), + _ => panic!("not a shape"), + } +} + +fn close(a: Vec2, b: Vec2, tol: f32) -> bool { + a.distance(b) <= tol +} + +/// `p` turned by `a` about `j`. +fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 { + let (s, c) = a.sin_cos(); + let d = p - j; + Vec2::new(j.x + d.x * c - d.y * s, j.y + d.x * s + d.y * c) +} + +#[test] +fn automatic_weights_sum_to_one_and_follow_the_nearest_bone() { + let (arm, _) = rig(); + let skin = arm.skin.as_ref().unwrap(); + let pts = anchors(&skin.rest); + assert_eq!(skin.points.len(), pts.len(), "one binding per anchor"); + for (b, p) in skin.points.iter().zip(&pts) { + let sum: f32 = b.bones.iter().map(|i| i.1).sum(); + assert!((sum - 1.0).abs() < 1e-5, "{p:?}: weights sum to {sum}"); + assert!(b.bones.len() <= MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0)); + } + // Far along each bone an anchor follows it alone; at the joint the two share it equally. + let at = |x: f32| skin.points.iter().zip(&pts).find(|(_, p)| **p == Vec2::new(x, -10.0)).map(|(b, _)| b.clone()).unwrap(); + assert_eq!(at(25.0).bones, vec![Influence(B1, 1.0)]); + assert_eq!(at(175.0).bones, vec![Influence(B2, 1.0)]); + let joint = at(100.0); + assert!((joint.weight(B1) - 0.5).abs() < 1e-5 && (joint.weight(B2) - 0.5).abs() < 1e-5, "{joint:?}"); + // In between the nearer bone weighs more. + let near = at(125.0); + assert!(near.weight(B2) > near.weight(B1) && near.weight(B1) > 0.0, "{near:?}"); +} + +#[test] +fn the_rest_pose_reproduces_the_shape_exactly() { + let (arm, mut els) = rig(); + let drawn = path_of(&els); + // No pose, and a pose that lists every bone at 0. + for pose in [Pose::default(), Pose(vec![crate::JointAngle { bone: B1, angle: 0.0 }, crate::JointAngle { bone: B2, angle: 0.0 }])] { + let rest = deform(&arm, &pose).unwrap(); + assert!(Arc::ptr_eq(&rest, &drawn), "the very path as drawn"); + assert!(!apply(&arm, &mut els, &pose), "nothing changes"); + } + // A pose that turns one bone leaves the anchors only the other bone moves bit for bit. + let mut pose = Pose::default(); + pose.set(B2, 0.7); + let bent = deform(&arm, &pose).unwrap(); + assert_eq!(bent.cmds[1], drawn.cmds[1], "x = 25 follows the first bone only"); + assert_eq!(bent.cmds[0], drawn.cmds[0]); +} + +#[test] +fn a_quarter_bend_turns_bound_points_about_the_joint() { + let (arm, mut els) = rig(); + let drawn = path_of(&els); + let mut pose = Pose::default(); + pose.set(B2, FRAC_PI_2); + assert!(apply(&arm, &mut els, &pose)); + let bent = path_of(&els); + let skin = arm.skin.as_ref().unwrap(); + let joint = Vec2::new(100.0, 0.0); + let (rest, now) = (anchors(&drawn), anchors(&bent)); + for ((b, r), n) in skin.points.iter().zip(&rest).zip(&now) { + let w2 = b.weight(B2); + if w2 == 1.0 { + assert!(close(*n, turned(*r, joint, FRAC_PI_2), 1e-3), "{r:?} → {n:?}"); + } else if w2 == 0.0 { + assert_eq!(n, r, "{r:?} follows the first bone, which didn't turn"); + } else { + // A shared anchor moves part of the way: the blend of rest and the full turn. + let want = *r * (1.0 - w2) + turned(*r, joint, FRAC_PI_2) * w2; + assert!(close(*n, want, 1e-3), "{r:?}: {n:?} vs {want:?}"); + } + } + // The tip (200, ±10) swings down to (90…110, 100), and its cubic handles turn with it. + assert!(close(now[8], Vec2::new(110.0, 100.0), 1e-3), "{:?}", now[8]); + let PathCmd::CubicTo(c1, c2, end) = bent.cmds[9] else { panic!("{:?}", bent.cmds[9]) }; + assert!(close(c1, turned(Vec2::new(215.0, -10.0), joint, FRAC_PI_2), 1e-3)); + assert!(close(c2, turned(Vec2::new(215.0, 10.0), joint, FRAC_PI_2), 1e-3)); + assert!(close(end, Vec2::new(90.0, 100.0), 1e-3)); + // The shape keeps its transform and its stroke's width. + assert_eq!(els[0].transform, Affine::translate(100.0, 100.0)); + let ElementKind::Shape(s) = &els[0].kind else { panic!("not a shape") }; + assert_eq!(s.stroke.as_ref().map(|s| s.width), Some(3.0)); + // Turning the first bone carries the second: the tip goes round the root joint too. + let mut pose = Pose::default(); + pose.set(B1, FRAC_PI_2); + let tip = anchors(&deform(&arm, &pose).unwrap())[8]; + assert!(close(tip, turned(Vec2::new(200.0, -10.0), Vec2::new(0.0, 0.0), FRAC_PI_2), 1e-3), "{tip:?}"); +} + +#[test] +fn joint_nodes_are_placed_by_forward_kinematics() { + let (arm, els) = rig(); + let mut pose = Pose::default(); + pose.set(B2, FRAC_PI_2); + let w = place(&arm, &els, &pose); + // The second bone's end, on the stage: the shape is at (100, 100), the joint at (200, 100). + assert!(close(w[&N2].apply(Vec2::new(200.0, 0.0)), Vec2::new(200.0, 200.0), 1e-3)); + let at = crate::armature::bones_at(&arm, &els, &pose); + assert_eq!(at.len(), 2, "bones of a shape show although their nodes are no elements"); + assert!(close(at[1].head, Vec2::new(200.0, 100.0), 1e-4) && close(at[1].tail, Vec2::new(200.0, 200.0), 1e-3)); + assert_eq!(arm.roots(), vec![TAIL]); +} + +#[test] +fn inverse_kinematics_bends_the_shape() { + let (arm, els) = rig(); + // Drag the tail's end (stage (300, 100)) up to (250, 0): both bones turn. + let target = Vec2::new(250.0, 0.0); + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(200.0, 0.0), target).unwrap(); + assert!(s.error <= 0.01, "{} px off", s.error); + assert_eq!(s.chain, 2); + let tip = place(&arm, &els, &s.pose)[&N2].apply(Vec2::new(200.0, 0.0)); + assert!(close(tip, target, 0.02)); + // The outline's anchors on the bone's end follow it (they're bound to the end bone only). + let mut moved = els.clone(); + apply(&arm, &mut moved, &s.pose); + let tip_anchor = moved[0].transform.apply(anchors(&path_of(&moved))[8]); + assert!(tip_anchor.distance(target) < 11.0, "{tip_anchor:?}"); +} + +fn tail_layer(easing: Easing) -> Layer { + let (arm, els) = rig(); + 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(B2, FRAC_PI_2); + l.keyframes = vec![Arc::new(a), Arc::new(b)]; + l +} + +#[test] +fn poses_tween_the_outline_with_easing() { + let l = tail_layer(Easing::Linear); + let tip = |f: u32| { + let (_, els) = evaluate_layer_elements(&l, f).unwrap(); + anchors(&path_of(&els))[8] + }; + let rest = Vec2::new(200.0, -10.0); + let joint = Vec2::new(100.0, 0.0); + assert_eq!(tip(0), rest, "exact at the first key"); + assert!(close(tip(10), turned(rest, joint, FRAC_PI_2), 1e-3), "exact at the second key"); + // Half way the tip has turned 45°: angles tween, the outline follows (not a straight morph). + assert!(close(tip(5), turned(rest, joint, FRAC_PI_2 * 0.5), 1e-3), "{:?}", tip(5)); + let eased = tail_layer(Easing::QuadIn); + assert!((pose_at(&eased, 5).unwrap().angle(B2) - FRAC_PI_2 * 0.25).abs() < 1e-6); +} + +#[test] +fn every_export_sees_the_bent_shape_and_files_keep_it() { + let mut d = Document::default(); + d.timeline_mut(0).layers = vec![Arc::new(tail_layer(Easing::Linear))]; + d.sanitize(); + let dl = evaluate(&d, 10); + let item = dl.items.iter().find(|i| i.element == TAIL).unwrap(); + let tip = item.transform.apply(anchors(&item.path)[8]); + assert!(close(tip, Vec2::new(210.0, 200.0), 1e-3), "the display list draws the bent tail: {tip:?}"); + let json = serde_json::to_string(&d).unwrap(); + let back: Document = serde_json::from_str(&json).unwrap(); + assert_eq!(back, d); + assert!(back.timeline(0).layers[0].armature.as_ref().unwrap().skin.is_some()); + // The joint nodes' ids are counted, so new ids never collide with them. + assert!(d.next_id > N2.0); + // An armature written before shape armatures reads as one without a skin. + let old: Armature = serde_json::from_str(r#"{"bones": []}"#).unwrap(); + assert!(old.skin.is_none()); + assert!(!serde_json::to_string(&old).unwrap().contains("skin")); +} + +#[test] +fn sanitize_repairs_hostile_skins() { + let (mut arm, _) = rig(); + let skin = arm.skin.as_mut().unwrap(); + skin.points.truncate(3); + skin.points[0] = Binding { bones: vec![Influence(B1, f32::NAN), Influence(BoneId(99), 1.0), Influence(B2, 3.0), Influence(B2, 1.0)], manual: true }; + skin.points[1] = Binding { bones: vec![Influence(B1, -1.0)], manual: false }; + skin.points[2] = Binding { bones: vec![], manual: true }; + assert!(arm.sanitize()); + let skin = arm.skin.as_ref().unwrap(); + assert_eq!(skin.points.len(), anchors(&skin.rest).len(), "one per anchor again"); + assert_eq!(skin.points[0].bones, vec![Influence(B2, 1.0)], "unknown bones, NaN and repeats go; the rest sums to 1"); + assert!(!skin.points[1].bones.is_empty(), "an automatic anchor left with nothing is bound again"); + assert!(skin.points[2].bones.is_empty(), "an anchor unbound by hand stays unbound"); + assert!(!arm.sanitize(), "sanitizing twice changes nothing"); + // A bone that starts somewhere other than the shape, and a shape that is a bone's node. + let (mut arm, _) = rig(); + arm.bones.push(bone(BoneId(40), ElementId(77), ElementId(78), Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))); + arm.sanitize(); + assert_eq!(arm.bones.len(), 2, "every bone of a shape armature hangs from the shape"); + let (mut arm, _) = rig(); + arm.bones.push(bone(BoneId(41), N2, TAIL, Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))); + arm.sanitize(); + assert!(arm.skin.is_none() || arm.bones.iter().all(|b| b.child != TAIL)); +} + +#[test] +fn hand_binding_survives_new_bones() { + let (mut arm, _) = rig(); + let skin = arm.skin.as_mut().unwrap(); + skin.points[1] = Binding { bones: vec![Influence(B2, 1.0)], manual: true }; + skin.points[2] = Binding { bones: vec![], manual: true }; + arm.bones.push(bone(BoneId(22), N2, ElementId(32), Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0))); + rebind(&mut arm); + let skin = arm.skin.as_ref().unwrap(); + assert_eq!(skin.points[1].bones, vec![Influence(B2, 1.0)], "kept as bound by hand"); + assert!(skin.points[2].bones.is_empty(), "kept unbound"); + // Taking its bone away sends a hand-bound anchor back to automatic. + let mut arm = arm.clone(); + arm.bones.retain(|b| b.id != B2 && b.id != BoneId(22)); + rebind(&mut arm); + assert_eq!(arm.skin.as_ref().unwrap().points[1].bones, vec![Influence(B1, 1.0)]); +} + +/// Skinning cost: a shape of 2,000 anchors on 16 bones, posed (debug builds are slower). +#[test] +fn skinning_is_fast() { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..1000 { + p.line_to(Vec2::new(i as f32 * 0.8, -10.0)); + } + for i in (0..1000).rev() { + p.line_to(Vec2::new(i as f32 * 0.8, 10.0)); + } + p.close(); + let mut bones = Vec::new(); + for i in 0..16u64 { + let parent = if i == 0 { TAIL } else { ElementId(100 + i - 1) }; + bones.push(bone(BoneId(200 + i), parent, ElementId(100 + i), Vec2::new(50.0 * i as f32, 0.0), Vec2::new(50.0 * (i + 1) as f32, 0.0))); + } + let mut arm = Armature { bones, skin: Some(Skin::new(TAIL, Arc::new(p))) }; + let t = std::time::Instant::now(); + rebind(&mut arm); + let bind = t.elapsed(); + let pose = Pose(arm.bones.iter().map(|b| crate::JointAngle { bone: b.id, angle: 0.1 }).collect()); + let t = std::time::Instant::now(); + for _ in 0..10 { + std::hint::black_box(deform(&arm, &pose)); + } + let per = t.elapsed() / 10; + println!("2,000 anchors × 16 bones: bind {bind:?}, deform {per:?}"); + assert!(per.as_millis() < 50, "{per:?}"); +} diff --git a/crates/doc/src/sound.rs b/crates/doc/src/sound.rs index da00a9c4..ec7adf7f 100644 --- a/crates/doc/src/sound.rs +++ b/crates/doc/src/sound.rs @@ -445,7 +445,7 @@ fn sounding_symbols(doc: &Document) -> HashSet { if k.sound.is_some() && set.insert(sym.id) { queue.push(sym.id); } - for el in &k.elements { + for el in crate::expand_groups(&k.elements).iter() { if let ElementKind::Symbol { symbol, .. } = &el.kind { shown_in.entry(*symbol).or_default().push(sym.id); } @@ -485,7 +485,8 @@ impl<'a> Layout<'a> { if let Some(fs) = &k.sound { self.sound(fs, k, st, gain); } - for el in &k.elements { + // (A symbol inside a group plays as if it were on the group's layer, ADR 0073.) + for el in crate::expand_groups(&k.elements).iter() { if matches!(&el.kind, ElementKind::Symbol { symbol, .. } if self.sounding.contains(symbol)) { self.instance(layer, k, el, st, gain, depth); } @@ -565,7 +566,7 @@ impl<'a> Layout<'a> { let enters = pa == s0 || (pa == st.l0 && st.enters); self.looped(tl, g, (pa - s0) % len, n, len, enters, gain, depth); } - // Buttons wait for the pointer: their sounds are not in this slice (ADR 0039). + // Buttons sound only under the pointer, in the interactive player (ADR 0057). (SymbolKind::Button, _) => {} } } diff --git a/crates/doc/src/sound_tests.rs b/crates/doc/src/sound_tests.rs index 8e31c35b..8cd0c68a 100644 --- a/crates/doc/src/sound_tests.rs +++ b/crates/doc/src/sound_tests.rs @@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option)], // Pad the symbol's timeline to `len` frames with a second, silent layer. let mut pad = Layer::new(LayerId(11), "pad"); pad.keyframes = vec![Arc::new(Keyframe::new(0, len))]; - d.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); + d.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } })); let mut l = Layer::new(LayerId(1), "outer"); l.keyframes = instances .iter() @@ -347,7 +347,7 @@ fn start_skips_a_playing_sound_and_stop_cuts_it() { fn scenes_play_in_order_guides_are_silent_and_missing_sounds_are_skipped() { let mut d = doc_with(&[(0, 3, with(SoundSync::Event, 1, false))], vec![ramp_sound(7, 100)]); let first = d.scenes[0].clone(); - d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone() })); + d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone(), guides: Vec::new() })); assert_eq!(spans(&voices(&d, 8000)), vec![(VoiceKind::Event, 0, 100), (VoiceKind::Event, 3000, 3100)]); Arc::make_mut(&mut d.timeline_mut(0).layers[0]).kind = LayerKind::Guide; assert_eq!(voices(&d, 8000).len(), 1, "guide layers are not exported, so not heard"); diff --git a/crates/doc/src/swatch.rs b/crates/doc/src/swatch.rs new file mode 100644 index 00000000..53521829 --- /dev/null +++ b/crates/doc/src/swatch.rs @@ -0,0 +1,266 @@ +//! The document's swatches (ADR 0078): saved colours and gradients, as Animate keeps them per +//! document in its Swatches panel. +//! +//! A swatch is a colour (with alpha) or a gradient's ramp and options, never its geometry: a +//! gradient swatch poured on a shape is fitted to it, as a new gradient is. A new document +//! starts with [`default_set`]; a document file that has no swatches (every file before ADR +//! 0078) opens with that set too, and the set is not written while it is unchanged. +//! +//! GIMP palettes (`.gpl`, an open plain-text format) import through [`parse_gpl`]. + +use crate::{GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, is_false, is_zero}; +use serde::{Deserialize, Serialize}; + +/// Most swatches a document keeps (Animate's panel holds a few hundred at most). +pub const MAX_SWATCHES: usize = 1024; +/// Longest swatch name, in characters. +pub const MAX_SWATCH_NAME: usize = 128; + +/// One saved colour or gradient. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Swatch { + /// Shown on hover (empty: the colour's hex). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub name: String, + pub paint: SwatchPaint, +} + +/// What a swatch holds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SwatchPaint { + Solid { + color: Rgba, + }, + Linear { + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + }, + Radial { + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + #[serde(default, skip_serializing_if = "is_zero")] + focal: f32, + }, +} + +impl SwatchPaint { + /// The swatch of a fill: its colour, or its gradient's ramp and options (where it lies is + /// left behind). `None` for a bitmap fill, which a swatch can't hold. + pub fn from_paint(p: &Paint) -> Option { + match p { + Paint::Solid(c) => Some(SwatchPaint::Solid { color: *c }), + Paint::Linear { stops, spread, linear_rgb, .. } => Some(SwatchPaint::Linear { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }), + Paint::Radial { stops, spread, linear_rgb, focal, .. } => Some(SwatchPaint::Radial { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal }), + Paint::Bitmap { .. } => None, + } + } + + /// Its colour, or its gradient's first stop. + pub fn primary_color(&self) -> Rgba { + match self { + SwatchPaint::Solid { color } => *color, + SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color), + } + } + + pub fn stops(&self) -> Option<&[GradientStop]> { + match self { + SwatchPaint::Solid { .. } => None, + SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => Some(stops), + } + } + + pub fn is_gradient(&self) -> bool { + !matches!(self, SwatchPaint::Solid { .. }) + } + + /// The key `paint.set_fill` and swatch files use for its kind. + pub fn kind(&self) -> &'static str { + match self { + SwatchPaint::Solid { .. } => "solid", + SwatchPaint::Linear { .. } => "linear", + SwatchPaint::Radial { .. } => "radial", + } + } + + /// Repaired: colours in range, 2 to [`MAX_GRADIENT_STOPS`] stops in order, the focal point + /// in range. `None` when it can't be (a gradient with fewer than two stops). + pub fn sanitized(&self) -> Option { + let stops = |s: &[GradientStop]| -> Option> { + if s.len() < 2 { + return None; + } + let mut v: Vec = s.iter().take(MAX_GRADIENT_STOPS).map(|g| GradientStop { offset: if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 }, color: g.color.sanitized() }).collect(); + v.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + Some(v) + }; + Some(match self { + SwatchPaint::Solid { color } => SwatchPaint::Solid { color: color.sanitized() }, + SwatchPaint::Linear { stops: s, spread, linear_rgb } => SwatchPaint::Linear { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb }, + SwatchPaint::Radial { stops: s, spread, linear_rgb, focal } => SwatchPaint::Radial { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb, focal: if focal.is_finite() { focal.clamp(-MAX_FOCAL, MAX_FOCAL) } else { 0.0 } }, + }) + } +} + +impl Swatch { + pub fn new(name: &str, paint: SwatchPaint) -> Swatch { + Swatch { name: clean_name(name), paint } + } + pub fn solid(c: Rgba) -> Swatch { + Swatch { name: String::new(), paint: SwatchPaint::Solid { color: c } } + } + /// Repaired (see [`SwatchPaint::sanitized`]), its name trimmed and bounded. + pub fn sanitized(&self) -> Option { + Some(Swatch { name: clean_name(&self.name), paint: self.paint.sanitized()? }) + } +} + +/// A swatch name: one line, trimmed, at most [`MAX_SWATCH_NAME`] characters. +pub fn clean_name(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_SWATCH_NAME).collect::().trim().to_string() +} + +fn stop(offset: f32, rgb: u32) -> GradientStop { + GradientStop { offset, color: Rgba::hex(rgb) } +} + +/// A new document's swatches: greys from black to white, the primaries and secondaries (the +/// picker's web-safe palette has the rest), then seven gradients. +pub fn default_set() -> Vec { + let colours = [0x000000, 0x333333, 0x666666, 0x999999, 0xcccccc, 0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff]; + let mut v: Vec = colours.iter().map(|c| Swatch::solid(Rgba::hex(*c))).collect(); + let linear = |stops| SwatchPaint::Linear { stops, spread: Spread::Pad, linear_rgb: false }; + let radial = |stops| SwatchPaint::Radial { stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0 }; + v.extend([ + Swatch::new("Black to white", linear(vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)])), + Swatch::new("White to black", radial(vec![stop(0.0, 0xffffff), stop(1.0, 0x000000)])), + Swatch::new("Red ball", radial(vec![stop(0.0, 0xff8080), stop(1.0, 0x990000)])), + Swatch::new("Green ball", radial(vec![stop(0.0, 0x80ff80), stop(1.0, 0x006600)])), + Swatch::new("Blue ball", radial(vec![stop(0.0, 0x80b0ff), stop(1.0, 0x000099)])), + Swatch::new("Spectrum", linear(vec![stop(0.0, 0xff0000), stop(0.2, 0xffff00), stop(0.4, 0x00ff00), stop(0.6, 0x00ffff), stop(0.8, 0x0000ff), stop(1.0, 0xff00ff)])), + Swatch::new("Gold", linear(vec![stop(0.0, 0xfff2a8), stop(0.5, 0xd4a017), stop(1.0, 0x7a5200)])), + ]); + v +} + +/// Whether `v` is exactly the default set (then a document file leaves it out). +pub fn is_default_set(v: &[Swatch]) -> bool { + let d = default_set(); + v.len() == d.len() && v.iter().zip(&d).all(|(a, b)| a == b) +} + +/// Largest palette file read, in bytes. +pub const MAX_PALETTE_BYTES: usize = 1 << 20; + +/// Reads a GIMP palette (`.gpl`): a `GIMP Palette` line, optional `Name:` and `Columns:` +/// lines and `#` comments, then one colour per line, `R G B` (0 to 255) and an optional name. +/// Lines that aren't colours are skipped; at most [`MAX_SWATCHES`] colours are read. The +/// palette's own name comes back with the colours. +pub fn parse_gpl(text: &str) -> Result<(String, Vec), String> { + if text.len() > MAX_PALETTE_BYTES { + return Err("the palette file is too large".into()); + } + let mut lines = text.lines(); + let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); + if first != "GIMP Palette" { + return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); + } + let mut name = String::new(); + let mut out = Vec::new(); + for line in lines { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(n) = l.strip_prefix("Name:") { + name = clean_name(n); + continue; + } + if l.starts_with("Columns:") || l.starts_with("Channels:") { + continue; + } + let mut parts = l.split_whitespace(); + let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| f32::from(v) / 255.0); + let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; + let rest: Vec<&str> = parts.collect(); + let label = rest.join(" "); + // GIMP names unnamed colours "Untitled"; the hex says more. + let label = if label == "Untitled" { String::new() } else { label }; + out.push(Swatch::new(&label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) })); + if out.len() >= MAX_SWATCHES { + break; + } + } + if out.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok((name, out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_set_is_valid_and_recognised() { + let d = default_set(); + assert_eq!(d.len(), 19); + assert!(is_default_set(&d)); + assert!(d.iter().all(|s| s.sanitized().as_ref() == Some(s)), "nothing to repair"); + assert_eq!(d.iter().filter(|s| s.paint.is_gradient()).count(), 7); + let mut other = d.clone(); + other.swap(0, 1); + assert!(!is_default_set(&other)); + assert!(!is_default_set(&[])); + } + + #[test] + fn swatches_are_repaired() { + let bad = Swatch { name: " a\nb ".into(), paint: SwatchPaint::Radial { stops: vec![GradientStop { offset: 2.0, color: Rgba::new(f32::NAN, 9.0, -1.0, 1.0) }, GradientStop { offset: -1.0, color: Rgba::WHITE }], spread: Spread::Pad, linear_rgb: false, focal: 5.0 } }; + let s = bad.sanitized().unwrap(); + assert_eq!(s.name, "ab"); + let SwatchPaint::Radial { stops, focal, .. } = &s.paint else { panic!() }; + assert_eq!((stops[0].offset, stops[1].offset), (0.0, 1.0), "in order and in range"); + assert_eq!(stops[1].color, Rgba::new(0.0, 1.0, 0.0, 1.0)); + assert_eq!(*focal, MAX_FOCAL); + let one = Swatch { name: String::new(), paint: SwatchPaint::Linear { stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }], spread: Spread::Pad, linear_rgb: false } }; + assert!(one.sanitized().is_none(), "a gradient needs two stops"); + assert_eq!(clean_name(&"x".repeat(500)).chars().count(), MAX_SWATCH_NAME); + } + + #[test] + fn a_swatch_keeps_a_fills_ramp_not_its_geometry() { + let p = Paint::linear(crate::Vec2::new(5.0, 5.0), crate::Vec2::new(50.0, 5.0), vec![stop(0.0, 0xff0000), stop(1.0, 0x0000ff)]); + let s = SwatchPaint::from_paint(&p).unwrap(); + assert_eq!(s.kind(), "linear"); + assert_eq!(s.primary_color(), Rgba::hex(0xff0000)); + assert!(SwatchPaint::from_paint(&Paint::Bitmap { bitmap: crate::BitmapId(1), repeat: true, matrix: crate::Affine::IDENTITY }).is_none()); + } + + #[test] + fn gimp_palettes_are_read() { + let text = "GIMP Palette\nName: Brand\nColumns: 4\n# a comment\n255 0 0\tCrimson red\n 0 128 255 Untitled\n300 0 0 too bright\nnot a colour\n\n10 20 30\n"; + let (name, sw) = parse_gpl(text).unwrap(); + assert_eq!(name, "Brand"); + assert_eq!(sw.len(), 3); + assert_eq!(sw[0].name, "Crimson red"); + assert_eq!(sw[0].paint, SwatchPaint::Solid { color: Rgba::hex(0xff0000) }); + assert_eq!(sw[1].name, "", "GIMP's Untitled shows as the hex"); + assert_eq!(sw[2].paint.primary_color().to_hex(), "#0a141e"); + // A byte-order mark and Windows line ends are fine. + assert!(parse_gpl("\u{feff}GIMP Palette\r\n1 2 3\r\n").is_ok()); + for bad in ["", "JASC-PAL\n0 0 0", "GIMP Palette\nName: empty\n", "GIMP Palette\n1 2\n"] { + assert!(parse_gpl(bad).is_err(), "{bad:?}"); + } + let many = format!("GIMP Palette\n{}", "1 2 3\n".repeat(MAX_SWATCHES + 10)); + assert_eq!(parse_gpl(&many).unwrap().1.len(), MAX_SWATCHES, "bounded"); + assert!(parse_gpl(&"x".repeat(MAX_PALETTE_BYTES + 1)).is_err()); + } +} diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs new file mode 100644 index 00000000..988308f2 --- /dev/null +++ b/crates/doc/src/templates.rs @@ -0,0 +1,329 @@ +//! The templates AniCraft ships with (ADR 0065): small documents built by code, so nothing +//! binary is committed and every line of them is original work. Each sets up a stage size and +//! frame rate, named layers ready to draw on, and guides on a locked guide layer (shown while +//! editing, never in output). They open as new, untitled documents (`file.new_from_template`). + +use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Path, Vec2}; +use std::sync::Arc; + +/// A built-in template: its id (for commands), name and category (English; the shell +/// translates them where they are drawn), what it is for, and how it is built. +pub struct Template { + pub id: &'static str, + pub name: &'static str, + pub category: &'static str, + pub description: &'static str, + pub build: fn() -> Document, +} + +/// Every built-in template, in the order the start screen shows them. +pub static TEMPLATES: [Template; 6] = [ + Template { id: "banner-728x90", name: "Leaderboard banner", category: "Advertising", description: "A 728 × 90 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_728x90 }, + Template { id: "banner-300x250", name: "Rectangle banner", category: "Advertising", description: "A 300 × 250 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_300x250 }, + Template { id: "social-square", name: "Social square", category: "Social", description: "A 1080 × 1080 post at 30 fps, 15 seconds long, with a safe margin and thirds on a guide layer", build: social_square }, + Template { id: "storyboard", name: "Storyboard 16:9", category: "Storyboard", description: "Six 2-second panels at 1920 × 1080, labelled Panel 1 to 6, with action- and title-safe areas", build: storyboard }, + Template { id: "character-turnaround", name: "Character turnaround", category: "Character", description: "Front, three-quarter, side and back views side by side, on head-height guides eight heads tall", build: turnaround }, + Template { id: "lip-sync", name: "Lip-sync mouth chart", category: "Character", description: "A Mouth graphic symbol with ten labelled mouth shapes to redraw, placed on a face guide", build: lip_sync }, +]; + +/// The built-in template with this id. +pub fn find(id: &str) -> Option<&'static Template> { + TEMPLATES.iter().find(|t| t.id == id) +} + +/// The colour guides are drawn in (the guide layer's colour too, so the stage shows them alike). +const GUIDE: u32 = 0x4fa3ff; +/// A second, quieter guide colour for secondary lines. +const GUIDE_SOFT: u32 = 0x9cc8ff; + +fn blank(width: u32, height: u32, fps: f32) -> Document { + let mut d = Document { stage: Stage { width, height, fps, background: Rgba::WHITE }, ..Document::default() }; + d.timeline_mut(0).layers.clear(); + d +} + +fn element(d: &mut Document, name: &str, transform: Affine, shape: Shape) -> Arc { + Arc::new(Element { id: ElementId(d.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }) +} + +/// A stroked line from `a` to `b`. +fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, width: f32) -> Arc { + let mut p = Path::new(); + p.move_to(Vec2::new(a.0, a.1)).line_to(Vec2::new(b.0, b.1)); + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None }) +} + +/// A stroked rectangle outline, `(x, y, w, h)`. +fn outline(d: &mut Document, name: &str, (x, y, w, h): (f32, f32, f32, f32), color: u32, width: f32) -> Arc { + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None }) +} + +/// A layer holding `elements` in one keyframe `frames` long. +fn layer(d: &mut Document, name: &str, kind: LayerKind, color: u32, frames: u32, elements: Vec>) -> Arc { + let mut l = Layer::new(LayerId(d.alloc_id()), name); + l.kind = kind; + l.color = Rgba::hex(color); + // Guides stay put while drawing over them. + l.locked = kind == LayerKind::Guide; + let mut k = Keyframe::new(0, frames.max(1)); + k.elements = elements; + l.keyframes = vec![Arc::new(k)]; + Arc::new(l) +} + +/// Drawing layers, empty, top first. +fn drawing_layers(d: &mut Document, names: &[&str], frames: u32) -> Vec> { + let palette = [0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; + names.iter().enumerate().map(|(i, n)| layer(d, n, LayerKind::Normal, palette[i % palette.len()], frames, Vec::new())).collect() +} + +/// A banner: the safe area (inset by a tenth of the short edge) and the edge on a guide layer, +/// layers for the call to action, text and artwork, and a soft background. +fn banner(width: u32, height: u32) -> Document { + const FRAMES: u32 = 24 * 15; + let mut d = blank(width, height, 24.0); + let (w, h) = (width as f32, height as f32); + let m = (w.min(h) * 0.1).round(); + let guides = vec![outline(&mut d, "Safe area", (m, m, w - 2.0 * m, h - 2.0 * m), GUIDE, 1.0), outline(&mut d, "Edge", (0.5, 0.5, w - 1.0, h - 1.0), GUIDE_SOFT, 1.0)]; + let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)]; + layers.extend(drawing_layers(&mut d, &["Call to action", "Text", "Artwork"], FRAMES)); + let bg = element(&mut d, "background", Affine::IDENTITY, Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::hex(0xeef2f7)))); + let mut back = layer(&mut d, "Background", LayerKind::Normal, 0x7e57c2, FRAMES, vec![bg]); + Arc::make_mut(&mut back).locked = true; + layers.push(back); + d.timeline_mut(0).layers = layers; + d +} + +fn banner_728x90() -> Document { + banner(728, 90) +} + +fn banner_300x250() -> Document { + banner(300, 250) +} + +/// A square post: a safe margin, the thirds and the centre on a guide layer. +fn social_square() -> Document { + const FRAMES: u32 = 30 * 15; + let mut d = blank(1080, 1080, 30.0); + let s = 1080.0; + let m = 60.0; + let mut guides = vec![outline(&mut d, "Safe margin", (m, m, s - 2.0 * m, s - 2.0 * m), GUIDE, 2.0)]; + for (i, t) in [s / 3.0, s * 2.0 / 3.0].into_iter().enumerate() { + guides.push(line(&mut d, &format!("Third {}", i + 1), (t, 0.0), (t, s), GUIDE_SOFT, 1.0)); + guides.push(line(&mut d, &format!("Third {}", i + 3), (0.0, t), (s, t), GUIDE_SOFT, 1.0)); + } + guides.push(line(&mut d, "Centre", (s / 2.0 - 20.0, s / 2.0), (s / 2.0 + 20.0, s / 2.0), GUIDE, 2.0)); + guides.push(line(&mut d, "Centre", (s / 2.0, s / 2.0 - 20.0), (s / 2.0, s / 2.0 + 20.0), GUIDE, 2.0)); + let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)]; + layers.extend(drawing_layers(&mut d, &["Text", "Artwork", "Background"], FRAMES)); + d.timeline_mut(0).layers = layers; + d +} + +/// A storyboard for 16:9: the action-safe (93 %) and title-safe (90 %) areas and the centre on a +/// guide layer, and a Panels layer of six labelled 2-second keyframes (an animatic as it plays). +fn storyboard() -> Document { + const PANEL: u32 = 48; + const PANELS: u32 = 6; + let mut d = blank(1920, 1080, 24.0); + let (w, h) = (1920.0, 1080.0); + let safe = |d: &mut Document, name: &str, keep: f32, color: u32| { + let (mx, my) = (w * (1.0 - keep) / 2.0, h * (1.0 - keep) / 2.0); + outline(d, name, (mx, my, w - 2.0 * mx, h - 2.0 * my), color, 2.0) + }; + let guides = vec![ + safe(&mut d, "Action safe", 0.93, GUIDE), + safe(&mut d, "Title safe", 0.90, GUIDE_SOFT), + line(&mut d, "Centre", (w / 2.0 - 30.0, h / 2.0), (w / 2.0 + 30.0, h / 2.0), GUIDE, 2.0), + line(&mut d, "Centre", (w / 2.0, h / 2.0 - 30.0), (w / 2.0, h / 2.0 + 30.0), GUIDE, 2.0), + ]; + let total = PANEL * PANELS; + let guide = layer(&mut d, "Safe areas", LayerKind::Guide, GUIDE, total, guides); + let notes = layer(&mut d, "Notes", LayerKind::Normal, 0xffd54a, total, Vec::new()); + let mut panels = Layer::new(LayerId(d.alloc_id()), "Panels"); + panels.color = Rgba::hex(0xff6b4a); + panels.keyframes = (0..PANELS) + .map(|i| { + let mut k = Keyframe::new(i * PANEL, PANEL); + k.label = format!("Panel {}", i + 1); + Arc::new(k) + }) + .collect(); + d.timeline_mut(0).layers = vec![guide, notes, Arc::new(panels)]; + d +} + +/// A turnaround: five views side by side (a centre line each) on horizontal lines a head +/// apart, eight heads from the top of the head to the ground, and a layer per view. +fn turnaround() -> Document { + let mut d = blank(1920, 1080, 24.0); + let (left, right, top, ground) = (60.0, 1860.0, 120.0, 960.0); + let head = (ground - top) / 8.0; + let mut guides = Vec::new(); + for i in 0..=8 { + let y = top + head * i as f32; + let (color, width) = if i == 0 || i == 8 { (GUIDE, 2.0) } else { (GUIDE_SOFT, 1.0) }; + let name = match i { + 0 => "Top of head".to_string(), + 8 => "Ground".to_string(), + n => format!("Head {n}"), + }; + guides.push(line(&mut d, &name, (left, y), (right, y), color, width)); + } + let views = ["Front", "Three-quarter", "Side", "Three-quarter back", "Back"]; + let col = (right - left) / views.len() as f32; + for (i, v) in views.iter().enumerate() { + let x = left + col * (i as f32 + 0.5); + guides.push(line(&mut d, v, (x, top - 30.0), (x, ground + 30.0), GUIDE, 1.5)); + } + let mut layers = vec![layer(&mut d, "Turnaround guides", LayerKind::Guide, GUIDE, 1, guides)]; + layers.extend(drawing_layers(&mut d, &views, 1)); + d.timeline_mut(0).layers = layers; + d +} + +/// The mouth shapes of a lip-sync chart, as frame labels and placeholder shapes to redraw. +pub const MOUTHS: [&str; 10] = ["Rest", "AI", "E", "O", "U", "CDGKNRSThYZ", "FV", "L", "MBP", "WQ"]; + +/// A lip-sync chart: a Mouth graphic symbol with a labelled keyframe per mouth shape (each with +/// a simple placeholder), placed at Single Frame on a face guide, so each keyframe of the Mouth +/// layer picks a shape by its first frame. +fn lip_sync() -> Document { + const FRAMES: u32 = 24; + let mut d = blank(1280, 720, 24.0); + let lips = Rgba::hex(0x8e3b46); + let mouth = |path: Path| Shape::filled(path, Paint::Solid(lips)).with_stroke(Rgba::hex(0x5a1f28), 3.0); + let shapes = [ + mouth(Path::rounded_rect(-50.0, -4.0, 100.0, 8.0, 4.0)), + mouth(Path::ellipse(0.0, 0.0, 55.0, 35.0)), + mouth(Path::ellipse(0.0, 0.0, 60.0, 20.0)), + mouth(Path::ellipse(0.0, 0.0, 35.0, 40.0)), + mouth(Path::ellipse(0.0, 0.0, 22.0, 26.0)), + mouth(Path::rounded_rect(-55.0, -14.0, 110.0, 28.0, 12.0)), + mouth(Path::rounded_rect(-50.0, -10.0, 100.0, 20.0, 8.0)), + mouth(Path::ellipse(0.0, 0.0, 45.0, 30.0)), + mouth(Path::rounded_rect(-50.0, -3.0, 100.0, 6.0, 3.0)), + mouth(Path::ellipse(0.0, 0.0, 18.0, 20.0)), + ]; + let sym_id = SymbolId(d.alloc_id()); + let mut inner = Layer::new(LayerId(d.alloc_id()), "Mouth"); + inner.color = Rgba::hex(0xff6b4a); + let mut keys = Vec::with_capacity(shapes.len()); + for (i, (label, shape)) in MOUTHS.iter().zip(shapes).enumerate() { + let mut k = Keyframe::new(i as u32, 1); + k.label = (*label).to_string(); + k.elements = vec![element(&mut d, &format!("{label} mouth"), Affine::IDENTITY, shape)]; + keys.push(Arc::new(k)); + } + inner.keyframes = keys; + d.library.push(Arc::new(Symbol { id: sym_id, name: "Mouth".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + let (cx, cy) = (640.0, 340.0); + let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false, warp: None }); + let guides = vec![ + face, + line(&mut d, "Eye line", (cx - 200.0, cy), (cx + 200.0, cy), GUIDE_SOFT, 1.0), + line(&mut d, "Centre line", (cx, cy - 250.0), (cx, cy + 250.0), GUIDE_SOFT, 1.0), + line(&mut d, "Mouth line", (cx - 120.0, cy + 130.0), (cx + 120.0, cy + 130.0), GUIDE_SOFT, 1.0), + ]; + let instance = Arc::new(Element { + id: ElementId(d.alloc_id()), + name: "mouth".into(), + transform: Affine::translate(cx, cy + 130.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, + }); + let layers = vec![ + layer(&mut d, "Face guide", LayerKind::Guide, GUIDE, FRAMES, guides), + layer(&mut d, "Mouth", LayerKind::Normal, 0xff6b4a, FRAMES, vec![instance]), + layer(&mut d, "Head", LayerKind::Normal, 0x66bb6a, FRAMES, Vec::new()), + ]; + d.timeline_mut(0).layers = layers; + d +} + +/// A copy of `doc` with its guide layers drawn as artwork, their lines `widen` times as wide: a +/// template's picture shows its guides (which output never does), and a small picture needs +/// them wider to see them. +pub fn with_guides_shown(doc: &Document, widen: f32) -> Document { + let widen = if widen.is_finite() { widen.clamp(1.0, 16.0) } else { 1.0 }; + let show = |tl: &mut Timeline| { + for l in &mut tl.layers { + if l.kind != LayerKind::Guide { + continue; + } + let l = Arc::make_mut(l); + l.kind = LayerKind::Normal; + for k in &mut l.keyframes { + for e in &mut Arc::make_mut(k).elements { + if let ElementKind::Shape(sh) = &e.kind + && let Some(st) = &sh.stroke + { + let mut sh = sh.clone(); + sh.stroke = Some(Stroke { width: st.width * widen, ..st.clone() }); + Arc::make_mut(e).kind = ElementKind::Shape(sh); + } + } + } + } + }; + let mut d = doc.clone(); + for scene in &mut d.scenes { + show(&mut Arc::make_mut(scene).timeline); + } + for sym in &mut d.library { + show(&mut Arc::make_mut(sym).timeline); + } + d +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_template_builds_a_consistent_document() { + let mut ids = std::collections::HashSet::new(); + for t in &TEMPLATES { + assert!(ids.insert(t.id), "{} is listed once", t.id); + assert!(find(t.id).is_some_and(|f| std::ptr::eq(f, t))); + let d = (t.build)(); + assert!(d.stage.width > 0 && d.stage.height > 0 && d.stage.fps > 0.0, "{}", t.id); + let tl = d.timeline(0); + assert!(tl.layers.len() >= 3, "{}: named layers to draw on", t.id); + assert!(tl.layers.iter().any(|l| l.kind == LayerKind::Guide && l.locked), "{}: a locked guide layer", t.id); + // Ids are unique and below `next_id`, so editing never reuses one. + let mut seen = std::collections::HashSet::new(); + let mut check = |id: u64| assert!(id < d.next_id && seen.insert(id), "{}: id {id}", t.id); + for l in &tl.layers { + check(l.id.0); + l.keyframes.iter().flat_map(|k| k.elements.iter()).for_each(|e| check(e.id.0)); + } + for s in &d.library { + check(s.id.0); + } + // Guides never render; the picture with them shown is not blank. + assert!(crate::evaluate(&d, 0).items.iter().all(|i| i.guide || tl.layer(i.layer).is_some_and(|l| l.kind != LayerKind::Guide))); + assert!(crate::evaluate(&with_guides_shown(&d, 4.0), 0).items.iter().any(|i| !i.guide), "{}", t.id); + } + // The sizes the task asks for. + let size = |id: &str| find(id).map(|t| (t.build)().stage).map(|s| (s.width, s.height, s.fps)); + assert_eq!(size("banner-728x90"), Some((728, 90, 24.0))); + assert_eq!(size("banner-300x250"), Some((300, 250, 24.0))); + assert_eq!(size("social-square"), Some((1080, 1080, 30.0))); + assert_eq!(size("storyboard"), Some((1920, 1080, 24.0))); + } + + #[test] + fn the_storyboard_and_mouth_chart_are_labelled() { + let d = storyboard(); + let panels = d.timeline(0).layers.iter().find(|l| l.name == "Panels").map(|l| l.keyframes.iter().map(|k| k.label.clone()).collect::>()); + assert_eq!(panels.map(|p| p.len()), Some(6)); + assert_eq!(d.timeline(0).frame_count(), 6 * 48); + let d = lip_sync(); + let labels: Vec = d.library.first().map(|s| s.timeline.layers.iter().flat_map(|l| l.keyframes.iter().map(|k| k.label.clone())).collect()).unwrap_or_default(); + assert_eq!(labels, MOUTHS.map(str::to_string).to_vec()); + } +} diff --git a/crates/doc/src/warp.rs b/crates/doc/src/warp.rs new file mode 100644 index 00000000..61a11805 --- /dev/null +++ b/crates/doc/src/warp.rs @@ -0,0 +1,641 @@ +//! Asset Warp (ADR 0079): a deformation mesh over a shape or a bitmap, bent by pins. +//! +//! A [`Warp`] sits on a [`Shape`] (a bitmap on the stage is a shape filled with its image). It +//! keeps the artwork's outline as it was drawn (`rest`), a mesh **resolution**, and the +//! **pins**: each a point of the artwork as drawn (`rest`) and where it is now (`at`), both in +//! the shape's own space. The mesh is not stored: it is a grid over the rest outline's bounds, +//! `resolution` cells along the longer side (square-ish cells, each split into two triangles, +//! the diagonals alternating so the grid has no preferred direction), so it is always the same +//! for the same artwork. +//! +//! **Deformation** is the rigid moving-least-squares deformation of S. Schaefer, T. McPhail and +//! J. Warren, *Image deformation using moving least squares* (SIGGRAPH 2006, §2.3), evaluated at +//! the mesh's vertices: each vertex `v` moves by the rotation and translation that best carry +//! the pins near it (weighted `1 / |p − v|²`) to where they are. It interpolates the pins +//! exactly, is as rigid as possible locally (no shear, no scale), is a closed form per vertex +//! (no solver, no iterations, nothing to converge), and depends only on the pins, so it is +//! deterministic and its cost is bounded: vertices × pins. Between vertices the mesh is +//! piecewise affine, so a bitmap is drawn as textured triangles and a shape's outline maps +//! through the same triangles: the shape and the bitmap bend the same way. +//! +//! **The outline.** Straight edges are split where they cross the mesh's edges, so a line +//! maps exactly to the mesh's image of it (a bitmap's outline is exactly the mesh's border). +//! Curves are split into pieces no longer than half a cell, each end mapped through the mesh +//! and each handle by the triangle of the end it belongs to, so curves stay smooth. **At rest** +//! (every pin where it was placed) the outline is the drawing, bit for bit: the very `Arc` of +//! the rest path. +//! +//! **The file holds what shows.** Commands write the bent outline into the shape's `path` and +//! its fingerprint into `shown`. A shape whose path no longer has that fingerprint was edited +//! by another tool since: its warp is stale, [`Shape::live_warp`] ignores it, and the next warp +//! command starts again from the shape as it now is ([`Warp::rebased`]). Pins tween between +//! keyframes with the keyframe's easing (as bone poses do, ADR 0043): `evaluate` blends the +//! pins and bends the rest outline, so a tween never accumulates drift. + +use crate::Shape; +use anicraft_geom::{Path, PathCmd, Vec2}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Fewest and most cells along the mesh's longer side, and the resolution a new warp has. +pub const MIN_RESOLUTION: u32 = 2; +pub const MAX_RESOLUTION: u32 = 48; +pub const DEFAULT_RESOLUTION: u32 = 12; +/// Most pins on one warp. +pub const MAX_PINS: usize = 128; +/// Most anchors a warped outline may have (Optimize first beyond it). +pub const MAX_WARP_POINTS: usize = 20_000; +/// Most commands a bent outline may have; past it curves and lines are not split. +const MAX_BENT_CMDS: usize = 400_000; +/// Most pieces one curve is split into. +const MAX_SPLIT: usize = 32; +/// Largest artwork a warp covers (local units on either side). +pub const MAX_EXTENT: f32 = 1_000_000.0; +/// Two pins closer than this (local units, as drawn) are one place. +pub const PIN_SPACING: f32 = 0.5; + +/// Unique id of a pin within a document (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct PinId(pub u64); + +/// A pin: a point of the artwork as drawn, and where it is now (the shape's space). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Pin { + pub id: PinId, + pub rest: Vec2, + pub at: Vec2, +} + +fn default_resolution() -> u32 { + DEFAULT_RESOLUTION +} + +/// A warp mesh on a shape (see the module docs). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Warp { + /// The outline as it was drawn, in the shape's space. + #[serde(with = "crate::path_table")] + pub rest: Arc, + /// Cells along the mesh's longer side ([`MIN_RESOLUTION`]..=[`MAX_RESOLUTION`]). + #[serde(default = "default_resolution")] + pub resolution: u32, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pins: Vec, + /// Fingerprint of the outline the warp gave the shape ([`fingerprint`]). + #[serde(default)] + pub shown: u64, +} + +impl PartialEq for Warp { + fn eq(&self, o: &Warp) -> bool { + crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution && self.pins == o.pins && self.shown == o.shown + } +} + +/// The deformation mesh as drawn: every vertex as drawn (`rest`) and bent (`shown`), and the +/// triangles (indices into both), in the shape's space, in drawing order. +#[derive(Clone, Debug, PartialEq)] +pub struct WarpMesh { + pub rest: Vec, + pub shown: Vec, + pub tris: Vec<[u32; 3]>, +} + +/// The mesh's grid: `nx × ny` cells from `min` to `max`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Grid { + pub min: Vec2, + pub max: Vec2, + pub nx: u32, + pub ny: u32, +} + +impl Grid { + /// The grid over `rest`'s control-point bounds with `resolution` cells along the longer side + /// (an extent under 1 unit is widened to 1, about its middle). `None` for an empty or + /// unbounded outline. + pub fn of(rest: &Path, resolution: u32) -> Option { + let b = rest.bounds(); + if !(b.min.is_finite() && b.max.is_finite()) || b.max.x < b.min.x || b.max.y < b.min.y { + return None; + } + if b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT { + return None; + } + let widen = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) }; + let (x0, x1) = widen(b.min.x, b.max.x); + let (y0, y1) = widen(b.min.y, b.max.y); + let (w, h) = (x1 - x0, y1 - y0); + let r = resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION); + let size = w.max(h) / r as f32; + let cells = |len: f32| { + let n = (len / size).ceil(); + if n.is_finite() { (n as u32).clamp(1, r) } else { 1 } + }; + Some(Grid { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1), nx: cells(w), ny: cells(h) }) + } + + /// The x of column line `i` (exactly the bounds at either end). + pub fn x(&self, i: u32) -> f32 { + if i >= self.nx { self.max.x } else { self.min.x + (self.max.x - self.min.x) * i as f32 / self.nx as f32 } + } + + /// The y of row line `j`. + pub fn y(&self, j: u32) -> f32 { + if j >= self.ny { self.max.y } else { self.min.y + (self.max.y - self.min.y) * j as f32 / self.ny as f32 } + } + + /// Vertices, row by row: `(nx + 1) × (ny + 1)`. + pub fn vertices(&self) -> Vec { + let mut out = Vec::with_capacity(((self.nx + 1) * (self.ny + 1)) as usize); + for j in 0..=self.ny { + for i in 0..=self.nx { + out.push(Vec2::new(self.x(i), self.y(j))); + } + } + out + } + + fn vertex(&self, i: u32, j: u32) -> u32 { + j * (self.nx + 1) + i + } + + /// Whether cell `(i, j)`'s diagonal runs from its top-left to its bottom-right corner (else + /// from its top-right to its bottom-left): they alternate like a chequerboard. + fn falling(i: u32, j: u32) -> bool { + (i + j).is_multiple_of(2) + } + + /// The two triangles of cell `(i, j)`, as vertex indices. + fn cell_tris(&self, i: u32, j: u32) -> [[u32; 3]; 2] { + let (a, b, c, d) = (self.vertex(i, j), self.vertex(i + 1, j), self.vertex(i, j + 1), self.vertex(i + 1, j + 1)); + if Grid::falling(i, j) { [[a, b, d], [a, d, c]] } else { [[a, b, c], [b, d, c]] } + } + + /// Every triangle, cell by cell, row by row. + pub fn triangles(&self) -> Vec<[u32; 3]> { + let mut out = Vec::with_capacity((2 * self.nx * self.ny) as usize); + for j in 0..self.ny { + for i in 0..self.nx { + out.extend(self.cell_tris(i, j)); + } + } + out + } + + /// The cell `p` falls in (clamped to the grid, so points just outside use the edge cells). + fn cell(&self, p: Vec2) -> (u32, u32) { + let at = |v: f32, lo: f32, hi: f32, n: u32| { + let k = ((v - lo) / (hi - lo) * n as f32).floor(); + if k.is_finite() { (k.max(0.0) as u32).min(n - 1) } else { 0 } + }; + (at(p.x, self.min.x, self.max.x, self.nx), at(p.y, self.min.y, self.max.y, self.ny)) + } + + /// The triangle (vertex indices) of the grid that holds `p`. + pub fn locate(&self, p: Vec2) -> [u32; 3] { + let (i, j) = self.cell(p); + let [t0, t1] = self.cell_tris(i, j); + let (x0, y0) = (self.x(i), self.y(j)); + let (cw, ch) = ((self.x(i + 1) - x0).max(1e-12), (self.y(j + 1) - y0).max(1e-12)); + let (u, v) = ((p.x - x0) / cw, (p.y - y0) / ch); + let first = if Grid::falling(i, j) { u >= v } else { u + v <= 1.0 }; + if first { t0 } else { t1 } + } + + /// The parameters in `(0, 1)` where the segment `a → b` crosses an edge of the mesh, in + /// order: column and row lines, then each cell's diagonal. + fn crossings(&self, a: Vec2, b: Vec2, out: &mut Vec) { + out.clear(); + let d = b - a; + if d.x != 0.0 { + for i in 1..self.nx { + let t = (self.x(i) - a.x) / d.x; + if t > 0.0 && t < 1.0 { + out.push(t); + } + } + } + if d.y != 0.0 { + for j in 1..self.ny { + let t = (self.y(j) - a.y) / d.y; + if t > 0.0 && t < 1.0 { + out.push(t); + } + } + } + out.sort_by(f32::total_cmp); + out.dedup_by(|x, y| (*x - *y).abs() < 1e-6); + // Inside each cell the segment may still cross the cell's diagonal. + let mut diag = Vec::new(); + let mut t0 = 0.0f32; + for &t1 in out.iter().chain(std::iter::once(&1.0)) { + let mid = a + d * ((t0 + t1) * 0.5); + let (i, j) = self.cell(mid); + let (p, q) = if Grid::falling(i, j) { (Vec2::new(self.x(i), self.y(j)), Vec2::new(self.x(i + 1), self.y(j + 1))) } else { (Vec2::new(self.x(i + 1), self.y(j)), Vec2::new(self.x(i), self.y(j + 1))) }; + let e = q - p; + let den = d.cross(e); + if den.abs() > 1e-12 { + let t = (p - a).cross(e) / den; + if t > t0 + 1e-6 && t < t1 - 1e-6 { + diag.push(t); + } + } + t0 = t1; + } + out.extend(diag); + out.sort_by(f32::total_cmp); + } +} + +/// Barycentric coordinates of `p` in triangle `(a, b, c)` (extrapolated outside it); `None` for +/// a triangle with no area. +fn barycentric(a: Vec2, b: Vec2, c: Vec2, p: Vec2) -> Option<(f32, f32, f32)> { + let det = (b - a).cross(c - a); + if det.abs() <= 1e-12 || det.is_nan() { + return None; + } + let l1 = (p - a).cross(c - a) / det; + let l2 = (b - a).cross(p - a) / det; + Some((1.0 - l1 - l2, l1, l2)) +} + +/// The rigid moving-least-squares deformation (Schaefer et al. 2006, §2.3) of `v` by pins +/// `(from, to)`, with weights `1 / |from − v|²`: the rotation and translation that best carry +/// the pins near `v` where they go, applied to `v`. A point on a pin goes with it; with one pin +/// everything moves with it; with none nothing moves. Computed in `f64`. +pub fn mls_rigid(pins: &[(Vec2, Vec2)], v: Vec2) -> Vec2 { + if pins.is_empty() { + return v; + } + let (vx, vy) = (f64::from(v.x), f64::from(v.y)); + let (mut sw, mut px, mut py, mut qx, mut qy) = (0.0f64, 0.0, 0.0, 0.0, 0.0); + let mut ws = Vec::with_capacity(pins.len()); + for &(p, q) in pins { + let (dx, dy) = (f64::from(p.x) - vx, f64::from(p.y) - vy); + let d2 = dx * dx + dy * dy; + if d2 < 1e-12 { + return q; + } + let w = 1.0 / d2; + ws.push(w); + sw += w; + px += w * f64::from(p.x); + py += w * f64::from(p.y); + qx += w * f64::from(q.x); + qy += w * f64::from(q.y); + } + if !(sw > 0.0 && sw.is_finite()) { + return v; + } + let (px, py, qx, qy) = (px / sw, py / sw, qx / sw, qy / sw); + // The best rotation: its cosine and sine are the weighted dot and cross of the centred pins. + let (mut dot, mut cross) = (0.0f64, 0.0f64); + for (&(p, q), &w) in pins.iter().zip(&ws) { + let (ax, ay) = (f64::from(p.x) - px, f64::from(p.y) - py); + let (bx, by) = (f64::from(q.x) - qx, f64::from(q.y) - qy); + dot += w * (ax * bx + ay * by); + cross += w * (ax * by - ay * bx); + } + let r = dot.hypot(cross); + let (c, s) = if r > 1e-18 && r.is_finite() { (dot / r, cross / r) } else { (1.0, 0.0) }; + let (dx, dy) = (vx - px, vy - py); + let out = Vec2::new((qx + c * dx - s * dy) as f32, (qy + s * dx + c * dy) as f32); + if out.is_finite() { out } else { v } +} + +/// A fingerprint of `path`'s commands and coordinates (FNV-1a over their bits): how a warp +/// knows the outline is still the one it gave the shape. +pub fn fingerprint(path: &Path) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut eat = |bits: u32| { + for b in bits.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + for c in &path.cmds { + let (tag, pts): (u32, [Option; 3]) = match *c { + PathCmd::MoveTo(p) => (1, [Some(p), None, None]), + PathCmd::LineTo(p) => (2, [Some(p), None, None]), + PathCmd::QuadTo(a, p) => (3, [Some(a), Some(p), None]), + PathCmd::CubicTo(a, b, p) => (4, [Some(a), Some(b), Some(p)]), + PathCmd::Close => (5, [None, None, None]), + }; + eat(tag); + for p in pts.into_iter().flatten() { + eat(p.x.to_bits()); + eat(p.y.to_bits()); + } + } + h +} + +/// How many anchors (command ends) `path` has. +pub fn anchor_count(path: &Path) -> usize { + path.cmds.iter().filter(|c| !matches!(c, PathCmd::Close)).count() +} + +/// The bent mesh: the grid's vertices as drawn and where the pins carry them. +struct Bent { + grid: Grid, + rest: Vec, + shown: Vec, +} + +impl Bent { + fn at(&self, i: u32) -> (Vec2, Vec2) { + let i = i as usize; + (self.rest.get(i).copied().unwrap_or_default(), self.shown.get(i).copied().unwrap_or_default()) + } + + /// `p` (as drawn) mapped through triangle `tri`'s affine map (extrapolated outside it). + fn through(&self, tri: [u32; 3], p: Vec2) -> Vec2 { + let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| self.at(i)); + match barycentric(ra, rb, rc, p) { + Some((l0, l1, l2)) => { + let out = sa * l0 + sb * l1 + sc * l2; + if out.is_finite() { out } else { p } + } + None => p + (sa - ra), + } + } + + /// `p` (as drawn) where the mesh carries it, and the triangle that did. + fn map(&self, p: Vec2) -> (Vec2, [u32; 3]) { + let tri = self.grid.locate(p); + (self.through(tri, p), tri) + } +} + +impl Warp { + /// A warp of the outline `rest` with no pins. + pub fn new(rest: Arc, resolution: u32) -> Warp { + let shown = fingerprint(&rest); + Warp { rest, resolution: resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION), pins: Vec::new(), shown } + } + + /// Every pin where it was placed: the artwork shows as drawn. + pub fn at_rest(&self) -> bool { + self.pins.iter().all(|p| p.at == p.rest) + } + + pub fn pin(&self, id: PinId) -> Option<&Pin> { + self.pins.iter().find(|p| p.id == id) + } + + pub fn grid(&self) -> Option { + Grid::of(&self.rest, self.resolution) + } + + fn bent(&self) -> Option { + let grid = self.grid()?; + let rest = grid.vertices(); + let pins: Vec<(Vec2, Vec2)> = self.pins.iter().map(|p| (p.rest, p.at)).collect(); + let shown = if self.at_rest() { rest.clone() } else { rest.iter().map(|&v| mls_rigid(&pins, v)).collect() }; + Some(Bent { grid, rest, shown }) + } + + /// The mesh as it shows (`None` for an outline with no extent). + pub fn mesh(&self) -> Option { + let b = self.bent()?; + Some(WarpMesh { tris: b.grid.triangles(), rest: b.rest, shown: b.shown }) + } + + /// Where point `p` of the artwork as drawn shows now. + pub fn map(&self, p: Vec2) -> Vec2 { + if self.at_rest() { + return p; + } + self.bent().map_or(p, |b| b.map(p).0) + } + + /// The point of the artwork as drawn that shows at `p` (the topmost triangle there, as the + /// mesh draws); `None` off the mesh. + pub fn unmap(&self, p: Vec2) -> Option { + let b = self.bent()?; + if self.at_rest() { + return (p.x >= b.grid.min.x && p.x <= b.grid.max.x && p.y >= b.grid.min.y && p.y <= b.grid.max.y).then_some(p); + } + let tris = b.grid.triangles(); + for tri in tris.iter().rev() { + let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| b.at(i)); + let Some((l0, l1, l2)) = barycentric(sa, sb, sc, p) else { continue }; + let eps = -1e-4; + if l0 >= eps && l1 >= eps && l2 >= eps { + let r = ra * l0 + rb * l1 + rc * l2; + return r.is_finite().then_some(r); + } + } + None + } + + /// The outline as the pins bend it (the rest path itself, shared, at rest). + pub fn outline(&self) -> Arc { + if self.at_rest() { + return self.rest.clone(); + } + match self.bent() { + Some(b) => Arc::new(bend(&self.rest, &b)), + None => self.rest.clone(), + } + } + + /// Whether `path` is the outline this warp last gave its shape. + pub fn shows(&self, path: &Path) -> bool { + fingerprint(path) == self.shown + } + + /// The warp of `path` (the shape as it now is, edited since by another tool), its pins kept + /// where they show: they are its new rest, so nothing moves. + pub fn rebased(&self, path: Arc) -> Warp { + let mut w = Warp::new(path, self.resolution); + w.pins = self.pins.iter().map(|p| Pin { id: p.id, rest: p.at, at: p.at }).collect(); + w + } + + /// This warp's pins blended `t` of the way to `o`'s (pins pair by id; one without a partner + /// holds). `None` unless both bend the same artwork on the same mesh. + pub fn lerp(&self, o: &Warp, t: f32) -> Option { + if !(crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution) { + return None; + } + let mut w = self.clone(); + for p in &mut w.pins { + if let Some(q) = o.pin(p.id) { + p.at = p.at.lerp(q.at, t); + } + } + Some(w) + } + + /// Repairs a loaded warp: the resolution in range, finite pins (one per id, at most + /// [`MAX_PINS`]). `false` when nothing usable is left (no extent, too many points): the + /// shape keeps the outline it shows. + pub fn sanitize(&mut self) -> bool { + if self.grid().is_none() || anchor_count(&self.rest) > MAX_WARP_POINTS { + return false; + } + self.resolution = self.resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION); + let near = |v: Vec2| v.is_finite() && v.x.abs() <= MAX_EXTENT && v.y.abs() <= MAX_EXTENT; + let mut seen = Vec::with_capacity(self.pins.len()); + self.pins.retain(|p| { + let keep = near(p.rest) && near(p.at) && !seen.contains(&p.id); + seen.push(p.id); + keep + }); + self.pins.truncate(MAX_PINS); + true + } +} + +impl Shape { + /// The shape's warp while its outline is still the one the warp gave it. + pub fn live_warp(&self) -> Option<&Warp> { + self.warp.as_deref().filter(|w| w.shows(&self.path)) + } + + /// Sets the shape's warp to `w` and its outline to what `w` bends it into. + pub fn set_warp(&mut self, mut w: Warp) { + let path = w.outline(); + w.shown = fingerprint(&path); + self.path = path; + self.warp = Some(Arc::new(w)); + } +} + +/// Splits cubic `(p0, c1, c2, p3)` at `t`. +fn split_cubic(p0: Vec2, c1: Vec2, c2: Vec2, p3: Vec2, t: f32) -> ([Vec2; 4], [Vec2; 4]) { + let (a, b, c) = (p0.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p3, t)); + let (d, e) = (a.lerp(b, t), b.lerp(c, t)); + let f = d.lerp(e, t); + ([p0, a, d, f], [f, e, c, p3]) +} + +fn split_quad(p0: Vec2, c: Vec2, p2: Vec2, t: f32) -> ([Vec2; 3], [Vec2; 3]) { + let (a, b) = (p0.lerp(c, t), c.lerp(p2, t)); + let m = a.lerp(b, t); + ([p0, a, m], [m, b, p2]) +} + +/// How many pieces a curve with control polygon length `len` is split into. +fn pieces(len: f32, step: f32) -> usize { + let n = (len / step).ceil(); + if n.is_finite() { (n as usize).clamp(1, MAX_SPLIT) } else { 1 } +} + +/// `rest` bent through the mesh (see the module docs). +fn bend(rest: &Path, b: &Bent) -> Path { + let g = &b.grid; + let step = (((g.max.x - g.min.x) / g.nx as f32).min((g.max.y - g.min.y) / g.ny as f32) * 0.5).max(1e-3); + // Splitting is skipped past the command budget (each anchor still maps through the mesh). + let split = rest.cmds.len().saturating_mul(MAX_SPLIT) <= MAX_BENT_CMDS || estimate(rest, g, step) <= MAX_BENT_CMDS; + let mut out: Vec = Vec::with_capacity(rest.cmds.len() * 4); + let mut ts = Vec::new(); + let mut cur = Vec2::ZERO; + let mut start = Vec2::ZERO; + // The last anchor's triangle: a cubic's first handle moves with it. + let mut cur_tri = g.locate(cur); + let line = |out: &mut Vec, a: Vec2, p: Vec2, ts: &mut Vec| { + if split { + g.crossings(a, p, ts); + for &t in ts.iter() { + out.push(PathCmd::LineTo(b.map(a.lerp(p, t)).0)); + } + } + let (q, tri) = b.map(p); + out.push(PathCmd::LineTo(q)); + tri + }; + for c in &rest.cmds { + match *c { + PathCmd::MoveTo(p) => { + let (q, tri) = b.map(p); + out.push(PathCmd::MoveTo(q)); + (cur, start, cur_tri) = (p, p, tri); + } + PathCmd::LineTo(p) => { + cur_tri = line(&mut out, cur, p, &mut ts); + cur = p; + } + PathCmd::QuadTo(c, p) => { + let n = if split { pieces(cur.distance(c) + c.distance(p), step) } else { 1 }; + let mut rest_q = [cur, c, p]; + for k in 0..n { + let left = n - k; + let (piece, tail) = if left > 1 { split_quad(rest_q[0], rest_q[1], rest_q[2], 1.0 / left as f32) } else { (rest_q, rest_q) }; + let (q, tri) = b.map(piece[2]); + out.push(PathCmd::QuadTo(b.map(piece[1]).0, q)); + cur_tri = tri; + rest_q = tail; + } + cur = p; + } + PathCmd::CubicTo(c1, c2, p) => { + let n = if split { pieces(cur.distance(c1) + c1.distance(c2) + c2.distance(p), step) } else { 1 }; + let mut rest_c = [cur, c1, c2, p]; + for k in 0..n { + let left = n - k; + let (piece, tail) = if left > 1 { split_cubic(rest_c[0], rest_c[1], rest_c[2], rest_c[3], 1.0 / left as f32) } else { (rest_c, rest_c) }; + let (q, tri) = b.map(piece[3]); + out.push(PathCmd::CubicTo(b.through(cur_tri, piece[1]), b.through(tri, piece[2]), q)); + cur_tri = tri; + rest_c = tail; + } + cur = p; + } + PathCmd::Close => { + // The closing edge is a straight line too: split it like one. + if cur != start { + if split { + g.crossings(cur, start, &mut ts); + for &t in &ts { + out.push(PathCmd::LineTo(b.map(cur.lerp(start, t)).0)); + } + } + let (q, tri) = b.map(start); + out.push(PathCmd::LineTo(q)); + cur_tri = tri; + } + out.push(PathCmd::Close); + cur = start; + } + } + } + Path { cmds: out } +} + +/// A cheap upper bound of the bent outline's commands. +fn estimate(rest: &Path, g: &Grid, step: f32) -> usize { + let lines = (g.nx + g.ny) as usize * 2 + 1; + let mut cur = Vec2::ZERO; + let mut n = 0usize; + for c in &rest.cmds { + n = n.saturating_add(match *c { + PathCmd::MoveTo(p) => { + cur = p; + 1 + } + PathCmd::LineTo(p) => { + cur = p; + lines + } + PathCmd::QuadTo(a, p) => { + let k = pieces(cur.distance(a) + a.distance(p), step); + cur = p; + k + } + PathCmd::CubicTo(a, b, p) => { + let k = pieces(cur.distance(a) + a.distance(b) + b.distance(p), step); + cur = p; + k + } + PathCmd::Close => lines + 1, + }); + } + n +} + +#[cfg(test)] +#[path = "warp_tests.rs"] +mod tests; diff --git a/crates/doc/src/warp_tests.rs b/crates/doc/src/warp_tests.rs new file mode 100644 index 00000000..59578c45 --- /dev/null +++ b/crates/doc/src/warp_tests.rs @@ -0,0 +1,244 @@ +use super::*; +use crate::{Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, Tween, evaluate_layer_elements}; +use anicraft_geom::Affine; + +fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin { + Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) } +} + +fn blob() -> Arc { + Arc::new(Path::ellipse(100.0, 50.0, 100.0, 50.0)) +} + +fn anchors(p: &Path) -> Vec { + p.cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p), + PathCmd::Close => None, + }) + .collect() +} + +#[test] +fn rest_pose_reproduces_the_artwork_exactly() { + let rest = blob(); + let mut w = Warp::new(rest.clone(), 12); + // No pins, then pins exactly where they were placed: the very path, shared. + assert!(Arc::ptr_eq(&w.outline(), &rest)); + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))]; + assert!(w.at_rest()); + assert!(Arc::ptr_eq(&w.outline(), &rest)); + assert_eq!(w.map(Vec2::new(33.3, 12.5)), Vec2::new(33.3, 12.5)); + assert_eq!(w.mesh().map(|m| m.rest == m.shown), Some(true)); +} + +#[test] +fn mls_interpolates_pins_and_is_rigid_with_one_or_two() { + // One pin: everything moves with it. + let one = [(Vec2::new(0.0, 0.0), Vec2::new(5.0, -3.0))]; + assert_eq!(mls_rigid(&one, Vec2::new(40.0, 40.0)), Vec2::new(45.0, 37.0)); + // Two pins turned a quarter turn about their middle: every point turns with them. + let two = [(Vec2::new(-10.0, 0.0), Vec2::new(0.0, -10.0)), (Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0))]; + for v in [Vec2::new(3.0, 7.0), Vec2::new(-20.0, 4.0), Vec2::new(0.0, 0.0)] { + let f = mls_rigid(&two, v); + let want = Vec2::new(-v.y, v.x); + assert!(f.distance(want) < 1e-3, "{v:?} → {f:?}, want {want:?}"); + } + // On a pin: exactly its target. + assert_eq!(mls_rigid(&two, Vec2::new(10.0, 0.0)), Vec2::new(0.0, 10.0)); + assert_eq!(mls_rigid(&[], Vec2::new(1.0, 2.0)), Vec2::new(1.0, 2.0)); +} + +#[test] +fn a_single_moved_pin_moves_nearby_points_most() { + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 300.0, 100.0)), 12); + // Three pins along the strip; the right one is pulled down. + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (150.0, 50.0), (150.0, 50.0)), pin(3, (290.0, 50.0), (290.0, 90.0))]; + let moved = |x: f32| w.map(Vec2::new(x, 50.0)).distance(Vec2::new(x, 50.0)); + let (near, mid, far) = (moved(270.0), moved(200.0), moved(40.0)); + assert!(near > mid && mid > far, "{near} > {mid} > {far}"); + assert!(near > 25.0 && far < 3.0, "near {near}, far {far}"); + // The pins themselves are where they were put (to within the mesh's interpolation). + for p in &w.pins { + assert!(w.map(p.rest).distance(p.at) < 1.5, "{p:?} → {:?}", w.map(p.rest)); + } +} + +#[test] +fn deformation_is_as_rigid_as_possible() { + // Rigidity: how much each triangle's map stretches or shears (its singular values' distance + // from 1). A pure turn of the pins turns the mesh rigidly; a bend stays near rigid. + let distortion = |w: &Warp| { + let m = w.mesh().unwrap_or_else(unreachable_mesh); + let mut worst = 0.0f32; + for t in &m.tris { + let [a, b, c] = t.map(|i| i as usize); + let (r0, r1, r2) = (m.rest[a], m.rest[b], m.rest[c]); + let (s0, s1, s2) = (m.shown[a], m.shown[b], m.shown[c]); + // The linear part J with J·(r1 − r0, r2 − r0) = (s1 − s0, s2 − s0). + let (e1, e2, f1, f2) = (r1 - r0, r2 - r0, s1 - s0, s2 - s0); + let det = e1.cross(e2); + let inv = [e2.y / det, -e2.x / det, -e1.y / det, e1.x / det]; + let j = [f1.x * inv[0] + f2.x * inv[2], f1.x * inv[1] + f2.x * inv[3], f1.y * inv[0] + f2.y * inv[2], f1.y * inv[1] + f2.y * inv[3]]; + let (p, q, r, s) = (j[0], j[1], j[2], j[3]); + let e = (p * p + q * q + r * r + s * s) * 0.5; + let d = (p * s - q * r).abs(); + let disc = (e * e - d * d).max(0.0).sqrt(); + let (big, small) = ((e + disc).sqrt(), (e - disc).max(0.0).sqrt()); + worst = worst.max((big - 1.0).abs()).max((small - 1.0).abs()); + } + worst + }; + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 10); + let turn = Affine::translate(100.0, 50.0).mul(&Affine::rotate(0.6)).mul(&Affine::translate(-100.0, -50.0)); + w.pins = [(20.0, 20.0), (180.0, 30.0), (100.0, 90.0)].iter().enumerate().map(|(i, &(x, y))| Pin { id: PinId(i as u64), rest: Vec2::new(x, y), at: turn.apply(Vec2::new(x, y)) }).collect(); + assert!(distortion(&w) < 1e-3, "a turn is rigid: {}", distortion(&w)); + // A bend: one end of a strip turned down by 30°. + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (190.0, 50.0), (178.0, 95.0))]; + let d = distortion(&w); + assert!(d < 0.25, "a bend stays near rigid: {d}"); +} + +fn unreachable_mesh() -> WarpMesh { + WarpMesh { rest: Vec::new(), shown: Vec::new(), tris: Vec::new() } +} + +#[test] +fn straight_edges_follow_the_mesh_exactly() { + // A bitmap's outline is a rectangle: bent, it is exactly the mesh's border. + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 120.0, 60.0)), 6); + w.pins = vec![pin(1, (0.0, 0.0), (0.0, 0.0)), pin(2, (120.0, 60.0), (150.0, 90.0))]; + let m = w.mesh().unwrap_or_else(unreachable_mesh); + let g = w.grid().unwrap_or(Grid { min: Vec2::ZERO, max: Vec2::ZERO, nx: 1, ny: 1 }); + assert_eq!((g.nx, g.ny), (6, 3)); + let pts = anchors(&w.outline()); + // Every border vertex of the mesh is on the bent outline. + for (i, v) in m.rest.iter().enumerate() { + let border = v.x == 0.0 || v.y == 0.0 || v.x == 120.0 || v.y == 60.0; + if border { + assert!(pts.iter().any(|p| p.distance(m.shown[i]) < 1e-3), "border vertex {v:?} missing"); + } + } + // And the outline has no point the border doesn't (straight lines between them). + assert_eq!(pts.len(), 2 * (6 + 3) + 1); +} + +#[test] +fn curves_split_and_stay_close_to_the_true_deformation() { + let mut w = Warp::new(blob(), 16); + w.pins = vec![pin(1, (0.0, 50.0), (0.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (200.0, 50.0), (190.0, 100.0))]; + let bent = w.outline(); + assert!(bent.cmds.len() > blob().cmds.len()); + // Points of the bent outline lie near where the exact MLS deformation puts the drawn curve. + let pins: Vec<(Vec2, Vec2)> = w.pins.iter().map(|p| (p.rest, p.at)).collect(); + let truth: Vec = (0..400).map(|i| { + let a = i as f32 / 400.0 * std::f32::consts::TAU; + mls_rigid(&pins, Vec2::new(100.0 + 100.0 * a.cos(), 50.0 + 50.0 * a.sin())) + }).collect(); + for p in anchors(&bent) { + let d = truth.iter().map(|t| t.distance(p)).fold(f32::MAX, f32::min); + assert!(d < 2.0, "{p:?} is {d} from the true curve"); + } +} + +#[test] +fn unmap_finds_the_drawn_point() { + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 8); + w.pins = vec![pin(1, (20.0, 50.0), (20.0, 50.0)), pin(2, (180.0, 50.0), (200.0, 80.0))]; + for p in [Vec2::new(50.0, 30.0), Vec2::new(150.0, 70.0), Vec2::new(190.0, 10.0)] { + let shown = w.map(p); + let back = w.unmap(shown).unwrap_or(Vec2::new(f32::NAN, 0.0)); + assert!(back.distance(p) < 1e-2, "{p:?} → {shown:?} → {back:?}"); + } + assert_eq!(w.unmap(Vec2::new(-500.0, 0.0)), None); +} + +#[test] +fn deterministic_and_bounded() { + let mut w = Warp::new(blob(), 1000); + assert_eq!(w.resolution, MAX_RESOLUTION); + w.pins = (0..MAX_PINS as u64).map(|i| pin(i, (i as f32, 50.0), (i as f32 + 3.0, 50.0 + (i % 7) as f32))).collect(); + let (a, b) = (w.outline(), w.outline()); + assert_eq!(fingerprint(&a), fingerprint(&b)); + let m = w.mesh().unwrap_or_else(unreachable_mesh); + assert!(m.rest.len() <= ((MAX_RESOLUTION + 1) * (MAX_RESOLUTION + 1)) as usize); + // Tiny, flat and enormous artwork never fails. + for p in [Path::line(Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)), Path::line(Vec2::new(0.0, 5.0), Vec2::new(300.0, 5.0)), Path::rect(0.0, 0.0, 1e7, 1.0), Path::default()] { + let mut w = Warp::new(Arc::new(p), 12); + w.pins = vec![pin(1, (0.0, 5.0), (40.0, 9.0)), pin(2, (100.0, 5.0), (100.0, 5.0))]; + let out = w.outline(); + assert!(out.cmds.iter().all(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(), + _ => true, + })); + } + // Hostile pins are dropped on load; the rest stays. + let mut h = Warp::new(blob(), 0); + h.pins = vec![pin(1, (f32::NAN, 0.0), (0.0, 0.0)), pin(2, (1.0, 1.0), (2.0, 2.0)), pin(2, (3.0, 3.0), (3.0, 3.0))]; + assert!(h.sanitize()); + assert_eq!(h.pins.len(), 1); + assert_eq!(h.resolution, MIN_RESOLUTION); +} + +fn warped_layer(at_end: (f32, f32), easing: Easing) -> (Layer, Warp) { + let mut shape = Shape::filled(Path::rect(0.0, 0.0, 200.0, 100.0), Paint::Solid(Rgba::hex(0x3080ff))); + let mut w = Warp::new(shape.path.clone(), 8); + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))]; + shape.set_warp(w.clone()); + let el = |s: Shape| Arc::new(Element { id: ElementId(5), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(s) }); + let mut end = shape.clone(); + let mut w2 = w.clone(); + if let Some(p) = w2.pins.get_mut(1) { + p.at = Vec2::new(at_end.0, at_end.1); + } + end.set_warp(w2); + let mut layer = Layer::new(LayerId(1), "Art"); + let mut a = Keyframe::new(0, 10); + a.elements = vec![el(shape)]; + a.tween = Some(Tween { easing, ..Default::default() }); + let mut b = Keyframe::new(10, 1); + b.elements = vec![el(end)]; + layer.keyframes = vec![Arc::new(a), Arc::new(b)]; + (layer, w) +} + +fn shape_at(layer: &Layer, frame: u32) -> Shape { + let (_, els) = evaluate_layer_elements(layer, frame).unwrap_or((0, std::borrow::Cow::Owned(Vec::new()))); + match els.first().map(|e| &e.kind) { + Some(ElementKind::Shape(s)) => s.clone(), + _ => Shape::filled(Path::default(), Paint::Solid(Rgba::BLACK)), + } +} + +#[test] +fn pins_tween_between_keyframes() { + let (layer, w) = warped_layer((190.0, 150.0), Easing::Linear); + let mid = shape_at(&layer, 5); + let mw = mid.live_warp().cloned().unwrap_or_else(|| w.clone()); + // Halfway the pulled pin is halfway, and the outline is the mesh bent by the halfway pins. + assert_eq!(mw.pin(PinId(2)).map(|p| p.at), Some(Vec2::new(190.0, 100.0))); + let mut want = w.clone(); + if let Some(p) = want.pins.get_mut(1) { + p.at = Vec2::new(190.0, 100.0); + } + assert_eq!(*mid.path, *want.outline()); + // At the keyframes: exactly what they hold. + assert!(Arc::ptr_eq(&shape_at(&layer, 0).path, &w.rest)); + // Easing applies to the pins as it does to bone poses. + let (eased, _) = warped_layer((190.0, 150.0), Easing::QuadIn); + let ep = shape_at(&eased, 5).live_warp().and_then(|w| w.pin(PinId(2)).map(|p| p.at.y)).unwrap_or(0.0); + assert!(ep < 100.0 && ep > 50.0, "{ep}"); +} + +#[test] +fn a_shape_edited_by_another_tool_drops_out_of_its_warp() { + let (layer, _) = warped_layer((190.0, 150.0), Easing::Linear); + let mut s = shape_at(&layer, 10); + assert!(s.live_warp().is_some()); + s.path = Arc::new(s.path.transformed(&Affine::translate(1.0, 0.0))); + assert!(s.live_warp().is_none()); + let w = s.warp.as_deref().cloned().unwrap_or_else(|| Warp::new(blob(), 4)).rebased(s.path.clone()); + // Rebased, nothing moves: the edited outline is the new rest and the pins stay where they show. + assert!(w.at_rest() && w.pins.iter().any(|p| p.rest == Vec2::new(190.0, 150.0))); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d5329679..f6d9eda8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,10 +21,12 @@ thiserror.workspace = true rayon.workspace = true web-time.workspace = true gif.workspace = true +# Animated PNG frames (ADR 0063; already in the tree through the renderer). +png.workspace = true +image-webp.workspace = true +regex.workspace = true [dev-dependencies] -# Decodes exported sheets in tests (already in the tree through the renderer). -png.workspace = true # Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl). miniz_oxide = "0.8" # Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception). diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs new file mode 100644 index 00000000..b54c248e --- /dev/null +++ b/crates/engine/src/anim.rs @@ -0,0 +1,502 @@ +//! Animated PNG and animated WebP export (ADR 0063): full colour and real alpha, for the web +//! and chat apps, where an animated GIF has 256 colours and 1-bit transparency. +//! +//! Both formats share one pipeline. Frames render in parallel, a batch at a time (memory stays +//! bounded), as GIF export does. A frame identical to the one before it is merged into that +//! frame's delay. Every other frame is cut down to the rectangle that changed since the frame +//! before and compressed in parallel as an image of its own (a PNG, or a lossless WebP); the +//! compressed data is then put into one file in order, by hand, chunk by chunk: +//! +//! * **APNG** (the APNG specification): `IHDR`, `acTL`, then per frame an `fcTL` (its region, +//! delay, dispose op none, blend op) and its `IDAT` / `fdAT` data. Delays are exact fractions +//! of the document's frame rate (2 frames at 29.97 fps: 200/2997 s). A region whose changed +//! pixels are all opaque blends *over* the frame before, with its unchanged pixels left +//! transparent (they compress to almost nothing); otherwise it replaces (*source*). +//! * **WebP** (the WebP container specification): `VP8X`, `ANIM`, then an `ANMF` per frame +//! wrapping its `VP8L` (lossless) bitstream. Regions start on even pixels, as the format +//! needs, and replace what was there (no blending: the decoders' blend rounds opaque pixels). +//! Durations are whole milliseconds; each is rounded from the exact time the frame starts, so +//! the error never adds up and the running time is exact to the millisecond. +//! +//! A delay longer than one frame header can hold goes on, after the frame, as frames that +//! change nothing (one transparent pixel blended over), so timing is never cut short. + +use crate::params::*; +use crate::{EngineError, Result, Session}; +use anicraft_render::{View, render}; +use rayon::prelude::*; +use serde_json::{Value, json}; +use std::path::PathBuf; + +/// The two animated formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Apng, + Webp, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Apng => "animated PNG", + Kind::Webp => "animated WebP", + } + } +} + +/// Largest animation made (frames × pixels), as for GIF: time stays bounded. +pub const MAX_ANIM_PIXELS: u64 = 600 * 1280 * 720; +/// WebP canvases and frames are at most 16384 px per side. +pub const MAX_WEBP_EDGE: u32 = 16_384; +/// Pixels rendered at once (a batch of frames), so memory stays bounded at any size. +const BATCH_PIXELS: u64 = 32 * 1024 * 1024; +/// Most plays a loop count says (both formats store it in 16 bits for WebP's sake). +pub const MAX_PLAYS: u32 = anicraft_doc::publish::MAX_PLAYS; +/// Longest WebP frame duration (24 bits of milliseconds). +const MAX_WEBP_MS: u64 = 0xFF_FFFF; + +/// A rectangle of the canvas, in pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, +} + +/// One frame, compressed: the region it covers, whether it blends over what is there (else it +/// replaces it), and its image data (PNG `IDAT` data, or a whole `VP8L` chunk). +struct Encoded { + rect: Rect, + over: bool, + data: Vec, +} + +/// The frame rate as a fraction `p / q` frames per second: 24 → 24/1, 29.97 → 2997/100, +/// 23.976 → 2997/125. Rates no small fraction matches are taken to a thousandth. +pub fn fps_ratio(fps: f32) -> (u64, u64) { + let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 }; + for q in 1..=1001u64 { + let p = (fps * q as f64).round(); + if p >= 1.0 && (p / q as f64 - fps).abs() <= fps * 1e-6 { + return (p as u64, q); + } + } + let p = ((fps * 1000.0).round() as u64).max(1); + let g = gcd(p, 1000); + (p / g, 1000 / g) +} + +fn gcd(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +/// When frame `t` (from the first exported) starts, in whole milliseconds, rounded from the +/// exact time at `p / q` fps. +pub fn start_ms(t: u64, (p, q): (u64, u64)) -> u64 { + let p = u128::from(p.max(1)); + ((2 * u128::from(t) * 1000 * u128::from(q) + p) / (2 * p)) as u64 +} + +/// The APNG delays (numerator, denominator in seconds) of a frame shown from frame `start` for +/// `count` frames: one exact fraction, or more when it is longer than one `fcTL` holds. +pub fn apng_delays(start: u64, count: u64, (p, q): (u64, u64)) -> Vec<(u16, u16)> { + let mut out = Vec::new(); + if let Ok(den) = u16::try_from(p) { + // `count` frames last count·q/p s; pieces of at most 65535/q frames always fit. + let most = (u64::from(u16::MAX) / q.max(1)).max(1); + let mut left = count; + while left > 0 { + let m = left.min(most); + let (num, g) = (m * q, gcd(m * q, p)); + out.push((u16::try_from(num / g).unwrap_or(u16::MAX), u16::try_from(u64::from(den) / g).unwrap_or(den))); + left -= m; + } + } else { + // A rate with a huge denominator: milliseconds, rounded from each frame's start. + let mut ms = start_ms(start + count, (p, q)) - start_ms(start, (p, q)); + while ms > 0 { + let m = ms.min(u64::from(u16::MAX)); + out.push((m as u16, 1000)); + ms -= m; + } + } + if out.is_empty() { + out.push((0, 1)); + } + out +} + +/// The WebP durations (milliseconds) of a frame shown from frame `start` for `count` frames: +/// one, or more when it is longer than one `ANMF` holds. +pub fn webp_durations(start: u64, count: u64, ratio: (u64, u64)) -> Vec { + let mut ms = start_ms(start + count, ratio).saturating_sub(start_ms(start, ratio)); + let mut out = Vec::new(); + loop { + let m = ms.min(MAX_WEBP_MS); + out.push(m as u32); + ms -= m; + if ms == 0 { + return out; + } + } +} + +/// The smallest rectangle holding every pixel where RGBA8 images `a` and `b` (`w` × `h`) differ, +/// or `None` when they are the same. +pub fn changed(a: &[u8], b: &[u8], w: u32, h: u32) -> Option { + let stride = w as usize * 4; + let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32); + for y in 0..h { + let at = y as usize * stride; + let (Some(ra), Some(rb)) = (a.get(at..at + stride), b.get(at..at + stride)) else { break }; + if ra == rb { + continue; + } + let (pa, pb) = (ra.as_chunks::<4>().0, rb.as_chunks::<4>().0); + let first = pa.iter().zip(pb).position(|(u, v)| u != v).unwrap_or(0) as u32; + let last = pa.iter().zip(pb).rposition(|(u, v)| u != v).unwrap_or(0) as u32; + x0 = x0.min(first); + x1 = x1.max(last); + y0 = y0.min(y); + y1 = y; + } + (y0 != u32::MAX).then(|| Rect { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }) +} + +/// Rectangle `r` of RGBA8 image `px` (`w` wide). +fn crop(px: &[u8], w: u32, r: Rect) -> Vec { + let stride = w as usize * 4; + let mut out = Vec::with_capacity(r.w as usize * r.h as usize * 4); + for y in r.y..r.y + r.h { + let at = y as usize * stride + r.x as usize * 4; + if let Some(row) = px.get(at..at + r.w as usize * 4) { + out.extend_from_slice(row); + } + } + out +} + +/// What frame `cur` writes after frame `before` (none: it is the first, and covers the canvas): +/// the region, whether it blends over, and its pixels. +fn region(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> (Rect, bool, Vec) { + let full = Rect { x: 0, y: 0, w, h }; + let Some(before) = before else { return (full, false, cur.to_vec()) }; + let mut r = changed(before, cur, w, h).unwrap_or(full); + match kind { + Kind::Webp => { + // Frame offsets are stored halved: the region starts on an even pixel. + let (ex, ey) = (r.x & !1, r.y & !1); + r = Rect { x: ex, y: ey, w: r.w + (r.x - ex), h: r.h + (r.y - ey) }; + (r, false, crop(cur, w, r)) + } + Kind::Apng => { + let (old, new) = (crop(before, w, r), crop(cur, w, r)); + let (po, pn) = (old.as_chunks::<4>().0, new.as_chunks::<4>().0); + if po.iter().zip(pn).all(|(o, n)| o == n || n[3] == 255) { + // Every changed pixel is opaque: blend over, unchanged pixels transparent. + let mut px = Vec::with_capacity(new.len()); + for (o, n) in po.iter().zip(pn) { + px.extend_from_slice(if o == n { &[0, 0, 0, 0] } else { n }); + } + (r, true, px) + } else { + (r, false, new) + } + } + } +} + +/// A standalone PNG's image data: its `IDAT` chunks' contents, joined. +fn idat(png: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut at = 8usize; + while let Some(head) = png.get(at..at + 8) { + let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + let data = png.get(at + 8..at + 8 + len).ok_or_else(|| EngineError::Format("the PNG encoder wrote a short chunk".into()))?; + if &head[4..8] == b"IDAT" { + out.extend_from_slice(data); + } + at += 12 + len; + } + Ok(out) +} + +/// A RIFF file's first chunk named `id`, whole (header, data and padding). +fn riff_chunk<'a>(riff: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> { + let mut at = 12usize; + while let Some(head) = riff.get(at..at + 8) { + let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let whole = 8 + len + (len & 1); + if &head[0..4] == id { + return riff.get(at..at + whole).or_else(|| riff.get(at..at + 8 + len)); + } + at += whole; + } + None +} + +/// Compresses `px` (`w` × `h` RGBA8) as one frame's data. +fn compress(kind: Kind, px: &[u8], w: u32, h: u32) -> Result> { + let fail = |e: String| EngineError::Format(format!("{} frame: {e}", kind.name())); + match kind { + Kind::Apng => { + let mut buf = Vec::new(); + { + let mut enc = png::Encoder::new(&mut buf, w, h); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_adaptive_filter(png::AdaptiveFilterType::Adaptive); + enc.set_compression(png::Compression::Best); + let mut wr = enc.write_header().map_err(|e| fail(e.to_string()))?; + wr.write_image_data(px).map_err(|e| fail(e.to_string()))?; + } + idat(&buf) + } + Kind::Webp => { + if px.len() != w as usize * h as usize * 4 { + return Err(fail("the frame has the wrong size".into())); + } + let mut buf = Vec::new(); + image_webp::WebPEncoder::new(&mut buf).encode(px, w, h, image_webp::ColorType::Rgba8).map_err(|e| fail(e.to_string()))?; + riff_chunk(&buf, b"VP8L").map(<[u8]>::to_vec).ok_or_else(|| fail("the WebP encoder wrote no lossless image".into())) + } + } +} + +fn encode(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> Result { + let (rect, over, px) = region(kind, before, cur, w, h); + Ok(Encoded { rect, over, data: compress(kind, &px, rect.w, rect.h)? }) +} + +/// A frame that changes nothing (one transparent pixel blended over the top-left corner): how +/// a delay too long for one frame header goes on. +fn still(kind: Kind) -> Result { + Ok(Encoded { rect: Rect { x: 0, y: 0, w: 1, h: 1 }, over: true, data: compress(kind, &[0, 0, 0, 0], 1, 1)? }) +} + +// ----- the files --------------------------------------------------------------------------- + +fn png_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?; + out.extend_from_slice(&len.to_be_bytes()); + let from = out.len(); + out.extend_from_slice(id); + out.extend_from_slice(data); + let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[])); + out.extend_from_slice(&crc.to_be_bytes()); + Ok(()) +} + +/// The APNG file: frames with their delays (the first frame is the default image). +fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result> { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace + png_chunk(&mut out, b"IHDR", &ihdr)?; + let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?; + let mut actl = count.to_be_bytes().to_vec(); + actl.extend_from_slice(&plays.to_be_bytes()); + png_chunk(&mut out, b"acTL", &actl)?; + let mut seq = 0u32; + for (k, (f, (num, den))) in frames.iter().enumerate() { + let mut fctl = Vec::with_capacity(26); + for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] { + fctl.extend_from_slice(&v.to_be_bytes()); + } + fctl.extend_from_slice(&num.to_be_bytes()); + fctl.extend_from_slice(&den.to_be_bytes()); + fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over + png_chunk(&mut out, b"fcTL", &fctl)?; + seq += 1; + if k == 0 { + png_chunk(&mut out, b"IDAT", &f.data)?; + } else { + let mut fdat = Vec::with_capacity(f.data.len() + 4); + fdat.extend_from_slice(&seq.to_be_bytes()); + fdat.extend_from_slice(&f.data); + png_chunk(&mut out, b"fdAT", &fdat)?; + seq += 1; + } + } + png_chunk(&mut out, b"IEND", &[])?; + Ok(out) +} + +fn le24(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()[..3]); +} + +fn riff_push(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).map_err(|_| EngineError::Format("an animated WebP frame is too large".into()))?; + out.extend_from_slice(id); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(data); + if len & 1 == 1 { + out.push(0); + } + Ok(()) +} + +/// The animated WebP file: frames with their durations. `background` is the stage colour as +/// the `ANIM` background (RGBA), or transparent. +fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result> { + let mut body = b"WEBP".to_vec(); + let mut vp8x = vec![if alpha { 0x10 | 0x02 } else { 0x02 }, 0, 0, 0]; + le24(&mut vp8x, w - 1); + le24(&mut vp8x, h - 1); + riff_push(&mut body, b"VP8X", &vp8x)?; + let [r, g, b, a] = background; + let mut anim = vec![b, g, r, a]; + anim.extend_from_slice(&u16::try_from(plays).unwrap_or(u16::MAX).to_le_bytes()); + riff_push(&mut body, b"ANIM", &anim)?; + for (f, ms) in frames { + let mut anmf = Vec::with_capacity(16 + f.data.len()); + le24(&mut anmf, f.rect.x / 2); + le24(&mut anmf, f.rect.y / 2); + le24(&mut anmf, f.rect.w - 1); + le24(&mut anmf, f.rect.h - 1); + le24(&mut anmf, *ms); + anmf.push(if f.over { 0 } else { 0x02 }); // blending: alpha-blend or replace; dispose: none + anmf.extend_from_slice(&f.data); + riff_push(&mut body, b"ANMF", &anmf)?; + } + let mut out = Vec::with_capacity(body.len() + 8); + riff_push(&mut out, b"RIFF", &body)?; + Ok(out) +} + +// ----- the command ------------------------------------------------------------------------- + +/// How many times it plays: `loop` true (or absent) forever (0), false once, or a count. +pub(crate) fn plays(p: &Value) -> Result { + match p.get("loop") { + None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(0), + Some(Value::Bool(false)) => Ok(1), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= MAX_PLAYS) + .ok_or_else(|| EngineError::Param(format!("param 'loop' must be true (forever), false (once) or how many times it plays (0 is forever, at most {MAX_PLAYS})"))), + } +} + +/// `file.export_apng` and `file.export_webp`. +pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + // The whole movie: every scene in order. + let last = s.doc.frame_count().saturating_sub(1); + let from = opt_u32(p, "from")?.unwrap_or(0).min(last); + let to = opt_u32(p, "to")?.unwrap_or(last).min(last); + if to < from { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + let scale = crate::cmds_file::scale_param(p)?; + let plays = plays(p)?; + let background = opt_bool(p, "background")?.unwrap_or(false); + let mut view = View::stage(&s.doc, scale); + if !background { + view.background = None; + } + let (w, h) = (view.width.max(1), view.height.max(1)); + if kind == Kind::Webp && (w > MAX_WEBP_EDGE || h > MAX_WEBP_EDGE) { + return Err(EngineError::Param(format!("WebP frames are at most {MAX_WEBP_EDGE} px per side; lower 'scale'"))); + } + let n = u64::from(to - from) + 1; + if n * u64::from(w) * u64::from(h) > MAX_ANIM_PIXELS { + return Err(EngineError::Param(format!("that {} would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range", kind.name()))); + } + let doc = &s.doc; + let job = s.job.as_deref(); + let started = web_time::Instant::now(); + let batch = (BATCH_PIXELS / (u64::from(w) * u64::from(h))).clamp(2, 16) as usize; + // Each distinct frame: its first frame (from 0) and how many frames it shows for. + let mut shown: Vec<(u64, u64)> = Vec::new(); + let mut encoded: Vec = Vec::new(); + let mut prev: Option> = None; + let frames: Vec = (from..=to).collect(); + for (b, chunk) in frames.chunks(batch).enumerate() { + let images: Vec> = chunk + .par_iter() + .map(|&f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm.to_rgba8()) + }) + .collect::>()?; + // A frame like the one before it only lengthens that frame's delay. + let mut fresh: Vec = Vec::new(); + let mut last_seen: Option<&[u8]> = prev.as_deref(); + for (i, img) in images.iter().enumerate() { + match shown.last_mut() { + Some((_, count)) if last_seen == Some(img.as_slice()) => *count += 1, + _ => { + shown.push(((b * batch + i) as u64, 1)); + fresh.push(i); + } + } + last_seen = Some(img.as_slice()); + } + let made = (0..fresh.len()) + .into_par_iter() + .map(|k| { + let cur = fresh.get(k).and_then(|&i| images.get(i)).ok_or_else(|| EngineError::Format("lost a frame".into()))?; + let before = match k.checked_sub(1) { + None => prev.as_deref(), + Some(j) => fresh.get(j).and_then(|&i| images.get(i)).map(Vec::as_slice), + }; + encode(kind, before, cur, w, h) + }) + .collect::>>()?; + encoded.extend(made); + if let Some(&i) = fresh.last() { + prev = images.into_iter().nth(i); + } + } + let ratio = fps_ratio(doc.stage.fps); + let pad = still(kind)?; + let bytes = match kind { + Kind::Apng => { + let mut list: Vec<(&Encoded, (u16, u16))> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in apng_delays(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + apng_file(w, h, plays, &list)? + } + Kind::Webp => { + let mut list: Vec<(&Encoded, u32)> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in webp_durations(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + let padded = list.len() > encoded.len(); + let c = s.doc.stage.background.sanitized(); + let q = |v: f32| (v * 255.0).round() as u8; + let bg = if background { [q(c.r), q(c.g), q(c.b), 255] } else { [0; 4] }; + webp_file(w, h, plays, !background || padded, bg, &list)? + } + }; + crate::vfs::write(&path, &bytes)?; + Ok(json!({ + "written": path.display().to_string(), + "frames": n, + "stored_frames": encoded.len(), + "bytes": bytes.len(), + "width": w, + "height": h, + "loop": plays, + "ms": started.elapsed().as_millis() as u64, + })) +} + +#[cfg(test)] +#[path = "anim_tests.rs"] +mod tests; diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs new file mode 100644 index 00000000..fcce90cd --- /dev/null +++ b/crates/engine/src/anim_tests.rs @@ -0,0 +1,347 @@ +use super::*; +use crate::Session; +use anicraft_doc::sample; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn tmp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-anim-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// What the CPU renderer draws for movie frames `from..=to`, as straight RGBA8. +fn renders(doc: &anicraft_doc::Document, from: u32, to: u32, scale: f32, background: bool) -> Vec> { + let mut view = View::stage(doc, scale); + if !background { + view.background = None; + } + (from..=to).map(|f| render(&anicraft_doc::evaluate(doc, f), &view).unwrap().0.to_rgba8()).collect() +} + +/// An APNG decoded as a player shows it (the APNG specification's compositing): each frame's +/// canvas, its delay (num, den), its region and blend op, and the play count. +struct ApngFrame { + canvas: Vec, + delay: (u16, u16), + rect: Rect, + over: bool, +} + +struct Apng { + frames: Vec, + plays: u32, + size: (u32, u32), +} + +fn decode_apng(bytes: &[u8]) -> Apng { + let dec = png::Decoder::new(std::io::Cursor::new(bytes)); + let mut reader = dec.read_info().unwrap(); + let info = reader.info(); + let (w, h) = (info.width, info.height); + let actl = info.animation_control.expect("an acTL chunk"); + assert_eq!((info.color_type, info.bit_depth), (png::ColorType::Rgba, png::BitDepth::Eight)); + let mut canvas = vec![0u8; (w * h * 4) as usize]; + let mut frames = Vec::new(); + let mut buf = vec![0u8; reader.output_buffer_size()]; + for _ in 0..actl.num_frames { + let out = reader.next_frame(&mut buf).unwrap(); + let fc = *reader.info().frame_control().expect("an fcTL per frame"); + assert_eq!(fc.dispose_op, png::DisposeOp::None); + let over = fc.blend_op == png::BlendOp::Over; + let r = Rect { x: fc.x_offset, y: fc.y_offset, w: fc.width, h: fc.height }; + assert_eq!((out.width, out.height), (r.w, r.h)); + assert!(r.x + r.w <= w && r.y + r.h <= h); + for y in 0..r.h { + for x in 0..r.w { + let s = ((y * r.w + x) * 4) as usize; + let d = (((r.y + y) * w + r.x + x) * 4) as usize; + let src = &buf[s..s + 4]; + if over { + // Exact for the pixels the exporter blends: transparent or opaque. + assert!(src[3] == 0 || src[3] == 255, "an over-blended pixel is neither transparent nor opaque"); + if src[3] == 255 { + canvas[d..d + 4].copy_from_slice(src); + } + } else { + canvas[d..d + 4].copy_from_slice(src); + } + } + } + frames.push(ApngFrame { canvas: canvas.clone(), delay: (fc.delay_num, fc.delay_den), rect: r, over }); + } + Apng { frames, plays: actl.num_plays, size: (w, h) } +} + +/// The frames an APNG shows, one per movie frame at `ratio` fps (each delay is a whole number +/// of movie frames, exactly). +fn apng_movie(a: &Apng, (p, q): (u64, u64)) -> Vec> { + let mut out = Vec::new(); + for f in &a.frames { + let (num, den) = (u64::from(f.delay.0), u64::from(f.delay.1)); + // num/den s = k·q/p s + assert_eq!((num * p) % (den * q), 0, "a delay of {num}/{den} s is not a whole number of frames at {p}/{q} fps"); + for _ in 0..num * p / (den * q) { + out.push(f.canvas.clone()); + } + } + out +} + +/// A WebP decoded as a player shows it: each frame's canvas and duration. +/// An animated WebP's frames (canvas, milliseconds), loop count, size and whether it has alpha. +struct Webp { + frames: Vec<(Vec, u32)>, + looping: image_webp::LoopCount, + size: (u32, u32), + alpha: bool, +} + +fn decode_webp(bytes: &[u8]) -> Webp { + let mut dec = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).unwrap(); + assert!(dec.is_animated()); + let (w, h) = dec.dimensions(); + let alpha = dec.has_alpha(); + let mut buf = vec![0u8; dec.output_buffer_size().unwrap()]; + let mut frames = Vec::new(); + for _ in 0..dec.num_frames() { + let ms = dec.read_frame(&mut buf).unwrap(); + let rgba = if alpha { buf.clone() } else { buf.chunks(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; + frames.push((rgba, ms)); + } + Webp { frames, looping: dec.loop_count(), size: (w, h), alpha } +} + +/// The frames a WebP shows, one per movie frame: the frame showing when each starts. +fn webp_movie(frames: &[(Vec, u32)], n: u64, ratio: (u64, u64)) -> Vec> { + let mut starts = Vec::new(); + let mut t = 0u64; + for (_, ms) in frames { + starts.push(t); + t += u64::from(*ms); + } + assert_eq!(t, start_ms(n, ratio), "the running time is exact to the millisecond"); + (0..n).map(|f| { + let at = start_ms(f, ratio); + let i = starts.iter().rposition(|s| *s <= at).unwrap(); + frames[i].0.clone() + }) + .collect() +} + +fn same(got: &[Vec], want: &[Vec], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: frame count"); + for (k, (g, w)) in got.iter().zip(want).enumerate() { + assert!(g == w, "{what}: frame {} differs from the CPU renderer", k + 1); + } +} + +/// A ball that holds still for 10 frames, jumps, and holds 6 more: 16 frames, 2 pictures. +fn holds() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.ellipse", json!({"x": 40, "y": 40, "w": 60, "h": 60})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 30})); + run(&mut s, "timeline.goto", json!({"frame": 15})); + run(&mut s, "timeline.insert_frame", json!({})); + assert_eq!(s.frame_count(), 16); + s +} + +#[test] +fn frame_rates_are_exact_fractions() { + assert_eq!(fps_ratio(24.0), (24, 1)); + assert_eq!(fps_ratio(29.97), (2997, 100)); + assert_eq!(fps_ratio(23.976), (2997, 125)); + assert_eq!(fps_ratio(12.5), (25, 2)); + assert_eq!(fps_ratio(f32::NAN), (24, 1)); + assert_eq!(fps_ratio(-3.0), (24, 1)); + // Millisecond starts round from the exact time, so the error never adds up. + assert_eq!(start_ms(24, (24, 1)), 1000); + assert_eq!(start_ms(1, (30, 1)), 33); + assert_eq!(start_ms(2, (30, 1)), 67); + assert_eq!(start_ms(2997, (2997, 100)), 100_000); + assert_eq!(webp_durations(0, 3, (30, 1)), vec![100]); + let total: u32 = (0..30).flat_map(|i| webp_durations(i, 1, (30, 1))).sum(); + assert_eq!(total, 1000); + // APNG delays are fractions of the frame rate, reduced. + assert_eq!(apng_delays(0, 1, (24, 1)), vec![(1, 24)]); + assert_eq!(apng_delays(0, 6, (24, 1)), vec![(1, 4)]); + assert_eq!(apng_delays(5, 2, (2997, 100)), vec![(200, 2997)]); + // Longer than one fcTL holds: more pieces, adding up exactly. + let long = apng_delays(0, 200_000, (2997, 100)); + assert!(long.len() > 1); + let frames: u64 = long.iter().map(|&(n, d)| u64::from(n) * 2997 / (u64::from(d) * 100)).sum(); + assert_eq!(frames, 200_000); + // A rate with a huge denominator falls back to milliseconds, still adding up. + let odd = (100_003, 1000); + let ms: u64 = apng_delays(0, 1000, odd).iter().map(|&(n, d)| { + assert_eq!(d, 1000); + u64::from(n) + }).sum(); + assert_eq!(ms, start_ms(1000, odd)); + let hours = webp_durations(0, 100_000, (1, 1)); + assert_eq!(hours.iter().map(|&m| u64::from(m)).sum::(), 100_000_000); + assert!(hours.iter().all(|&m| u64::from(m) <= MAX_WEBP_MS) && hours.len() > 1); +} + +#[test] +fn the_changed_rectangle_is_tight() { + let (w, h) = (8u32, 6u32); + let a = vec![0u8; (w * h * 4) as usize]; + assert_eq!(changed(&a, &a, w, h), None); + let mut b = a.clone(); + b[((2 * w + 3) * 4 + 1) as usize] = 9; // (3, 2) + b[((4 * w + 6) * 4 + 3) as usize] = 9; // (6, 4) + assert_eq!(changed(&a, &b, w, h), Some(Rect { x: 3, y: 2, w: 4, h: 3 })); + // WebP regions start on even pixels; APNG's stay tight. + let (r, over, px) = region(Kind::Webp, Some(&a), &b, w, h); + assert_eq!((r, over, px.len()), (Rect { x: 2, y: 2, w: 5, h: 3 }, false, 5 * 3 * 4)); + let (r, over, _) = region(Kind::Apng, Some(&a), &b, w, h); + assert_eq!((r, over), (Rect { x: 3, y: 2, w: 4, h: 3 }, false), "semi-transparent changes replace"); + let mut c = a.clone(); + c[((2 * w + 3) * 4) as usize..((2 * w + 3) * 4 + 4) as usize].copy_from_slice(&[1, 2, 3, 255]); + let (r, over, px) = region(Kind::Apng, Some(&a), &c, w, h); + assert_eq!((r, over, px), (Rect { x: 3, y: 2, w: 1, h: 1 }, true, vec![1, 2, 3, 255]), "opaque changes blend over"); +} + +#[test] +fn apng_frames_match_the_renderer_exactly() { + let dir = tmp("apng"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.png")); + let v = run(&mut s, "file.export_apng", json!({"path": path.display().to_string(), "scale": 0.25, "to": 23, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(v["bytes"], bytes.len()); + let a = decode_apng(&bytes); + assert_eq!(a.plays, 0, "loops forever by default"); + let want = renders(&s.doc, 0, 23, 0.25, background); + assert_eq!(a.size, (320, 180)); + same(&apng_movie(&a, fps_ratio(s.doc.stage.fps)), &want, "APNG"); + // Frames after the first cover only what changed. + assert!(a.frames.iter().skip(1).any(|f| f.rect.w * f.rect.h < 320 * 180), "dirty rectangles"); + if background { + assert!(a.frames.iter().skip(1).all(|f| f.over), "opaque frames blend over"); + } + // The default image is the first frame, and a plain PNG reader sees it. + let first = png::Decoder::new(std::io::Cursor::new(&bytes)).read_info().unwrap().info().frame_control.unwrap(); + assert_eq!((first.width, first.height, first.x_offset, first.y_offset), (320, 180, 0, 0)); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn webp_frames_match_the_renderer_exactly() { + let dir = tmp("webp"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.webp")); + let v = run(&mut s, "file.export_webp", json!({"path": path.display().to_string(), "scale": 0.25, "from": 4, "to": 27, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP"); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len()); + let Webp { frames, looping, size, alpha } = decode_webp(&bytes); + assert_eq!((size, alpha), ((320, 180), !background)); + assert_eq!(looping, image_webp::LoopCount::Forever); + let want = renders(&s.doc, 4, 27, 0.25, background); + same(&webp_movie(&frames, 24, fps_ratio(s.doc.stage.fps)), &want, "WebP"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn identical_frames_merge_into_longer_delays() { + let dir = tmp("holds"); + let mut s = holds(); + let ratio = fps_ratio(s.doc.stage.fps); + let want = renders(&s.doc, 0, 15, 1.0, false); + let png = dir.join("holds.png"); + let v = run(&mut s, "file.export_apng", json!({"path": png.display().to_string(), "loop": 3})); + assert_eq!((v["frames"].as_u64(), v["stored_frames"].as_u64(), v["loop"].as_u64()), (Some(16), Some(2), Some(3))); + let a = decode_apng(&std::fs::read(&png).unwrap()); + assert_eq!(a.frames.len(), 2); + assert_eq!(a.plays, 3); + let fps = s.doc.stage.fps; + assert_eq!(a.frames[0].delay, apng_delays(0, 10, ratio)[0], "10 frames at {fps} fps"); + same(&apng_movie(&a, ratio), &want, "held APNG"); + let webp = dir.join("holds.webp"); + let v = run(&mut s, "file.export_webp", json!({"path": webp.display().to_string(), "loop": false})); + assert_eq!(v["stored_frames"], 2); + let Webp { frames, looping, .. } = decode_webp(&std::fs::read(&webp).unwrap()); + assert_eq!(frames.len(), 2); + assert_eq!(looping, image_webp::LoopCount::Times(std::num::NonZeroU16::new(1).unwrap())); + same(&webp_movie(&frames, 16, ratio), &want, "held WebP"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_overwrites_confirm() { + let dir = tmp("params"); + let mut s = holds(); + let at = |n: &str| dir.join(n).display().to_string(); + for id in ["file.export_apng", "file.export_webp"] { + for bad in [json!({"loop": -1}), json!({"loop": 70_000}), json!({"loop": "yes"}), json!({"scale": 0}), json!({"from": 9, "to": 2}), json!({"background": 3})] { + let mut p = bad.clone(); + p["path"] = json!(at("x.out")); + assert!(s.execute(id, &p).is_err(), "{id} {bad}"); + } + assert!(s.execute(id, &json!({"path": at("big.out"), "scale": 8})).is_err(), "{id}: too large"); + assert!(!Path::new(&at("x.out")).exists() && !Path::new(&at("big.out")).exists()); + let path = at(&format!("once-{id}.out")); + run(&mut s, id, json!({"path": path, "to": 1})); + assert!(s.execute(id, &json!({"path": path})).is_err(), "{id}: replacing a file asks first"); + run(&mut s, id, json!({"path": path, "confirm": true})); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_cancelled_publish_stops_the_export() { + let mut s = Session::new(sample::demo()); + let job = std::sync::Arc::new(crate::publish::Control::default()); + job.cancel(); + s.job = Some(job); + let dir = tmp("cancel"); + let path = dir.join("walk.webp"); + let e = s.execute("file.export_webp", &json!({"path": path.display().to_string(), "scale": 0.1})).unwrap_err(); + assert!(matches!(e, EngineError::Cancelled), "{e}"); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +#[ignore = "a measurement: cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture"] +fn sizes() { + // docs/performance.md › Animated exports: the sample, every frame, at full size and half. + let dir = tmp("sizes"); + for scale in [1.0, 0.5] { + let mut s = Session::new(sample::demo()); + let mut row = format!("scale {scale}:"); + for (id, ext, extra) in [ + ("file.export_gif", "gif", json!({})), + ("file.export_apng", "png", json!({"background": true})), + ("file.export_apng", "png", json!({})), + ("file.export_webp", "webp", json!({"background": true})), + ("file.export_webp", "webp", json!({})), + ] { + let mut p = extra.clone(); + p["path"] = json!(dir.join(format!("walk-{scale}-{}.{ext}", extra.as_object().map_or(0, |o| o.len()))).display().to_string()); + p["scale"] = json!(scale); + p["confirm"] = json!(true); + let t = std::time::Instant::now(); + let v = run(&mut s, id, p); + row.push_str(&format!(" | {id} {extra}: {} KB, {} stored, {} ms", v["bytes"].as_u64().unwrap() / 1024, v["stored_frames"], t.elapsed().as_millis())); + } + println!("{row}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/brush_library.rs b/crates/engine/src/brush_library.rs new file mode 100644 index 00000000..f8c321a2 --- /dev/null +++ b/crates/engine/src/brush_library.rs @@ -0,0 +1,482 @@ +//! The brush library (ADR 0068): brush presets, the built-in ones and the user's own. +//! +//! A preset is a set of tip settings (size, shape, angle, roundness, smoothing), a pressure +//! curve, what pressure drives (size, opacity), and shaping (tapers, dab spacing, a ragged +//! edge). Everything is a parameter: no bitmaps, so a preset is a few numbers, renders at any +//! size and gives the same outline from the same points every time. +//! +//! The built-ins are AniCraft's own, made from these parameters. The user's presets belong to +//! the session (they survive New and Open, like recent files); the desktop app keeps them in +//! its preferences and puts them back at start, so the engine never reads the settings folder. +//! A brush set moves between computers as a small JSON file (`brush.preset_export`/`_import`). + +use crate::params::*; +use crate::{EngineError, Result}; +use anicraft_geom::brush::{Shaping, Tip, TipShape}; +use anicraft_geom::pressure::PressureCurve; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Most presets of the user's own. +pub const MAX_USER_PRESETS: usize = 200; +/// Longest preset name, in characters. +pub const MAX_NAME: usize = 64; +/// Largest brush set file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// What a brush set file says it is. +pub const FILE_FORMAT: &str = "anicraft-brushes"; +pub const FILE_VERSION: u32 = 1; + +/// A tip shape as a preset stores it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Shape { + #[default] + Round, + Square, +} + +impl Shape { + pub fn tip(self) -> TipShape { + match self { + Shape::Round => TipShape::Round, + Shape::Square => TipShape::Square, + } + } + pub fn from_tip(t: TipShape) -> Shape { + match t { + TipShape::Round => Shape::Round, + TipShape::Square => Shape::Square, + } + } + pub fn key(self) -> &'static str { + match self { + Shape::Round => "round", + Shape::Square => "square", + } + } +} + +/// A brush preset. Percentages are as Properties shows them. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BrushPreset { + pub name: String, + /// Diameter (or side), stage units. + pub size: f32, + pub shape: Shape, + /// Degrees, clockwise. + pub angle: f32, + /// The narrow side as a percentage of the wide one (5..=100). + pub roundness: f32, + /// 0..=100. + pub smoothing: f32, + /// How pen pressure maps before it drives size or opacity. + pub curve: PressureCurve, + /// Pressure varies the size (from 10 % to 100 %). + pub pressure_size: bool, + /// Pressure varies the paint's opacity (the stroke's average, ADR 0068). + pub pressure_opacity: bool, + /// Percentages of the stroke's length (0..=50). + pub taper_start: f32, + pub taper_end: f32, + /// 0: a continuous stroke; otherwise dabs this far apart, as a percentage of the size + /// (5..=1000). + pub spacing: f32, + /// A ragged edge, worn in by up to this percentage of the size (0..=50). + pub jitter: f32, +} + +impl Default for BrushPreset { + /// The Brush tool's own defaults (ADR 0033). + fn default() -> Self { + BrushPreset { + name: String::new(), + size: 10.0, + shape: Shape::Round, + angle: 0.0, + roundness: 100.0, + smoothing: 50.0, + curve: PressureCurve::LINEAR, + pressure_size: true, + pressure_opacity: false, + taper_start: 0.0, + taper_end: 0.0, + spacing: 0.0, + jitter: 0.0, + } + } +} + +/// The built-in presets: `(key, name)`, in the order the library shows them. +pub const BUILTIN: [(&str, &str); 7] = [ + ("pencil", "Pencil"), + ("ink_pen", "Ink Pen"), + ("calligraphy", "Flat Calligraphy"), + ("round_taper", "Round Taper"), + ("marker", "Marker"), + ("chalk", "Chalk"), + ("dotted", "Dotted"), +]; + +/// A one-line description of each built-in preset, for tooltips. +pub fn builtin_hint(key: &str) -> &'static str { + match key { + "pencil" => "A thin line with short tapered ends; it takes a firm press to paint wide.", + "ink_pen" => "A smooth inking line that follows a light touch and tapers at both ends.", + "calligraphy" => "A flat nib at 45°: thick and thin strokes by direction.", + "round_taper" => "A round brush that swells from a point and thins back to one.", + "marker" => "A chisel-tipped marker of one width, whatever the pressure.", + "chalk" => "A broad stroke with a ragged, worn edge.", + "dotted" => "Round dots spaced along the stroke.", + _ => "", + } +} + +/// A built-in preset by key. +pub fn builtin(key: &str) -> Option { + let (_, name) = BUILTIN.iter().find(|(k, _)| *k == key)?; + let d = BrushPreset { name: (*name).to_string(), ..BrushPreset::default() }; + Some(match key { + "pencil" => BrushPreset { size: 3.0, smoothing: 30.0, curve: PressureCurve::FIRM, taper_start: 5.0, taper_end: 5.0, ..d }, + "ink_pen" => BrushPreset { size: 6.0, smoothing: 60.0, curve: PressureCurve::SOFT, taper_start: 12.0, taper_end: 18.0, ..d }, + "calligraphy" => BrushPreset { size: 18.0, angle: 45.0, roundness: 15.0, smoothing: 50.0, ..d }, + "round_taper" => BrushPreset { size: 14.0, smoothing: 55.0, taper_start: 35.0, taper_end: 35.0, ..d }, + "marker" => BrushPreset { size: 16.0, shape: Shape::Square, angle: 30.0, roundness: 45.0, smoothing: 40.0, pressure_size: false, ..d }, + "chalk" => BrushPreset { size: 20.0, roundness: 80.0, angle: 20.0, smoothing: 40.0, jitter: 18.0, ..d }, + "dotted" => BrushPreset { size: 8.0, smoothing: 60.0, pressure_size: false, spacing: 220.0, ..d }, + _ => d, + }) +} + +impl BrushPreset { + /// The values clamped to their ranges (a file or a hand-edited preference). + pub fn sanitized(mut self) -> BrushPreset { + let d = BrushPreset::default(); + let c = |v: f32, lo: f32, hi: f32, def: f32| if v.is_finite() { v.clamp(lo, hi) } else { def }; + self.name = clean_name(&self.name).unwrap_or_default(); + self.size = c(self.size, *crate::cmds_brush::SIZE_RANGE.start(), *crate::cmds_brush::SIZE_RANGE.end(), d.size); + self.angle = c(self.angle, -1e6, 1e6, 0.0).rem_euclid(180.0); + self.roundness = c(self.roundness, 5.0, 100.0, 100.0); + self.smoothing = c(self.smoothing, 0.0, 100.0, d.smoothing); + self.curve = PressureCurve::new(self.curve.points()); + self.taper_start = c(self.taper_start, 0.0, 50.0, 0.0); + self.taper_end = c(self.taper_end, 0.0, 50.0, 0.0); + self.spacing = c(self.spacing, 0.0, 1000.0, 0.0); + if self.spacing > 0.0 { + self.spacing = self.spacing.max(5.0); + } + self.jitter = c(self.jitter, 0.0, 50.0, 0.0); + self + } + + pub fn tip(&self) -> Tip { + Tip { shape: self.shape.tip(), size: self.size, angle: self.angle, roundness: self.roundness / 100.0 } + } + + pub fn shaping(&self) -> Shaping { + Shaping { taper_start: self.taper_start / 100.0, taper_end: self.taper_end / 100.0, spacing: self.spacing / 100.0, jitter: self.jitter / 100.0 }.sanitized() + } + + /// The tip's size factor input at a measured pressure: the curve's output when pressure + /// drives the size, else full. + pub fn size_pressure(&self, pressure: f32) -> f32 { + if self.pressure_size { self.curve.map(pressure) } else { 1.0 } + } + + /// The settings without the name, as command params (what `draw.brush` takes). + pub fn params(&self) -> Value { + let mut v = serde_json::to_value(self).unwrap_or_default(); + if let Some(o) = v.as_object_mut() { + o.remove("name"); + } + v + } + + /// This preset with any settings `p` gives instead (the params of `draw.brush` and + /// `brush.preset_save`). Refuses values out of range. + pub fn with_params(&self, p: &Value) -> Result { + let mut b = self.clone(); + let r = crate::cmds_brush::ranged; + b.size = r(p, "size", crate::cmds_brush::SIZE_RANGE, b.size)?; + b.shape = match opt_str(p, "shape")? { + None => b.shape, + Some("round") => Shape::Round, + Some("square") => Shape::Square, + Some(other) => return Err(EngineError::Param(format!("unknown tip shape '{other}' (round or square)"))), + }; + if let Some(a) = opt_f32(p, "angle")? { + if !a.is_finite() || a.abs() > 1e6 { + return Err(EngineError::Param("param 'angle' must be a finite number of degrees".into())); + } + b.angle = a; + } + b.roundness = r(p, "roundness", 5.0..=100.0, b.roundness)?; + b.smoothing = r(p, "smoothing", 0.0..=100.0, b.smoothing)?; + if let Some(c) = curve_param(p, "curve")? { + b.curve = c; + } + b.pressure_size = opt_bool(p, "pressure_size")?.unwrap_or(b.pressure_size); + b.pressure_opacity = opt_bool(p, "pressure_opacity")?.unwrap_or(b.pressure_opacity); + b.taper_start = r(p, "taper_start", 0.0..=50.0, b.taper_start)?; + b.taper_end = r(p, "taper_end", 0.0..=50.0, b.taper_end)?; + b.spacing = r(p, "spacing", 0.0..=1000.0, b.spacing)?; + if b.spacing > 0.0 && b.spacing < 5.0 { + return Err(EngineError::Param("param 'spacing' must be 0 (a continuous stroke) or from 5 to 1000 %".into())); + } + b.jitter = r(p, "jitter", 0.0..=50.0, b.jitter)?; + Ok(b) + } +} + +/// The `curve` param: a preset name (`linear`, `soft`, `firm`) or `[[pressure, output], ..]` +/// (both 0..1). +pub fn curve_param(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be linear, soft, firm or a list of [pressure, output] pairs from 0 to 1")); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(k)) => PressureCurve::preset(k).map(Some).ok_or_else(bad), + Some(Value::Array(list)) => { + if list.is_empty() || list.len() > 64 { + return Err(bad()); + } + let pts = list + .iter() + .map(|v| { + let xy = v.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() && (-1e-3..=1.001).contains(f)).ok_or_else(bad); + Ok([n(0)?, n(1)?]) + }) + .collect::>>()?; + Ok(Some(PressureCurve::new(&pts))) + } + Some(_) => Err(bad()), + } +} + +/// A name as kept: trimmed, one line, at most [`MAX_NAME`] characters; `None` when empty. +pub fn clean_name(s: &str) -> Option { + let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + let t: String = one.trim().chars().take(MAX_NAME).collect(); + let t = t.trim().to_string(); + (!t.is_empty()).then_some(t) +} + +/// Whether two names are the same preset (case doesn't matter). +fn same_name(a: &str, b: &str) -> bool { + a.trim().to_lowercase() == b.trim().to_lowercase() +} + +/// Whether `name` is a built-in preset's (by key or by name). +pub fn is_builtin_name(name: &str) -> bool { + BUILTIN.iter().any(|(k, n)| same_name(k, name) || same_name(n, name)) +} + +/// The user's own presets, in the order they were saved. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct BrushLibrary { + user: Vec, +} + +/// A brush set file. +#[derive(Serialize, Deserialize)] +struct BrushFile { + format: String, + version: u32, + brushes: Vec, +} + +impl BrushLibrary { + pub fn user(&self) -> &[BrushPreset] { + &self.user + } + + pub fn is_empty(&self) -> bool { + self.user.is_empty() + } + + /// A library from untrusted entries (preferences, a file): bad entries and names skipped, + /// values clamped, names made unique, at most [`MAX_USER_PRESETS`]. + pub fn from_values(values: impl IntoIterator) -> BrushLibrary { + let mut lib = BrushLibrary::default(); + for v in values.into_iter().take(MAX_USER_PRESETS * 4) { + if let Ok(p) = serde_json::from_value::(v) { + let _ = lib.add_unique(p); + } + } + lib + } + + /// The same library with every entry sanitized (after deserializing preferences). + pub fn sanitized(self) -> BrushLibrary { + BrushLibrary::from_values(self.user.into_iter().filter_map(|p| serde_json::to_value(p).ok())) + } + + /// A preset by built-in key, built-in name or the user's name (case doesn't matter; the + /// user's own win only where no built-in has the name, which saving refuses anyway). + pub fn find(&self, name: &str) -> Option { + if let Some((k, _)) = BUILTIN.iter().find(|(k, n)| *k == name || same_name(n, name)) { + return builtin(k); + } + self.user.iter().find(|p| same_name(&p.name, name)).cloned() + } + + pub fn position(&self, name: &str) -> Option { + self.user.iter().position(|p| same_name(&p.name, name)) + } + + /// Saves `p` under its name, replacing the user's preset of that name. Returns whether it + /// replaced one. + pub fn save(&mut self, p: BrushPreset) -> Result { + let p = p.sanitized(); + let name = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?; + if is_builtin_name(&name) { + return Err(EngineError::Param(format!("'{name}' is a built-in brush; save yours under another name"))); + } + let p = BrushPreset { name, ..p }; + if let Some(i) = self.position(&p.name) + && let Some(slot) = self.user.get_mut(i) + { + *slot = p; + return Ok(true); + } + if self.user.len() >= MAX_USER_PRESETS { + return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first"))); + } + self.user.push(p); + Ok(false) + } + + /// Adds `p`, renaming it ("Ink 2", "Ink 3", ..) if the name is taken. Returns its name. + pub fn add_unique(&mut self, p: BrushPreset) -> Result { + let p = p.sanitized(); + let base = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?; + let taken = |lib: &BrushLibrary, n: &str| is_builtin_name(n) || lib.position(n).is_some(); + let mut name = base.clone(); + let mut k = 2; + while taken(self, &name) { + if k > MAX_USER_PRESETS + 10 { + return Err(EngineError::State("too many brushes of that name".into())); + } + let suffix = format!(" {k}"); + name = format!("{}{suffix}", base.chars().take(MAX_NAME.saturating_sub(suffix.chars().count())).collect::().trim_end()); + k += 1; + } + if self.user.len() >= MAX_USER_PRESETS { + return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first"))); + } + self.user.push(BrushPreset { name: name.clone(), ..p }); + Ok(name) + } + + pub fn rename(&mut self, name: &str, to: &str) -> Result { + let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?; + let to = clean_name(to).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?; + if is_builtin_name(&to) { + return Err(EngineError::Param(format!("'{to}' is a built-in brush's name"))); + } + if self.position(&to).is_some_and(|j| j != i) { + return Err(EngineError::Param(format!("you already have a brush named '{to}'"))); + } + if let Some(p) = self.user.get_mut(i) { + p.name = to.clone(); + } + Ok(to) + } + + pub fn delete(&mut self, name: &str) -> Result { + let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?; + Ok(self.user.remove(i)) + } + + /// A brush set file holding `presets`. + pub fn file_json(presets: &[BrushPreset]) -> String { + let f = BrushFile { format: FILE_FORMAT.into(), version: FILE_VERSION, brushes: presets.iter().filter_map(|p| serde_json::to_value(p).ok()).collect() }; + serde_json::to_string_pretty(&f).unwrap_or_default() + } + + /// The presets in a brush set file (bad entries skipped; values clamped). + pub fn parse_file(text: &str) -> Result> { + let f: BrushFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a brush set file: {e}")))?; + if f.format != FILE_FORMAT { + return Err(EngineError::Param(format!("not a brush set file (its format is '{}')", f.format.chars().take(40).collect::()))); + } + if f.version > FILE_VERSION { + return Err(EngineError::Param(format!("this brush set is version {}, newer than this AniCraft reads ({FILE_VERSION})", f.version))); + } + Ok(f.brushes.into_iter().take(MAX_USER_PRESETS * 4).filter_map(|v| serde_json::from_value::(v).ok()).map(BrushPreset::sanitized).filter(|p| !p.name.is_empty()).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn builtins_are_named_and_in_range() { + for (key, name) in BUILTIN { + let p = builtin(key).unwrap(); + assert_eq!(p.name, name); + assert_eq!(p.clone().sanitized(), p, "{key} is already in range"); + assert!(!builtin_hint(key).is_empty()); + } + assert_eq!(BrushPreset::default().shaping(), Shaping::default(), "the plain brush shapes nothing"); + } + + #[test] + fn saving_renaming_and_deleting() { + let mut lib = BrushLibrary::default(); + assert!(!lib.save(BrushPreset { name: " My ink \n".into(), size: 1e9, ..BrushPreset::default() }).unwrap()); + assert_eq!(lib.user()[0].name, "My ink"); + assert_eq!(lib.user()[0].size, 2000.0, "clamped"); + assert!(lib.save(BrushPreset { name: "my INK".into(), size: 4.0, ..BrushPreset::default() }).unwrap(), "same name replaces"); + assert_eq!(lib.user().len(), 1); + assert!(lib.save(BrushPreset { name: "Chalk".into(), ..BrushPreset::default() }).is_err(), "a built-in's name"); + assert!(lib.save(BrushPreset { name: " ".into(), ..BrushPreset::default() }).is_err()); + assert_eq!(lib.add_unique(BrushPreset { name: "My ink".into(), ..BrushPreset::default() }).unwrap(), "My ink 2"); + assert_eq!(lib.add_unique(BrushPreset { name: "chalk".into(), ..BrushPreset::default() }).unwrap(), "chalk 2"); + assert_eq!(lib.rename("my ink 2", "Wet").unwrap(), "Wet"); + assert!(lib.rename("Wet", "My Ink").is_err() && lib.rename("Wet", "Marker").is_err() && lib.rename("nope", "x").is_err()); + assert_eq!(lib.find("wet").map(|p| p.name), Some("Wet".into())); + assert_eq!(lib.find("ink_pen").map(|p| p.name), Some("Ink Pen".into())); + assert_eq!(lib.find("ink pen").map(|p| p.size), Some(6.0)); + assert_eq!(lib.delete("WET").unwrap().name, "Wet"); + assert!(lib.delete("Wet").is_err()); + } + + #[test] + fn brush_set_files_round_trip_and_reject_junk() { + let mine = vec![BrushPreset { name: "A".into(), curve: PressureCurve::SOFT, jitter: 12.0, ..BrushPreset::default() }, builtin("dotted").unwrap()]; + let text = BrushLibrary::file_json(&mine); + assert_eq!(BrushLibrary::parse_file(&text).unwrap(), mine); + assert!(BrushLibrary::parse_file("{}").is_err()); + assert!(BrushLibrary::parse_file(r#"{"format": "other", "version": 1, "brushes": []}"#).is_err()); + assert!(BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 99, "brushes": []}"#).is_err()); + // Bad entries are skipped, out-of-range values clamped, older files without the newer + // fields read with defaults. + let got = BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "brushes": [7, {"name": ""}, {"name": "Old", "size": -4, "spacing": 2, "curve": [[0.5, 9]]}]}"#).unwrap(); + assert_eq!(got.len(), 1); + assert_eq!((got[0].size, got[0].spacing, got[0].smoothing), (0.1, 5.0, 50.0)); + assert_eq!(got[0].curve.points(), &[[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]]); + // Preferences: the library as a list. + let lib = BrushLibrary::from_values(serde_json::from_str::>(&serde_json::to_string(&mine).unwrap()).unwrap()); + assert_eq!(lib.user().len(), 2); + assert_eq!(lib.user()[1].name, "Dotted 2", "a built-in's name is renamed"); + } + + #[test] + fn params_override_a_preset() { + let p = builtin("calligraphy").unwrap(); + let q = p.with_params(&serde_json::json!({"size": 30, "curve": "firm", "taper_end": 20})).unwrap(); + assert_eq!((q.size, q.curve, q.taper_end, q.roundness), (30.0, PressureCurve::FIRM, 20.0, 15.0)); + let q = p.with_params(&serde_json::json!({"curve": [[0, 0.2], [1, 0.8]]})).unwrap(); + assert_eq!(q.curve.map(0.0), 0.2); + for bad in [serde_json::json!({"curve": "wobbly"}), serde_json::json!({"curve": [[0, 2]]}), serde_json::json!({"curve": []}), serde_json::json!({"spacing": 2}), serde_json::json!({"jitter": 60}), serde_json::json!({"shape": "star"})] { + assert!(p.with_params(&bad).is_err(), "{bad}"); + } + // The params name every setting and read back as the same preset. + let back = BrushPreset::default().with_params(&p.params()).unwrap(); + assert_eq!(BrushPreset { name: p.name.clone(), ..back }, p); + } +} diff --git a/crates/engine/src/brush_library_tests.rs b/crates/engine/src/brush_library_tests.rs new file mode 100644 index 00000000..a5d1e2d3 --- /dev/null +++ b/crates/engine/src/brush_library_tests.rs @@ -0,0 +1,304 @@ +//! The brush library, pressure curves and the Paint Brush (ADR 0068). + +use crate::Session; +use crate::brush_library::BUILTIN; +use anicraft_doc::{ElementKind, Shape}; +use anicraft_geom::Affine; +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}: {e}")) +} + +fn blank() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": true})); + s +} + +fn shapes(s: &Session) -> Vec { + s.visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + .collect() +} + +fn area(sh: &Shape) -> f32 { + sh.path + .flatten(&Affine::IDENTITY, 0.01) + .iter() + .map(|pl| { + let n = pl.points.len(); + ((0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::() * 0.5).abs() + }) + .sum() +} + +/// A 400-unit wave with the pressure swelling from 0.3 to 1 and back. +fn wave() -> Vec<[f32; 3]> { + (0..=80) + .map(|i| { + let t = i as f32 / 80.0; + [100.0 + 400.0 * t, 200.0 + 30.0 * (t * std::f32::consts::TAU).sin(), 0.3 + 0.7 * (t * std::f32::consts::PI).sin()] + }) + .collect() +} + +/// The wave's length (polyline). +fn wave_length() -> f32 { + wave().windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum() +} + +fn painted(preset: &str, extra: Value) -> (Shape, Value) { + let mut s = blank(); + let mut p = json!({"points": wave(), "preset": preset, "color": "#203040"}); + if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { + o.extend(e.clone()); + } + let r = run(&mut s, "draw.brush", p); + let all = shapes(&s); + assert_eq!(all.len(), 1, "{preset}: one shape"); + (all[0].clone(), r) +} + +#[test] +fn every_preset_paints_within_its_area_bounds() { + let len = wave_length(); + // (key, least, most) area as a part of length × size: what each preset's settings allow. + let bounds = [ + ("pencil", 0.4, 0.65), // a firm curve thins the light parts; short tapers + ("ink_pen", 0.7, 0.9), // a soft curve keeps it wide; tapered ends + ("calligraphy", 0.45, 0.7), // a 15 % flat nib: thick and thin by direction + ("round_taper", 0.55, 0.75), // swells from a point and back + ("marker", 0.75, 0.95), // a square chisel at 45 %, no pressure + ("chalk", 0.35, 0.55), // its edge worn in + // Dots 2.2 sizes apart, each a quarter π of size²: π / 8.8 = 0.357 of length × size. + ("dotted", 0.33, 0.38), + ]; + assert_eq!(bounds.len(), BUILTIN.len(), "every built-in has bounds"); + for (key, lo, hi) in bounds { + let b = crate::brush_library::builtin(key).unwrap(); + let (sh, _) = painted(key, json!({})); + let a = area(&sh) / (len * b.size); + assert!((lo..=hi).contains(&a), "{key}: {a:.3} of length × size, want {lo}..{hi}"); + assert!(sh.stroke.is_none() && sh.fill.is_some(), "{key} paints a fill"); + } + // Dots are separate loops; chalk's edge is ragged (many more anchors than a plain stroke). + let (dots, _) = painted("dotted", json!({})); + let loops = dots.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count(); + let want = (wave_length() / (8.0 * 2.2)).floor() as usize + 1; + assert!(loops.abs_diff(want) <= 2, "{loops} dots, about {want}"); + let (chalk, _) = painted("chalk", json!({})); + let (plain, _) = painted("chalk", json!({"jitter": 0})); + assert!(chalk.path.anchors().len() > 2 * plain.path.anchors().len()); +} + +#[test] +fn the_same_points_and_settings_give_identical_outlines() { + for (key, _) in BUILTIN { + for as_stroke in [false, true] { + let (a, _) = painted(key, json!({"as_stroke": as_stroke})); + let (b, _) = painted(key, json!({"as_stroke": as_stroke})); + assert_eq!(a.path, b.path, "{key} as_stroke {as_stroke}"); + assert_eq!(a.stroke, b.stroke); + } + } +} + +#[test] +fn pressure_curves_map_before_the_size() { + // A steady half pressure: soft paints wider than linear, firm narrower. + let pts: Vec<[f32; 3]> = (0..=40).map(|i| [100.0 + i as f32 * 10.0, 100.0, 0.5]).collect(); + let area_with = |curve: Value| { + let mut s = blank(); + run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "curve": curve})); + area(&shapes(&s)[0]) + }; + let (lin, soft, firm) = (area_with(json!("linear")), area_with(json!("soft")), area_with(json!("firm"))); + // Linear: factor 0.1 + 0.9 × 0.5 = 0.55 of 20 across 400. + assert!((lin - 400.0 * 11.0).abs() / (400.0 * 11.0) < 0.06, "{lin}"); + assert!(soft > lin * 1.15 && firm < lin * 0.85, "{soft} {lin} {firm}"); + // A curve of points: flat at 1 paints full size at any pressure. + let full = area_with(json!([[0, 1], [1, 1]])); + assert!((full - 400.0 * 20.0).abs() / (400.0 * 20.0) < 0.06, "{full}"); + // Pressure off: full size too. + let mut s = blank(); + run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "pressure_size": false})); + assert!((area(&shapes(&s)[0]) - full).abs() < full * 0.01); +} + +#[test] +fn pressure_can_set_the_opacity() { + let pts: Vec<[f32; 3]> = (0..=10).map(|i| [i as f32 * 10.0, 50.0, 0.4]).collect(); + let mut s = blank(); + run(&mut s, "draw.brush", json!({"points": pts, "pressure_opacity": true, "color": "#ff0000"})); + let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[0].fill else { panic!("solid") }; + assert!((c.a - 0.4).abs() < 1e-3, "{}", c.a); + // A mouse (no pressure) paints opaque. + run(&mut s, "draw.brush", json!({"points": [[0, 100], [100, 100]], "pressure_opacity": true})); + let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[1].fill else { panic!("solid") }; + assert_eq!(c.a, 1.0); +} + +#[test] +fn the_paint_brush_draws_a_width_profiled_stroke() { + let mut s = blank(); + s.style.stroke = anicraft_doc::Rgba::hex(0x123456); + let r = run(&mut s, "draw.brush", json!({"points": wave(), "size": 16, "as_stroke": true, "taper_end": 30})); + assert_eq!(r["kind"], "paint_brush"); + let sh = &shapes(&s)[0]; + assert!(sh.fill.is_none(), "a line, not a fill"); + let st = sh.stroke.as_ref().unwrap(); + assert_eq!((st.width, st.color), (16.0, anicraft_doc::Rgba::hex(0x123456)), "the brush's size in the stroke colour"); + let prof = st.profile.as_ref().expect("pressure and a taper make a profile"); + let n = prof.points().len(); + assert!((3..=anicraft_doc::MAX_WIDTH_POINTS).contains(&n), "{n} width points"); + assert_eq!(r["width_points"], n); + // Thin at the light start, full in the middle, tapered to a point at the end. + let (l0, _) = prof.at(0.0); + let (lm, rm) = prof.at(0.5); + let (l1, _) = prof.at(1.0); + assert!(l0 < 0.5 && lm > 0.9 && (lm - rm).abs() < 1e-6 && l1 < 0.1, "{l0} {lm} {l1}"); + // The Width tool edits it afterwards. + let id = r["element"].as_u64().unwrap(); + run(&mut s, "stroke.set_width_point", json!({"id": id, "t": 0.5, "left": 3, "right": 3})); + let sh = &shapes(&s)[0]; + assert!(sh.stroke.as_ref().and_then(|st| st.profile.as_ref()).is_some_and(|p| p.at(0.5).0 > 2.9)); + // A mouse stroke with no taper is a plain line of one width (it merges off Object Drawing). + let mut s = blank(); + run(&mut s, "draw.object_drawing", json!({"on": false})); + let r = run(&mut s, "draw.brush", json!({"points": [[0, 0], [50, 10], [100, 0]], "as_stroke": true})); + assert_eq!(r["merged"], true); + assert!(shapes(&s).iter().all(|sh| sh.stroke.as_ref().is_none_or(|st| st.profile.is_none()))); + // One point is no line. + assert!(blank().execute("draw.brush", &json!({"points": [[5, 5]], "as_stroke": true})).is_err()); +} + +#[test] +fn user_brushes_are_saved_listed_renamed_and_deleted() { + let mut s = blank(); + let v = run(&mut s, "brush.preset_list", json!({})); + assert_eq!(v["presets"].as_array().map(Vec::len), Some(BUILTIN.len())); + assert_eq!(v["presets"][0]["key"], "pencil"); + let v = run(&mut s, "brush.preset_save", json!({"name": "Wet Ink", "from": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]})); + assert_eq!((v["name"].as_str(), v["replaced"].as_bool()), (Some("Wet Ink"), Some(false))); + let list = run(&mut s, "brush.preset_list", json!({})); + let mine = &list["presets"][BUILTIN.len()]; + assert_eq!((mine["name"].as_str(), mine["builtin"].as_bool(), mine["size"].as_f64(), mine["taper_end"].as_f64()), (Some("Wet Ink"), Some(false), Some(9.0), Some(18.0)), "from the ink pen, size changed"); + // Painting with it by name equals painting with its settings. + run(&mut s, "draw.brush", json!({"points": wave(), "preset": "wet ink"})); + let mut t = blank(); + run(&mut t, "draw.brush", json!({"points": wave(), "preset": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]})); + assert_eq!(shapes(&s)[0].path, shapes(&t)[0].path); + assert!(s.execute("draw.brush", &json!({"points": wave(), "preset": "nope"})).is_err()); + // Brushes aren't the document's: saving and renaming leave it as it is. + let doc = s.doc.clone(); + run(&mut s, "brush.preset_rename", json!({"name": "Wet Ink", "to": "Dry Ink"})); + run(&mut s, "brush.preset_save", json!({"name": "Spare"})); + run(&mut s, "brush.preset_delete", json!({"name": "Spare", "confirm": true})); + assert!(s.doc == doc); + assert!(s.execute("brush.preset_save", &json!({"name": "Marker"})).is_err(), "built-in names are taken"); + // Deleting can't be undone, so it asks first. + assert!(s.confirmation("brush.preset_delete", &json!({"name": "dry ink"})).is_some_and(|c| c.irreversible)); + assert!(s.confirmation("brush.preset_delete", &json!({"name": "nope"})).is_none()); + assert!(s.execute("brush.preset_delete", &json!({"name": "Dry Ink"})).is_err(), "needs confirm"); + run(&mut s, "brush.preset_delete", json!({"name": "Dry Ink", "confirm": true})); + assert!(s.brushes.is_empty()); + // They survive New and Open. + run(&mut s, "brush.preset_save", json!({"name": "Keep"})); + s.replace_document(anicraft_doc::Document::default(), None); + assert_eq!(s.brushes.user().len(), 1); +} + +#[test] +fn brush_sets_export_and_import_as_json() { + crate::vfs::use_memory(); + let mut s = blank(); + assert!(s.execute("brush.preset_export", &json!({"path": "none.json"})).is_err(), "nothing of yours yet"); + run(&mut s, "brush.preset_save", json!({"name": "Grit", "from": "chalk", "jitter": 30})); + run(&mut s, "brush.preset_save", json!({"name": "Dots", "from": "dotted", "spacing": 150})); + let v = run(&mut s, "brush.preset_export", json!({"path": "set.json"})); + assert_eq!(v["brushes"], 2); + let text = crate::vfs::read_to_string(std::path::Path::new("set.json")).unwrap(); + assert!(text.contains("\"format\": \"anicraft-brushes\"") && text.contains("\"Grit\"")); + // Exporting over the file asks first. + assert!(s.confirmation("brush.preset_export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible)); + // Another computer: the set comes in whole; names already there get a number. + let mut t = blank(); + run(&mut t, "brush.preset_save", json!({"name": "Grit"})); + let v = run(&mut t, "brush.preset_import", json!({"path": "set.json"})); + assert_eq!(v["imported"], json!(["Grit 2", "Dots"])); + assert_eq!(t.brushes.find("Grit 2").map(|b| b.jitter), Some(30.0)); + // Built-ins can be exported by name too. + let v = run(&mut s, "brush.preset_export", json!({"path": "two.json", "names": ["chalk", "Dots"], "confirm": true})); + assert_eq!(v["brushes"], 2); + // Junk is refused. + crate::vfs::put(std::path::Path::new("junk.json"), b"{\"format\": 3}".to_vec()).unwrap(); + for bad in [json!({"path": "junk.json"}), json!({"path": "missing.json"}), json!({})] { + assert!(t.execute("brush.preset_import", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn plug_ins_may_list_brushes_but_not_change_them() { + use crate::cmds_plugin::plugin_may_call; + assert!(plugin_may_call("brush.preset_list").is_ok()); + for id in ["brush.preset_save", "brush.preset_rename", "brush.preset_delete", "brush.preset_export", "brush.preset_import"] { + assert!(plugin_may_call(id).is_err(), "{id}"); + } +} + +#[test] +fn previews_are_drawn_by_the_renderer() { + for (key, _) in BUILTIN { + let b = crate::brush_library::builtin(key).unwrap(); + for as_stroke in [false, true] { + let px = crate::cmds_brush::preview(&b, as_stroke, 160, 48, 2.0, anicraft_doc::Rgba::hex(0x000000)).unwrap(); + let rgba = px.to_premul_rgba8(); + let inked = rgba.chunks(4).filter(|p| p[3] > 128).count(); + assert!(inked > 60, "{key} as_stroke {as_stroke}: {inked} pixels"); + assert!(rgba.chunks(4).filter(|p| p[3] == 0).count() > inked, "{key}: mostly transparent"); + } + } + assert!(crate::cmds_brush::preview(&crate::brush_library::BrushPreset::default(), false, 2, 2, 1.0, anicraft_doc::Rgba::hex(0)).is_err()); +} + +/// Measured numbers for ADR 0068: `cargo test --release -p anicraft-engine preset_timings -- --ignored --nocapture`. +#[test] +#[ignore] +fn preset_timings() { + for (key, _) in BUILTIN { + for as_stroke in [false, true] { + let mut ms: Vec = (0..15) + .map(|_| { + let mut s = blank(); + let t = std::time::Instant::now(); + run(&mut s, "draw.brush", json!({"points": wave(), "preset": key, "as_stroke": as_stroke})); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(); + ms.sort_by(f64::total_cmp); + let (sh, _) = painted(key, json!({"as_stroke": as_stroke})); + eprintln!("{key:12} stroke {as_stroke:5}: median {:6.2} ms, {} anchors", ms[7], sh.path.anchors().len()); + } + } + let b = crate::brush_library::builtin("chalk").unwrap(); + let t = std::time::Instant::now(); + for _ in 0..10 { + crate::cmds_brush::preview(&b, false, 300, 80, 2.0, anicraft_doc::Rgba::hex(0)).unwrap(); + } + eprintln!("chalk preview 300x80: {:.2} ms each", t.elapsed().as_secs_f64() * 100.0); +} + +#[test] +fn simplified_profiles_stay_close_and_small() { + let pts: Vec<(f32, f32)> = (0..256).map(|i| i as f32 / 255.0).map(|t| (t, 0.5 + 0.4 * (t * 9.0).sin())).collect(); + let kept = crate::cmds_brush::simplify_profile(&pts, 0.015, 64); + assert!(kept.len() <= 64 && kept.len() > 8, "{}", kept.len()); + assert_eq!((kept.first(), kept.last()), (pts.first(), pts.last())); + let noisy: Vec<(f32, f32)> = (0..256).map(|i| (i as f32 / 255.0, if i % 2 == 0 { 0.1 } else { 1.0 })).collect(); + assert!(crate::cmds_brush::simplify_profile(&noisy, 0.015, 64).len() <= 64); +} diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index dcd3d2b3..c748001c 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -196,7 +196,7 @@ fn bad_params_are_errors() { json!({"points": [[0, 0]], "size": 0}), json!({"points": [[0, 0]], "size": 1e9}), json!({"points": [[0, 0]], "shape": "star"}), - json!({"points": [[0, 0]], "mode": "inside"}), + json!({"points": [[0, 0]], "mode": "outside"}), json!({"points": [[0, 0]], "roundness": 1}), json!({"points": [[0, 0]], "smoothing": 101}), json!({"points": [[0, 0], [1e7, 0]]}), diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index f9dc5dff..fe106894 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -17,11 +17,11 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y}]} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), + c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output, the sounds it started ({tick, sound, name, sync, gain}; buttons' as the pointer changes their state) and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn), c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set), c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear), c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list), - c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance for actions", true, set_name), + c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance, or a dynamic or input text field, for actions and scripts", true, set_name), ] } @@ -37,7 +37,7 @@ pub(crate) enum Scope { /// A timeline commands address: a scene's (the one being edited) or a library symbol's. fn timeline_mut(s: &mut Session, symbol: Option, scope: Scope) -> Result<&mut Timeline> { match symbol { - None => Ok(crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)), + None => crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing), Some(id) => { let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip { @@ -232,7 +232,14 @@ fn set_name(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("“{name}” can't be an instance name: use letters, digits, _ or $ (no spaces), not starting with a digit, at most {} characters", actions::MAX_NAME_CHARS))); } let e = instance_mut(s, p)?.clone(); - interactive_kind(s, &e)?; + // Dynamic and input text fields take names too (ADR 0066); static text has none. + match &e.kind { + ElementKind::Text(t) if t.field.is_some() => {} + ElementKind::Text(_) => return Err(EngineError::State("static text has no instance name: make it dynamic or input text first (Properties › Text type)".into())), + _ => { + interactive_kind(s, &e)?; + } + } let el = instance_mut(s, p)?; el.name = name.clone(); Ok(json!({"element": el.id.0, "name": name})) @@ -241,6 +248,8 @@ fn set_name(s: &mut Session, p: &Value) -> Result { /// Most steps and events of a headless test. const MAX_TEST_STEPS: u32 = 10_000; const MAX_TEST_EVENTS: usize = 10_000; +/// Most started sounds `control.test_movie` lists (the rest are counted). +const MAX_TEST_SOUNDS: usize = 10_000; fn test_movie(s: &mut Session, p: &Value) -> Result { let fps = s.doc.stage.fps.max(1.0); @@ -259,16 +268,34 @@ fn test_movie(s: &mut Session, p: &Value) -> Result { } Some(_) => return Err(EngineError::Param("param 'events' must be a list".into())), } + let seed = opt_u64(p, "seed")?.unwrap_or(anicraft_doc::player::DEFAULT_SEED); let mut runner = ScriptRunner::new(&s.plugins); - let mut movie = Movie::start(&s.doc, &mut runner); + let mut movie = Movie::start_seeded(&s.doc, seed, &mut runner); + // The sounds the movie started (buttons' under the pointer too, ADR 0057), in order. + let mut sounds: Vec = Vec::new(); + let mut more = 0usize; + let mut heard = |movie: &mut Movie, doc: &anicraft_doc::Document| { + for (tick, st) in movie.take_sounds() { + if sounds.len() >= MAX_TEST_SOUNDS { + more += 1; + continue; + } + let name = doc.sound(st.sound.sound).map(|x| x.name.clone()); + sounds.push(json!({"tick": tick, "sound": st.sound.sound.0, "name": name, "sync": st.sound.sync.key(), "gain": st.gain})); + } + }; + heard(&mut movie, &s.doc); for tick in 1..=u64::from(frames) { let events: Vec<_> = timed.iter().filter(|(t, _)| *t == tick).flat_map(|(_, e)| e.iter().copied()).collect(); movie.step(&s.doc, &events, &mut runner); + heard(&mut movie, &s.doc); } let nodes = anicraft_doc::player::tree(&s.doc, &movie.state); Ok(json!({ "steps": frames, "output": movie.output.iter().map(|(t, l)| json!({"tick": t, "line": l})).collect::>(), + "sounds": sounds, + "more_sounds": more, "state": state_view(&s.doc, &movie.state, &nodes, None), "script_runs": runner.runs, "script_fuel": runner.fuel_used, diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index d18defb7..df5df123 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -12,6 +12,7 @@ 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::skin::{self, Binding, Influence, MAX_SKIN_POINTS, Skin}; 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}; @@ -23,16 +24,24 @@ pub fn specs() -> 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)", + "{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), 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.add_in_shape", + "Add Bone in Shape", + "{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones", + true, + add_in_shape, + ), + c("bone.bind", "Bind Points", "{bone, points?: [point index…] (default every point; see bone.info with points), mode?: \"only\" (the points follow just this bone; default) | \"add\" (they share it with the bones they follow) | \"remove\" | \"auto\" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone", true, bind), 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), + c("bone.info", "Armatures", "{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned; a shape armature's shape, how many points each bone moves, and with points the shape's points (stage px) and the bones each follows", false, info), ] } @@ -119,6 +128,32 @@ fn rebake(layer: &mut Layer) { } } +/// A new armature layer at `index` holding `arm` and `elements` on one pose that spans from the +/// keyframe of `from` at the playhead to the end of the timeline (a classic tween on it, so +/// poses keyed later tween). +fn armature_layer(s: &mut Session, from: LayerId, index: usize, elements: Vec>, arm: Armature) -> Result { + let (start, end) = s.timeline().layer(from).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()); + if s.timeline().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(arm)); + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = elements; + k.tween = Some(Tween::default()); + layer.keyframes = vec![Arc::new(k)]; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; + layer.parent = tl.container_at(index, LayerKind::Armature); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); + tl.repair_masks(); + Ok(lid) +} + fn add(s: &mut Session, p: &Value) -> Result { 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")?); @@ -158,10 +193,12 @@ fn add(s: &mut Session, p: &Value) -> Result { 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. + // The joint. An instance that already hangs from a bone has one joint, that bone's end: every + // bone from it starts there, wherever on the instance the drag began, so the chain stays + // joined end to start and turns about the joints it shows, as in Animate (#239). A root's + // bones start where given (a torso's shoulders and hips), else at 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 head = into_from.or(head).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() { @@ -184,30 +221,10 @@ fn add(s: &mut Session, p: &Value) -> Result { 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.timeline().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()); + // The first bone: both instances move to a new armature layer above them. take_off(s, f.layer, from)?; - if s.timeline().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 = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); - layer.parent = tl.container_at(index, LayerKind::Armature); - tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); - tl.repair_masks(); - lid + let arm = Armature { bones: vec![bone], skin: None }; + armature_layer(s, f.layer, f.index.min(t.index), vec![f.el.clone(), t.el.clone()], arm)? } }; s.layer = lid; @@ -229,7 +246,10 @@ fn remove(s: &mut Session, p: &Value) -> Result { let mut left = (*arm).clone(); left.bones.retain(|b| !gone.contains(&b.id)); let dissolve = left.is_empty(); - let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; + // A shape armature's bones move no instances: only without bones does its shape go. + let skinned = arm.skin.is_some(); + skin::rebind(&mut left); + let freed: Vec = if dissolve { arm.members() } else if skinned { Vec::new() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; let tl = s.timeline(); 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()))?; @@ -244,7 +264,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); k.elements = shown; freed_layer.keyframes = vec![Arc::new(k)]; - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; if dissolve { tl.layers.retain(|l| l.id != lid); tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer)); @@ -257,12 +277,15 @@ fn remove(s: &mut Session, p: &Value) -> Result { } l.armature = Some(Arc::new(left)); rebake(l); - tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer)); + if !skinned { + 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::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": new_id.0, "armature_removed": dissolve})) + let layer = if dissolve || !skinned { new_id } else { lid }; + Ok(json!({"removed": gone.iter().map(|b| b.0).collect::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": layer.0, "armature_removed": dissolve})) } fn set_limits(s: &mut Session, p: &Value) -> Result { @@ -411,6 +434,7 @@ fn solve(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let only = opt_u64(p, "layer")?.map(LayerId); + let with_points = opt_bool(p, "points")?.unwrap_or(false); let tl = s.timeline(); let deg = |v: f32| v.to_degrees(); let pt = |v: Vec2| json!([v.x, v.y]); @@ -435,11 +459,179 @@ fn info(s: &mut Session, p: &Value) -> Result { "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, + "points": arm.skin.as_ref().map(|k| k.points.iter().filter(|x| x.weight(b.id) > 0.0).count()), }) }) .collect(); - Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones})) + let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0)}); + if with_points && let Some(k) = &arm.skin { + out["points"] = json!(skin::points_shown(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::>(), "manual": b.manual})).collect::>()); + } + Some(out) }) .collect(); Ok(json!({"frame": frame, "armatures": list})) } + +fn add_in_shape(s: &mut Session, p: &Value) -> Result { + let shape = opt_u64(p, "shape")?.map(ElementId); + let parent = opt_u64(p, "parent")?.map(BoneId); + let head = opt_point(p, "head")?; + let tail = opt_point(p, "tail")?.ok_or_else(|| EngineError::Param("param 'tail' ([x, y], stage px: where the bone ends) is required".into()))?; + 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"))); + } + let frame = s.frame; + // The armature the bone joins (none yet for the first bone), the shape, the node the bone + // starts on, and its joint on the stage. + let (existing, found, from, head) = match (parent, shape) { + (Some(b), _) => { + let (lid, arm) = find_bone(s, b)?; + let sh = arm.skin_shape().ok_or_else(|| EngineError::State("that bone joins symbol instances: continue it with bone.add".into()))?; + if shape.is_some_and(|x| x != sh) { + return Err(EngineError::Param("that bone is in another shape".into())); + } + let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the armature's shape isn't on the stage at frame {}", frame + 1)))?; + let node = arm.bone(b).map(|x| x.child).ok_or_else(|| EngineError::State("no such bone".into()))?; + let end = s.timeline().layer(lid).and_then(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + armature::bones_at(&arm, &els, &pose).into_iter().find(|g| g.id == b).map(|g| g.tail) + }); + let head = head.or(end).ok_or_else(|| EngineError::State(format!("the bone isn't on the stage at frame {}", frame + 1)))?; + (Some((lid, arm)), f, node, head) + } + (None, Some(sh)) => { + let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("no shape with id {} on the stage at frame {}", sh.0, frame + 1)))?; + let ElementKind::Shape(shp) = &f.el.kind else { + return Err(EngineError::State("bones inside a shape need a shape: for symbol instances, drag from one to another (bone.add)".into())); + }; + let head = head.ok_or_else(|| EngineError::Param("param 'head' ([x, y], stage px: where the bone starts, inside the shape) is required".into()))?; + let existing = match f.kind { + LayerKind::Normal => None, + LayerKind::Armature => { + let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.skin_shape() == Some(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?; + Some((f.layer, arm)) + } + _ => return Err(EngineError::State("bones go inside shapes on normal layers (not on guide or mask layers)".into())), + }; + // A bone starts inside the shape (on its fill, or on its line). + let reach = shp.stroke.as_ref().map_or(0.0, |k| k.width * 0.5 * f.el.transform.mean_scale()) + 2.0; + let inside = (shp.fill.is_some() && shp.path.contains(head, &f.el.transform, shp.fill_rule)) || shp.path.distance_to_edge(head, &f.el.transform) <= reach; + if !inside { + return Err(EngineError::State("start the bone inside the shape".into())); + } + (existing, f, sh, head) + } + (None, None) => return Err(EngineError::Param("give 'shape' (the shape's id, for the first bone) or 'parent' (a bone to continue from)".into())), + }; + unlocked(s, found.layer)?; + if head.distance(tail) < 1.0 { + return Err(EngineError::Param("a bone needs a length: drag from its joint to its end".into())); + } + let ElementKind::Shape(shp) = &found.el.kind else { return Err(EngineError::State("that isn't a shape".into())) }; + // The node the bone starts on, as placed at the playhead: the bone's points go back through + // it to the shape as drawn (a new bone is at rest in every pose). + let node = match &existing { + Some((lid, arm)) => { + let l = s.timeline().layer(*lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State("the armature isn't on this frame".into()))?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + armature::place(arm, &els, &pose).get(&from).copied() + } + None => Some(found.el.transform), + }; + let inv = node.and_then(|m| m.inverse()).ok_or_else(|| EngineError::State("a shape scaled to nothing can't hold a bone".into()))?; + let (h, t) = (inv.apply(head), inv.apply(tail)); + if !(h.x.is_finite() && h.y.is_finite() && t.x.is_finite() && t.y.is_finite()) { + return Err(EngineError::State("a shape scaled to nothing can't hold a bone".into())); + } + if existing.as_ref().is_some_and(|(_, a)| a.bones.len() >= MAX_BONES) { + return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones"))); + } + if existing.is_none() && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS { + return Err(EngineError::State(format!("bones go inside shapes of at most {MAX_SKIN_POINTS} points: simplify it first (Modify › Shape › Optimize)"))); + } + let id = BoneId(s.doc.alloc_id()); + let child = ElementId(s.doc.alloc_id()); + let bone = Bone { id, name, parent: from, child, head: h, tail: t, rest: Affine::IDENTITY, limits: None, pinned: false }; + let (lid, created) = match existing { + Some((lid, arm)) => { + let mut arm = (*arm).clone(); + arm.bones.push(bone); + skin::rebind(&mut arm); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + (lid, false) + } + None => { + // An armature's shape is an object: merge drawing (ADR 0031) no longer cuts it. + let mut el = (*found.el).clone(); + if let ElementKind::Shape(x) = &mut el.kind { + x.merge = false; + } + let mut arm = Armature { bones: vec![bone], skin: Some(Skin::new(found.el.id, shp.path.clone())) }; + skin::rebind(&mut arm); + take_off(s, found.layer, found.el.id)?; + (armature_layer(s, found.layer, found.index, vec![Arc::new(el)], arm)?, true) + } + }; + s.layer = lid; + s.selection.clear(); + let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).and_then(|a| a.skin.as_ref()).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count()); + Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound})) +} + +fn bind(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let mode = opt_str(p, "mode")?.unwrap_or("only"); + if !matches!(mode, "only" | "add" | "remove" | "auto") { + return Err(EngineError::Param("param 'mode' must be \"only\", \"add\", \"remove\" or \"auto\"".into())); + } + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let n = arm.skin.as_ref().map(|k| k.points.len()).ok_or_else(|| EngineError::State("that bone joins symbol instances: only bones inside a shape bind its points".into()))?; + let bad = || EngineError::Param(format!("param 'points' must be a list of point indices below {n} (see bone.info with points)")); + let points: Vec = match p.get("points") { + None | Some(Value::Null) => (0..n).collect(), + Some(Value::Array(a)) if a.len() <= MAX_SKIN_POINTS => a.iter().map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n).ok_or_else(bad)).collect::>()?, + Some(_) => return Err(bad()), + }; + let mut arm = (*arm).clone(); + let segments = skin::rest_segments(&arm); + let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) }; + let anchors = skin::anchors(&k.rest); + let mut changed = 0usize; + for i in points { + let (Some(b), Some(&at)) = (k.points.get_mut(i), anchors.get(i)) else { continue }; + let next = match mode { + "only" => Binding { bones: vec![Influence(id, 1.0)], manual: true }, + "add" if b.weight(id) > 0.0 => continue, + "add" => { + // An equal share with the bones the point already follows. + let share = 1.0 / (b.bones.len() + 1) as f32; + let mut x = Binding { bones: b.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - share))).collect(), manual: true }; + x.bones.push(Influence(id, share)); + x.normalize(|_| true); + x + } + "remove" => { + let mut x = Binding { bones: b.bones.iter().copied().filter(|i| i.0 != id).collect(), manual: true }; + x.normalize(|_| true); + x + } + _ => skin::auto_binding(&segments, at), + }; + if *b != next { + *b = next; + changed += 1; + } + } + let bound = k.points.iter().filter(|b| b.weight(id) > 0.0).count(); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(json!({"bone": id.0, "changed": changed, "bound": bound})) +} diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index df6e1423..d26a71f8 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -2,26 +2,35 @@ //! tip sweeps, in the fill colour. Off Object Drawing it is a raw shape that merges with the //! drawing (ADR 0031), placed by the paint mode. -use crate::cmds_draw::{MAX_EXTENT, object_param}; +use crate::brush_library::{BUILTIN, BrushLibrary, BrushPreset, MAX_FILE_BYTES, MAX_USER_PRESETS, builtin, builtin_hint, clean_name}; +use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param}; use crate::merge::{self, Order}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Paint, Shape}; -use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tip, TipShape, outline}; -use anicraft_geom::{Affine, FillRule, PathCmd, Vec2}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile}; +use anicraft_geom::planar; +use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tip, TipShape, centre_stroke, outline_shaped}; +use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; pub fn specs() -> Vec { - vec![CommandSpec { - id: "draw.brush", - label: "Brush Stroke", - menu: "", - shortcut: None, - params: "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), mode?: normal|fills|behind (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas), color? (default: the fill colour), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", - mutates: true, - run: draw_brush, - }] + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c( + "draw.brush", + "Brush Stroke", + "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", + true, + draw_brush as crate::RunFn, + ), + c("brush.preset_list", "Brush Presets", "{} the built-in brushes and yours, with their settings", false, preset_list), + c("brush.preset_save", "Save Brush", "{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)", false, preset_save), + c("brush.preset_rename", "Rename Brush", "{name, to}", false, preset_rename), + c("brush.preset_delete", "Delete Brush", "{name} deletes a brush of your own (asks first: it can't be undone)", false, preset_delete), + c("brush.preset_export", "Export Brushes", "{path, names? (default: all yours)} writes your brushes to a brush set file (JSON)", false, preset_export), + c("brush.preset_import", "Import Brushes", "{path} adds the brushes in a brush set file to yours (a name you have already gets a number)", false, preset_import), + ] } /// Brush sizes, in stage units. @@ -34,16 +43,22 @@ pub enum PaintMode { Normal, Fills, Behind, + /// Only inside the selected fills (ADR 0080). + Selection, + /// Only inside the fill the stroke starts on (ADR 0080). + Inside, } impl PaintMode { - pub const ALL: [PaintMode; 3] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind]; + pub const ALL: [PaintMode; 5] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind, PaintMode::Selection, PaintMode::Inside]; pub fn key(self) -> &'static str { match self { PaintMode::Normal => "normal", PaintMode::Fills => "fills", PaintMode::Behind => "behind", + PaintMode::Selection => "selection", + PaintMode::Inside => "inside", } } pub fn label(self) -> &'static str { @@ -51,6 +66,8 @@ impl PaintMode { PaintMode::Normal => "Paint Normal", PaintMode::Fills => "Paint Fills", PaintMode::Behind => "Paint Behind", + PaintMode::Selection => "Paint Selection", + PaintMode::Inside => "Paint Inside", } } pub fn hint(self) -> &'static str { @@ -58,12 +75,15 @@ impl PaintMode { PaintMode::Normal => "Paints over lines and fills on the layer.", PaintMode::Fills => "Paints over fills and empty areas, leaving lines alone.", PaintMode::Behind => "Paints only empty areas, behind the lines and fills on the layer.", + PaintMode::Selection => "Paints only inside the selected fills, leaving lines alone.", + PaintMode::Inside => "Paints only inside the fill where the stroke starts, leaving lines alone. Started on empty stage, it paints only the empty area there.", } } fn order(self) -> Order { match self { PaintMode::Normal => Order::Top, - PaintMode::Fills => Order::UnderLines, + // Clipped paint never covers a line either (ADR 0080). + PaintMode::Fills | PaintMode::Selection | PaintMode::Inside => Order::UnderLines, PaintMode::Behind => Order::Behind, } } @@ -72,6 +92,49 @@ impl PaintMode { } } +/// Where Paint Selection and Paint Inside may paint (ADR 0080). +enum Region { + /// Inside this outline (keyframe space, even-odd). + Clip(Path), + /// Only empty areas: Paint Inside started on open, empty stage (as Paint Behind). + Empty, + /// Nowhere, and why. + Nowhere(&'static str), +} + +const TOO_MUCH: &str = "there is too much artwork there to paint inside at once; paint a smaller area"; + +/// The region a clipped paint mode paints in: the union of the selected shapes' fills on the +/// active layer (Paint Selection), or the topmost fill under `start` there, else the empty area +/// the lines and fills close off around it (Paint Inside). Merged paint lies under drawing +/// objects, so off Object Drawing only raw fills count (an object is edited inside it). +fn paint_region(s: &mut Session, mode: PaintMode, start: Vec2, object: bool) -> Result { + let els = s.editable_keyframe()?.elements.clone(); + let filled = |e: &Element| match &e.kind { + ElementKind::Shape(sh) if sh.fill.is_some() && (object || sh.merge) => Some((sh.path.transformed(&e.transform), sh.fill_rule)), + _ => None, + }; + let too_much = || EngineError::State(TOO_MUCH.into()); + if mode == PaintMode::Selection { + let here = s.layer; + let picked: Vec<(Path, FillRule)> = els.iter().filter(|e| s.selection.contains(here, e.id)).filter_map(|e| filled(e)).collect(); + if picked.is_empty() { + return Ok(Region::Nowhere(if s.selection.on(here).is_empty() { "select the fills to paint inside first" } else { "the selection has no fills to paint inside" })); + } + let refs: Vec<(&Path, FillRule)> = picked.iter().map(|(p, r)| (p, *r)).collect(); + return Ok(Region::Clip(planar::union(&refs).ok_or_else(too_much)?)); + } + let on = els.iter().rev().find_map(|e| filled(e).filter(|(p, r)| p.contains(start, &Affine::IDENTITY, *r))); + if let Some((path, rule)) = on { + // The fill's own rule, as even-odd loops. + return Ok(Region::Clip(planar::union(&[(&path, rule)]).ok_or_else(too_much)?)); + } + Ok(match merge::enclosed_area(&els, start) { + Some(area) => Region::Clip(area), + None => Region::Empty, + }) +} + pub(crate) fn samples(p: &Value) -> Result> { let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into()); let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?; @@ -132,49 +195,335 @@ pub(crate) fn tip(p: &Value) -> Result { Ok(Tip { shape, size, angle, roundness: roundness / 100.0 }) } +/// The brush a command paints with: its `preset` (or the plain brush) with the params' own +/// settings on top. +pub fn brush_param(s: &Session, p: &Value) -> Result { + let base = match opt_str(p, "preset")? { + Some(name) => s.brushes.find(name).ok_or_else(|| EngineError::Param(format!("no brush named '{name}' (brush.preset_list lists them)")))?, + None => BrushPreset::default(), + }; + base.with_params(p) +} + +/// The stroke's opacity factor when pressure drives it: the average mapped pressure. +pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 { + if !b.pressure_opacity || pts.is_empty() { + return 1.0; + } + (pts.iter().map(|x| b.curve.map(x.pressure)).sum::() / pts.len() as f32).clamp(0.05, 1.0) +} + fn draw_brush(s: &mut Session, p: &Value) -> Result { let pts = bounded_samples(p)?; - let tip = tip(p)?; + let b = brush_param(s, p)?; + let tip = b.tip(); let size = tip.size; - let smoothing = ranged(p, "smoothing", 0.0..=100.0, 50.0)?; + let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false); let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?; let mode_key = opt_str(p, "mode")?.unwrap_or("normal"); - let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills or behind)")))?; - let color = opt_color(p, "color")?.unwrap_or(s.style.fill); + let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?; + let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill }); + let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color }; let object = object_param(s, p)?; + // Pressure through the curve (ADR 0068) before it sizes the tip. + let pts: Vec = pts.iter().map(|x| Sample { at: x.at, pressure: b.size_pressure(x.pressure) }).collect(); // Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50 // the centre line may wander 3.3 screen points from the hand, at 0 a third of a point. // The outline is fitted within a third of a screen point, or a hundredth of the size for // small brushes (so a small dab is still round). - let path = outline(&pts, &tip, unit * (0.3 + smoothing * 0.06), (unit * 0.35).min(size * 0.01)); + let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01)); + if as_stroke { + return paint_stroke(s, &pts, &b, smoothing, tol, color, object); + } + let start = pts.first().map_or(Vec2::ZERO, |x| x.at); + let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol); if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { return Err(EngineError::Param("the stroke is too small to paint".into())); } + // Paint Selection and Paint Inside (ADR 0080): the outline clipped to the region, then + // merged as usual. Nothing changes when nothing is painted (no keyframe made, no step). + let mut order = mode.order(); + // Paint Selection keeps the selection: the region, to select again after the merge. + let mut kept_region: Option = None; + if matches!(mode, PaintMode::Selection | PaintMode::Inside) { + let before = s.doc.clone(); + let region = paint_region(s, mode, start, object); + let clipped = match region { + Ok(Region::Clip(r)) => { + let c = planar::intersect(&path, FillRule::EvenOdd, &r).ok_or_else(|| EngineError::State(TOO_MUCH.into())); + kept_region = (mode == PaintMode::Selection).then_some(r); + Some(c) + } + Ok(Region::Empty) => None, + Ok(Region::Nowhere(why)) => { + s.doc = before; + return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why})); + } + Err(e) => Some(Err(e)), + }; + match clipped { + None => order = Order::Behind, + Some(Err(e)) => { + s.doc = before; + return Err(e); + } + Some(Ok(p)) if !p.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) => { + s.doc = before; + let why = if mode == PaintMode::Selection { "the stroke doesn't reach the selected fills" } else { "nothing to paint there" }; + return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why})); + } + Some(Ok(p)) => path = p, + } + } let c = path.bounds().center(); + let local = path.transformed(&Affine::translate(-c.x, -c.y)); + // A gradient or bitmap in the fill swatch paints too, locked or fitted (ADR 0074), unless a + // colour was given or pressure sets the opacity. + let fill = match &s.style.fill_paint { + Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()), + _ => Paint::Solid(color), + }; let id = ElementId(s.doc.alloc_id()); let el = Element { id, name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(path.transformed(&Affine::translate(-c.x, -c.y))), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), }; if s.editable_keyframe()?.elements.len() >= 100_000 { return Err(EngineError::State("too many elements on this keyframe".into())); } if object { let kf = s.editable_keyframe()?; - match mode { + match order { // Behind everything on the layer. - PaintMode::Behind => kf.elements.insert(0, Arc::new(el)), - PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)), + Order::Behind => kf.elements.insert(0, Arc::new(el)), + Order::Top | Order::UnderLines => kf.elements.push(Arc::new(el)), + } + // Paint Selection: the selected objects stay selected, for the next stroke. + if kept_region.is_none() { + s.select_only([id]); } - s.select_only([id]); return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false})); } - let merged = merge::merge_in_order(s, vec![el], mode.order())?; - s.select_only(merged); - let ids: Vec = s.selection.id_list(); + let merged = merge::merge_in_order(s, vec![el], order)?; + let ids: Vec = merged.iter().map(|e| e.0).collect(); + match &kept_region { + // Paint Selection: what lies in the region (the selected fills' pieces and the paint) + // stays selected, for the next stroke. + Some(region) => { + let inside = pieces_in(s, region); + s.select_only(inside); + } + None => s.select_only(merged), + } Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true})) } + +/// The raw fills on the active keyframe that cover part of `region` (keyframe space, even-odd). +fn pieces_in(s: &mut Session, region: &Path) -> Vec { + let Ok(kf) = s.editable_keyframe() else { return Vec::new() }; + let bounds = region.bounds(); + kf.elements + .iter() + .filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some() && !sh.path.bounds().transformed(&e.transform).intersect(&bounds).is_empty())) + .filter(|e| match &e.kind { + ElementKind::Shape(sh) => planar::intersect(&sh.path.transformed(&e.transform), sh.fill_rule, region).is_some_and(|p| !p.is_empty()), + _ => false, + }) + .map(|e| e.id) + .collect() +} + +/// Width points a Paint Brush stroke's profile is simplified from (evenly along its length). +const PROFILE_SAMPLES: usize = 256; +/// How closely the simplified profile follows the brush's widths (a factor of the size). +const PROFILE_TOLERANCE: f32 = 0.015; + +/// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the +/// stroke colour, its width profile following the pressure and tapers, so the Width tool edits +/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's. +fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result { + let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES); + if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { + return Err(EngineError::Param("the stroke is too short to draw a line".into())); + } + let kept = simplify_profile(&factors, PROFILE_TOLERANCE, MAX_WIDTH_POINTS); + let profile = WidthProfile::new(kept.iter().map(|(t, f)| WidthPoint::new(*t, *f, *f)).collect()); + let stroke = Stroke::new(color, b.size).with_profile(profile); + let c = path.bounds().center(); + let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), object)?; + v["width_points"] = json!(kept.len()); + Ok(v) +} + +/// The fewest of `pts` (`(t, factor)`, sorted) that stay within `tol` of the rest by straight +/// lines between them (Ramer–Douglas–Peucker), widening the tolerance until at most `max` are +/// kept. The ends always stay. +pub fn simplify_profile(pts: &[(f32, f32)], tol: f32, max: usize) -> Vec<(f32, f32)> { + let n = pts.len(); + if n <= 2 { + return pts.to_vec(); + } + let mut tol = tol.max(1e-4); + for _ in 0..12 { + let mut keep = vec![false; n]; + if let Some(k) = keep.first_mut() { + *k = true; + } + if let Some(k) = keep.last_mut() { + *k = true; + } + let mut stack = vec![(0usize, n - 1)]; + while let Some((a, z)) = stack.pop() { + let (Some(pa), Some(pz)) = (pts.get(a), pts.get(z)) else { continue }; + let mut worst = (0.0f32, a); + for i in a + 1..z { + let Some(q) = pts.get(i) else { continue }; + let t = if pz.0 - pa.0 > 1e-9 { (q.0 - pa.0) / (pz.0 - pa.0) } else { 0.0 }; + let d = (q.1 - (pa.1 + (pz.1 - pa.1) * t)).abs(); + if d > worst.0 { + worst = (d, i); + } + } + if worst.0 > tol { + if let Some(k) = keep.get_mut(worst.1) { + *k = true; + } + stack.push((a, worst.1)); + stack.push((worst.1, z)); + } + } + let out: Vec<(f32, f32)> = pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect(); + if out.len() <= max.max(2) { + return out; + } + tol *= 1.6; + } + // Still too many (a wildly varying pressure): evenly spaced points. + let m = max.max(2); + (0..m).filter_map(|i| pts.get(i * (n - 1) / (m - 1))).copied().collect() +} + +// ----- the brush library (ADR 0068) --------------------------------------------------------- + +fn preset_json(p: &BrushPreset, key: Option<&str>) -> Value { + let mut v = p.params(); + v["name"] = json!(p.name); + v["builtin"] = json!(key.is_some()); + if let Some(k) = key { + v["key"] = json!(k); + v["hint"] = json!(builtin_hint(k)); + } + v +} + +fn preset_list(s: &mut Session, _: &Value) -> Result { + let mut list: Vec = BUILTIN.iter().filter_map(|(k, _)| builtin(k).map(|p| preset_json(&p, Some(k)))).collect(); + list.extend(s.brushes.user().iter().map(|p| preset_json(p, None))); + Ok(json!({"presets": list, "yours": s.brushes.user().len()})) +} + +fn preset_save(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let base = match opt_str(p, "from")? { + Some(from) => s.brushes.find(from).ok_or_else(|| EngineError::Param(format!("no brush named '{from}'")))?, + None => BrushPreset::default(), + }; + let b = BrushPreset { name: name.to_string(), ..base.with_params(p)? }; + let replaced = s.brushes.save(b)?; + let saved = clean_name(name).and_then(|n| s.brushes.position(&n)).and_then(|i| s.brushes.user().get(i)).map(|x| x.name.clone()); + Ok(json!({"name": saved, "replaced": replaced, "yours": s.brushes.user().len()})) +} + +fn preset_rename(s: &mut Session, p: &Value) -> Result { + let to = s.brushes.rename(str_req(p, "name")?, str_req(p, "to")?)?; + Ok(json!({"name": to})) +} + +fn preset_delete(s: &mut Session, p: &Value) -> Result { + let gone = s.brushes.delete(str_req(p, "name")?)?; + Ok(json!({"deleted": gone.name, "yours": s.brushes.user().len()})) +} + +fn preset_export(s: &mut Session, p: &Value) -> Result { + let path = std::path::PathBuf::from(str_req(p, "path")?); + let chosen: Vec = match p.get("names") { + None | Some(Value::Null) => s.brushes.user().to_vec(), + Some(Value::Array(names)) => names + .iter() + .take(MAX_USER_PRESETS * 2) + .map(|n| { + let n = n.as_str().ok_or_else(|| EngineError::Param("param 'names' must be a list of brush names".into()))?; + s.brushes.find(n).ok_or_else(|| EngineError::Param(format!("no brush named '{n}'"))) + }) + .collect::>()?, + Some(_) => return Err(EngineError::Param("param 'names' must be a list of brush names".into())), + }; + if chosen.is_empty() { + return Err(EngineError::State("there are no brushes of your own to export yet (save one first)".into())); + } + let text = BrushLibrary::file_json(&chosen); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "brushes": chosen.len(), "bytes": text.len()})) +} + +fn preset_import(s: &mut Session, p: &Value) -> Result { + let path = std::path::PathBuf::from(str_req(p, "path")?); + if crate::vfs::len(&path)? > MAX_FILE_BYTES { + return Err(EngineError::Param(format!("{} is too large to be a brush set", path.display()))); + } + let found = BrushLibrary::parse_file(&crate::vfs::read_to_string(&path)?)?; + if found.is_empty() { + return Err(EngineError::Param("the brush set has no brushes in it".into())); + } + let mut names = Vec::with_capacity(found.len()); + for b in found { + match s.brushes.add_unique(b) { + Ok(n) => names.push(n), + Err(e) if names.is_empty() => return Err(e), + // The library filled up part way: say what came in. + Err(_) => break, + } + } + Ok(json!({"imported": names, "yours": s.brushes.user().len()})) +} + +/// Where a preview's stroke runs on a `w` × `h` area: an S across it, the pressure swelling +/// in the middle (so pressure, curves and tapers show). +pub fn preview_points(w: f32, h: f32) -> Vec<[f32; 3]> { + (0..=48) + .map(|i| { + let t = i as f32 / 48.0; + let x = w * (0.1 + 0.8 * t); + let y = h * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin()); + [x, y, 0.25 + 0.75 * (t * std::f32::consts::PI).sin()] + }) + .collect() +} + +/// A brush's stroke preview, drawn by the CPU renderer on a transparent `w` × `h` image (in +/// pixels; `scale` pixels per point): the preview stroke in `color`, the brush's size kept +/// where it fits (between 2 and 40 % of the height). `as_stroke` previews the Paint Brush. +pub fn preview(preset: &BrushPreset, as_stroke: bool, w: u32, h: u32, scale: f32, color: Rgba) -> Result { + let scale = if scale.is_finite() { scale.clamp(0.25, 8.0) } else { 1.0 }; + let (pw, ph) = (w as f32 / scale, h as f32 / scale); + if !(pw >= 8.0 && ph >= 8.0 && w <= 4096 && h <= 4096) { + return Err(EngineError::Param("a brush preview is 8 to 4096 pixels across".into())); + } + let mut doc = anicraft_doc::Document::default(); + doc.stage.width = pw.ceil() as u32; + doc.stage.height = ph.ceil() as u32; + let mut scratch = Session::new(doc); + let mut params = BrushPreset { size: preset.size.clamp(2.0, (ph * 0.4).max(2.0)), ..preset.clone() }.params(); + params["points"] = json!(preview_points(pw, ph)); + params["color"] = json!(format!("#{:02x}{:02x}{:02x}", (color.r.clamp(0.0, 1.0) * 255.0).round() as u8, (color.g.clamp(0.0, 1.0) * 255.0).round() as u8, (color.b.clamp(0.0, 1.0) * 255.0).round() as u8)); + params["object"] = json!(true); + params["as_stroke"] = json!(as_stroke); + scratch.execute("draw.brush", ¶ms)?; + let dl = anicraft_doc::evaluate(&scratch.doc, 0); + let view = anicraft_render::View { transform: Affine::scale(scale, scale), width: w, height: h, background: None }; + Ok(anicraft_render::render(&dl, &view)?.0) +} diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index a5b64bbe..686609fb 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -65,7 +65,7 @@ fn add(s: &mut Session, _: &Value) -> Result { let mut k = Keyframe::new(0, frames); k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el))); layer.keyframes = vec![Arc::new(k)]; - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.insert(0, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -75,7 +75,7 @@ fn add(s: &mut Session, _: &Value) -> Result { fn remove(s: &mut Session, _: &Value) -> Result { let id = camera_layer(s).ok_or_else(no_camera)?; - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.retain(|l| l.id != id); tl.repair_masks(); if s.layer == id { @@ -167,7 +167,7 @@ fn set(s: &mut Session, p: &Value) -> Result { let lim = 1_000_000.0; c.center = Vec2::new(c.center.x.clamp(-lim, lim), c.center.y.clamp(-lim, lim)); el.transform = c.transform(); - el.color = c.color(); + el.color = c.to_element(el.id).color; Ok(c) })(); s.layer = layer; diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index a84fe80a..83f01769 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, ColorStyle, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -12,10 +12,10 @@ pub fn specs() -> Vec { vec![ 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.star", "PolyStar", "", None, "{cx, cy, outer (the corners' radius), shape?: star|polygon (default star; the PolyStar Tool Settings, ADR 0080), sides? (or points; 3..64, default 5), point_size? (0..1, default 0.5: how deep a star's points are, 1 is the polygon through its tips), inner? (an exact inner radius instead of point_size), fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash? (the line style), 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", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point, raw.move_handle and draw.snap do nothing while it is off)", false, snap_to_objects), + c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (while it is off, the `snap` params of element.translate, raw.move_point and draw.snap only snap to guides, the grid and pixels, as View › Guides, Grid and Snapping say)", 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(); @@ -23,24 +23,34 @@ pub fn specs() -> Vec { }), 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.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); 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.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, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", 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_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera's effect is a tint", true, |s, p| s.each_layer(true, |s| set_color_effect(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 symbols of every selected instance)}", true, set_symbol_kind), + c( + "symbol.set_scale_grid", + "9-Slice Scaling", + "", + None, + "{symbol?: id (default: the symbol open for editing, else the selected instance's), on?: bool, left?, right?, top?, bottom? (guide positions in the symbol's space)} turns a symbol's guides for 9-slice scaling on or off, or moves them (ADR 0055). Turning them on brings back the guides it had when they were turned off (ADR 0057), else puts them a quarter of the way in from each edge of the symbol's artwork; moving one turns them on. Scaled instances then keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways → {symbol, scale_grid: {left, right, top, bottom} | null}", + true, + set_scale_grid, + ), 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? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (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("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{} the selected symbol instances become their contents, text becomes shapes, and drawing objects become raw shapes that merge with the raw shapes they touch", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place), ] } @@ -98,9 +108,9 @@ fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> { /// (Object Drawing), it merges with the raw shapes it touches (ADR 0031), and the pieces of it /// that come out are selected. pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option, stroke: Option, object: bool) -> Result { - // 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))); + // A gradient or bitmap from the fill swatch is in stage space: with Lock Fill it stays where + // it is on the stage, else it is fitted to the new shape (ADR 0074). + let fill = fill.map(|f| if s.style.lock_fill || matches!(f, Paint::Solid(_)) { f.transformed(&Affine::translate(-origin.x, -origin.y)) } else { f.fitted(&local.bounds()) }); let merge = !object && crate::merge::can_merge(stroke.as_ref()); let id = ElementId(s.doc.alloc_id()); let el = Element { @@ -108,7 +118,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, name: String::new(), transform: Affine::translate(origin.x, origin.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge, warp: None }), }; if merge { let merged = crate::merge::merge_in(s, vec![el])?; @@ -148,13 +158,36 @@ fn draw_star(s: &mut Session, p: &Value) -> Result { if !(0.5..=MAX_EXTENT).contains(&outer) { return Err(EngineError::Param("param 'outer' must be between 0.5 and 1,000,000".into())); } - let inner = opt_f32(p, "inner")?.unwrap_or(outer * 0.5).clamp(0.0, MAX_EXTENT); - let points = opt_u32(p, "points")?.unwrap_or(5); + // PolyStar's Tool Settings (ADR 0080): a polygon or a star, its sides (or points) and the + // star's point size. + let polygon = match opt_str(p, "shape")?.unwrap_or("star") { + "star" => false, + "polygon" => true, + other => return Err(EngineError::Param(format!("unknown PolyStar style '{other}' (polygon or star)"))), + }; + let points = match (opt_u32(p, "sides")?, opt_u32(p, "points")?) { + (Some(n), _) | (None, Some(n)) => n, + (None, None) => 5, + }; if !(3..=64).contains(&points) { - return Err(EngineError::Param("param 'points' must be between 3 and 64".into())); + return Err(EngineError::Param("param 'sides' (or 'points') must be between 3 and 64".into())); } + let point_size = match opt_f32(p, "point_size")? { + None => 0.5, + Some(v) if (0.0..=1.0).contains(&v) => v, + Some(_) => return Err(EngineError::Param("param 'point_size' must be between 0 and 1".into())), + }; let (fill, stroke) = style(s, p, true)?; - add_shape(s, "star", Path::star(0.0, 0.0, outer, inner, points), Vec2::new(cx, cy), fill, stroke, object_param(s, p)?) + let object = object_param(s, p)?; + if polygon { + return add_shape(s, "polygon", Path::polystar(0.0, 0.0, outer, points, false, point_size), Vec2::new(cx, cy), fill, stroke, object); + } + // An explicit inner radius (scripts written before the point size) still wins. + let path = match opt_f32(p, "inner")? { + Some(inner) => Path::star(0.0, 0.0, outer, inner.clamp(0.0, MAX_EXTENT), points), + None => Path::polystar(0.0, 0.0, outer, points, true, point_size), + }; + add_shape(s, "star", path, Vec2::new(cx, cy), fill, stroke, object) } fn draw_line(s: &mut Session, p: &Value) -> Result { @@ -200,6 +233,7 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids"))); } let add = opt_bool(p, "add")?.unwrap_or(false); + let toggle = opt_bool(p, "toggle")?.unwrap_or(false); // Where each element is at the playhead: on `layer`, else the active layer first, then the // others top to bottom. let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { @@ -224,11 +258,17 @@ fn select(s: &mut Session, p: &Value) -> Result { } picked.push((l, id)); } - if !add { - s.selection.clear(); - } - for &(l, id) in &picked { - s.selection.insert(l, id); + if toggle { + for &(l, id) in &picked { + s.selection.toggle(l, id); + } + } else { + if !add { + s.selection.clear(); + } + for &(l, id) in &picked { + s.selection.insert(l, id); + } } // As a click does: the active layer is where the artwork is. if let Some(&(l, _)) = picked.first() @@ -266,7 +306,7 @@ fn pick(s: &mut Session, p: &Value) -> Result { fn translate(s: &mut Session, p: &Value) -> Result { 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 snap = 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) => { @@ -277,7 +317,7 @@ fn translate(s: &mut Session, p: &Value) -> Result { 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 + if s.snaps(snap) && let Some((extra, at, kind)) = crate::cmds_raw::snap_selection(s, snap, from) { move_by(s, extra)?; @@ -340,7 +380,7 @@ fn shapes_mut(s: &mut Session) -> Result> { .into_iter() .filter_map(|e| match &mut e.kind { ElementKind::Shape(sh) => Some(sh), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, }) .collect(); if shapes.is_empty() { @@ -361,7 +401,7 @@ fn set_fill(s: &mut Session, p: &Value) -> Result { Ok(json!({"ok": true})) } -fn set_stroke(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_stroke(s: &mut Session, p: &Value) -> Result { let remove = p.get("color").is_some_and(Value::is_null); let color = opt_color(p, "color")?; let width = opt_f32(p, "width")?; @@ -401,11 +441,86 @@ fn set_alpha(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into())); } for e in s.selected_elements_mut()? { - e.color.alpha = a; + e.color = e.color.with_alpha(a); } Ok(json!({"alpha": a})) } +/// Each colour effect value `element.set_color_effect` takes: its key, style, range and scale +/// (the model's value is the param's divided by it). +const EFFECT_VALUES: [(&str, ColorStyle, f32, f32, f32); 11] = [ + ("alpha", ColorStyle::Alpha, 0.0, 100.0, 100.0), + ("brightness", ColorStyle::Brightness, -100.0, 100.0, 100.0), + ("tint_amount", ColorStyle::Tint, 0.0, 100.0, 100.0), + ("red_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("green_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("blue_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("alpha_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("red_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("green_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("blue_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("alpha_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), +]; + +fn set_color_effect(s: &mut Session, p: &Value) -> Result { + let style = match opt_str(p, "style")? { + Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?), + None => None, + }; + let tint = opt_color(p, "tint")?; + let mut values: Vec<(usize, f32)> = Vec::new(); + let mut families: Vec = tint.map(|_| ColorStyle::Tint).into_iter().collect(); + for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() { + if let Some(v) = opt_f32(p, key)? { + if !(*lo..=*hi).contains(&v) { + return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}"))); + } + values.push((i, v / scale)); + if !families.contains(fam) { + families.push(*fam); + } + } + } + let style = match (style, families.as_slice()) { + (Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))), + (Some(st), _) => Some(st), + (None, []) => return Err(EngineError::Param("give a style, or a value to set".into())), + (None, [one]) => Some(*one), + (None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())), + }; + let mut first = None; + for e in s.selected_elements_mut()? { + let target = style.unwrap_or(e.color.style()); + if matches!(e.kind, ElementKind::Camera) && !matches!(target, ColorStyle::Tint | ColorStyle::None) { + return Err(EngineError::State("the camera's colour effect is a tint".into())); + } + let mut fx = e.color.to_style(target); + if let ColorEffect::Tint { color, .. } = &mut fx + && let Some(t) = tint + { + *color = t.with_alpha(1.0); + } + for &(i, v) in &values { + match &mut fx { + ColorEffect::Alpha(a) if i == 0 => *a = v, + ColorEffect::Brightness(b) if i == 1 => *b = v, + ColorEffect::Tint { amount, .. } if i == 2 => *amount = v, + ColorEffect::Advanced(t) => { + if let Some(m) = i.checked_sub(3).and_then(|j| t.mul.get_mut(j)) { + *m = v; + } else if let Some(o) = i.checked_sub(7).and_then(|j| t.add.get_mut(j)) { + *o = v; + } + } + _ => {} + } + } + e.color = fx.sanitized(); + first.get_or_insert(e.color); + } + Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx))) +} + /// Most filters on one instance. const MAX_FILTERS: usize = 16; @@ -555,6 +670,66 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::>(), "kind": format!("{kind:?}")})) } +/// The symbol a command means: `symbol`, else the selected instance's. +fn selected_symbol(s: &Session, p: &Value) -> Result { + Ok(match opt_u64(p, "symbol")? { + Some(id) => SymbolId(id), + None => { + // The symbol of the selected instance. + 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 { + ElementKind::Symbol { symbol, .. } => Some(symbol), + ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, + }) + .ok_or_else(|| EngineError::State("the selection is not a symbol instance".into()))? + } + }) +} + +/// 9-slice guides (ADR 0055): on, off or moved, on one symbol. +fn set_scale_grid(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "on")?; + let edges = [opt_f32(p, "left")?, opt_f32(p, "right")?, opt_f32(p, "top")?, opt_f32(p, "bottom")?]; + if on.is_none() && edges.iter().all(Option::is_none) { + return Err(EngineError::Param("pass 'on', or a guide to move: 'left', 'right', 'top' or 'bottom'".into())); + } + // The open symbol is the one being edited; otherwise the selected instance's. + let id = match (opt_u64(p, "symbol")?, s.editing_symbol()) { + (None, Some(open)) => open, + _ => selected_symbol(s, p)?, + }; + let sym = s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + let grid = if on == Some(false) { + if edges.iter().any(Option::is_some) { + return Err(EngineError::Param("guides can't be moved while turning them off".into())); + } + None + } else { + // Switched on again, the guides come back where they were (ADR 0057). + let start = sym.scale_grid.or(sym.scale_grid_kept).unwrap_or_else(|| { + let b = anicraft_doc::symbol_box(&s.doc, sym); + ScaleGrid::inset(&if b.is_empty() { anicraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0) } else { b }) + }); + let [l, r, t, b] = edges; + let g = ScaleGrid { left: l.unwrap_or(start.left), right: r.unwrap_or(start.right), top: t.unwrap_or(start.top), bottom: b.unwrap_or(start.bottom) }; + g.check().map_err(EngineError::Param)?; + Some(g) + }; + // Off, the guides are kept (only hidden), so switching back on finds them. + let kept = if grid.is_none() { sym.scale_grid.or(sym.scale_grid_kept) } else { None }; + if let Some(sym) = s.doc.library.iter_mut().find(|x| x.id == id) + && (sym.scale_grid != grid || sym.scale_grid_kept != kept) + { + let sym = Arc::make_mut(sym); + sym.scale_grid = grid; + sym.scale_grid_kept = kept; + } + Ok(json!({"symbol": id.0, "scale_grid": grid.map(|g| json!({"left": g.left, "right": g.right, "top": g.top, "bottom": g.bottom}))})) +} + fn rename(s: &mut Session, p: &Value) -> Result { let name: String = str_req(p, "name")?.chars().take(128).collect(); for e in s.selected_elements_mut()? { @@ -703,7 +878,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { } inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, timeline: Timeline { layers: inner } })); + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: inner } })); if folder.is_some() { s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder); } @@ -721,7 +896,21 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { let mut fresh_ids = Vec::new(); let kf_elements: Vec> = s.editable_keyframe()?.elements.clone(); let mut out = Vec::new(); + // Drawing objects (Object Drawing) break apart into raw shapes, which then merge with the + // raw shapes they touch, as in Animate (#253). + let mut objects = Vec::new(); for e in kf_elements { + if let ElementKind::Shape(sh) = &e.kind + && !sh.merge + && sel.contains(&e.id) + { + let mut c = (*e).clone(); + if let ElementKind::Shape(sh) = &mut c.kind { + sh.merge = true; + } + objects.push(c); + continue; + } // Text breaks apart into a shape with the same outlines. if let ElementKind::Text(t) = &e.kind && sel.contains(&e.id) @@ -733,6 +922,25 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { out.push(Arc::new(c)); continue; } + // A group breaks apart into its members (Animate's Ctrl+B on a group ungroups it). + if let ElementKind::Group { .. } = &e.kind + && sel.contains(&e.id) + { + for child in e.kind.group_members() { + let mut c = (*child).clone(); + c.id = ElementId(s.doc.alloc_id()); + c.transform = e.transform.mul(&child.transform); + c.color = e.color.nested(&child.color); + // Its raw shapes merge with the drawing they now stand in, as drawing objects do. + if crate::merge::mergeable(&c).is_some() { + objects.push(c); + continue; + } + fresh_ids.push(c.id); + out.push(Arc::new(c)); + } + continue; + } let ElementKind::Symbol { symbol, .. } = &e.kind else { out.push(e); continue; @@ -750,16 +958,19 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { let mut c = (**child).clone(); c.id = ElementId(s.doc.alloc_id()); c.transform = e.transform.mul(&child.transform); - c.color = e.color.concat(&child.color); + c.color = e.color.nested(&child.color); fresh_ids.push(c.id); out.push(Arc::new(c)); } } } - if fresh_ids.is_empty() { - return Err(EngineError::State("the selection has no symbol instances or text to break apart".into())); + if fresh_ids.is_empty() && objects.is_empty() { + return Err(EngineError::State("the selection has no symbol instances, groups, text or drawing objects to break apart".into())); } s.editable_keyframe()?.elements = out; + if !objects.is_empty() { + fresh_ids.extend(crate::merge::merge_in(s, objects)?); + } s.select_only(fresh_ids.iter().copied()); Ok(json!({"created": fresh_ids.len()})) } @@ -771,7 +982,7 @@ const MAX_PLACE: usize = 1_000; /// does (ADR 0053): an instance of each symbol, a rectangle of each bitmap's size showing it, /// in the active layer's keyframe at the playhead, all selected; a sound goes onto that /// keyframe. One command, so one undo step however many items. -fn place(s: &mut Session, p: &Value) -> Result { +pub(crate) fn place(s: &mut Session, p: &Value) -> Result { let items: Vec = match p.get("items") { Some(list) => { let list = list.as_array().ok_or_else(|| EngineError::Param("param 'items' must be a list of {\"symbol\" | \"bitmap\" | \"sound\": id}".into()))?; @@ -873,6 +1084,7 @@ fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32) stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); diff --git a/crates/engine/src/cmds_drop.rs b/crates/engine/src/cmds_drop.rs new file mode 100644 index 00000000..52823213 --- /dev/null +++ b/crates/engine/src/cmds_drop.rs @@ -0,0 +1,282 @@ +//! Files dropped onto the window (ADR 0059). What a file is, and where it was dropped, decide +//! what happens: documents open (`file.open`, which asks first over unsaved work); drawings, +//! images and sounds dropped on the stage go onto the active layer at the playhead at the drop +//! point, and dropped on the Library go into the Library (into the folder under the pointer; +//! an SVG as a graphic symbol, ADR 0065). Dropped on a layer's frame in the timeline, a sound +//! goes onto the keyframe there and a drawing or image onto that layer at that frame, in a +//! keyframe made there if there is none (ADR 0065). +//! The routing is a pure function the shell and tests share; `file.drop` does the import, so a +//! drop of several files is one undo step however many it brings in. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{FolderId, LibraryEntry, LibraryItem}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most files one drop brings in. +pub const MAX_DROPPED: usize = 64; + +/// What a dropped file is, by its name (and, for an XFL folder, what is inside it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropKind { + /// `.anicraft`, `.fla`, `.xfl` (or an XFL folder): opens as the document. + Document, + /// `.svg`. + Drawing, + /// `.png`, `.jpg`, `.jpeg`. + Image, + /// `.wav`, `.ogg`, `.mp3`. + Sound, + /// Anything else. + Unsupported, +} + +/// Where a file was dropped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropTarget { + Stage, + Library, + /// A layer's frame in the timeline. + Timeline, + /// Anywhere else on the window (panels, the timeline, the menu bar). + Window, +} + +/// What a drop does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropAction { + /// Open it as the document (`file.open`). + Open, + /// `file.drop` with `to: "stage"`. + ImportToStage, + /// `file.drop` with `to: "library"`. + ImportToLibrary, + /// `file.drop` with `to: "timeline"`. + ImportToTimeline, + /// Nothing; the message (English, translated where it is shown) says why. + Refuse(&'static str), +} + +pub fn kind_of(path: &Path) -> DropKind { + if crate::cmds_file::is_animate(path) { + return DropKind::Document; + } + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + match ext.as_deref() { + Some("anicraft") => DropKind::Document, + Some("svg") => DropKind::Drawing, + Some("png" | "jpg" | "jpeg") => DropKind::Image, + _ if crate::cmds_sound::is_sound(path) => DropKind::Sound, + _ => DropKind::Unsupported, + } +} + +/// The message for a file AniCraft can't take. +pub const UNSUPPORTED: &str = "AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds"; + +/// What dropping a file of `kind` on `target` does. +pub fn route(kind: DropKind, target: DropTarget) -> DropAction { + match (kind, target) { + (DropKind::Document, _) => DropAction::Open, + (DropKind::Unsupported, _) => DropAction::Refuse(UNSUPPORTED), + (_, DropTarget::Library) => DropAction::ImportToLibrary, + (_, DropTarget::Timeline) => DropAction::ImportToTimeline, + (_, DropTarget::Stage) => DropAction::ImportToStage, + // Not over the stage, the timeline or the Library: drop it on one of them. + (_, DropTarget::Window) => DropAction::Refuse(ELSEWHERE), + } +} + +/// The message for media dropped where nothing takes them. +pub const ELSEWHERE: &str = "Drop drawings, images and sounds on the stage or a layer's frame to place them, or on the Library to add them"; + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "file.drop", + label: "Import Dropped Files", + menu: "", + shortcut: None, + params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library | timeline, x?, y? (stage and timeline: the point in the edited space to centre on, default the stage centre), folder? (library: a folder id), layer, frame (timeline: a layer id and a frame, from 0)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, and drawings become graphic symbols, into `folder`; on the timeline the playhead goes to the frame, a sound goes onto the layer's keyframe there (one sound per drop) and drawings and images onto the layer in a keyframe starting at that frame (made if needed, keeping what the frame showed; a drawing with several layers or masks goes in as a graphic symbol). One undo step", + mutates: true, + run: drop, + }] +} + +fn paths(p: &Value) -> Result> { + let list: Vec = match (p.get("paths"), opt_str(p, "path")?) { + (Some(v), None) => { + let a = v.as_array().ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))?; + a.iter().map(|x| x.as_str().map(PathBuf::from).ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))).collect::>()? + } + (None, Some(one)) => vec![PathBuf::from(one)], + _ => return Err(EngineError::Param("name the files with 'paths' (or one with 'path')".into())), + }; + if list.is_empty() || list.len() > MAX_DROPPED { + return Err(EngineError::Param(format!("drop 1 to {MAX_DROPPED} files at once"))); + } + Ok(list) +} + +fn drop(s: &mut Session, p: &Value) -> Result { + let files = paths(p)?; + let target = match str_req(p, "to")? { + "stage" => DropTarget::Stage, + "library" => DropTarget::Library, + "timeline" => DropTarget::Timeline, + other => return Err(EngineError::Param(format!("param 'to' must be stage, library or timeline, not '{other}'"))), + }; + // Everything is checked before anything is imported (the command is atomic anyway). + for f in &files { + match route(kind_of(f), target) { + DropAction::Open => return Err(EngineError::Param(format!("{} is a document: open it with file.open", f.display()))), + DropAction::Refuse(why) => return Err(EngineError::Param(format!("{}: {why}", f.display()))), + DropAction::ImportToStage | DropAction::ImportToLibrary | DropAction::ImportToTimeline => {} + } + } + let folder = match opt_u64(p, "folder")? { + Some(f) if target == DropTarget::Library => { + let id = FolderId(f); + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("no Library folder with id {f}"))); + } + Some(id) + } + Some(_) => return Err(EngineError::Param("'folder' is for drops on the Library".into())), + None => None, + }; + let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); + let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); + if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 { + return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into())); + } + if target == DropTarget::Timeline { + return onto_timeline(s, p, &files, x, y); + } + let (mut elements, mut items, mut layers) = (Vec::new(), Vec::new(), 0u64); + for f in &files { + let path = f.display().to_string(); + if target == DropTarget::Library { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64(), v["symbol"].as_u64()) { + (Some(b), _, _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)), + (None, Some(snd), _) => LibraryItem::Sound(anicraft_doc::SoundId(snd)), + (None, None, Some(sym)) => LibraryItem::Symbol(anicraft_doc::SymbolId(sym)), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + if let Some(folder) = folder { + // Into the folder under the pointer, numbered if it has an item of that name. + let name = s.doc.item_name(item).unwrap_or("").to_string(); + let free = s.doc.unique_name(Some(folder), &name); + s.doc.place_entry(LibraryEntry::Item(item), Some(folder)); + if free != name { + let mut params = crate::cmds_library::entry_json(LibraryEntry::Item(item)); + params["name"] = json!(free); + crate::cmds_library::rename(s, ¶ms)?; + } + } + items.push(crate::cmds_library::entry_json(LibraryEntry::Item(item))); + continue; + } + match kind_of(f) { + DropKind::Drawing => { + // A drawing's own shapes, on the active layer (or its own layers when it has + // several or masks), centred on the drop point. + let v = crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + layers += v["layers"].as_u64().unwrap_or(0); + elements.extend(s.selection.ids()); + } + _ => { + // An image or a sound: into the Library, then placed as Place on Stage does. + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) { + (Some(b), _) => json!({"bitmap": b}), + (None, Some(snd)) => json!({"sound": snd}), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + items.push(item.clone()); + let mut place = item; + place["x"] = json!(x); + place["y"] = json!(y); + let placed = crate::cmds_draw::place(s, &place)?; + if let Some(list) = placed["elements"].as_array() { + elements.extend(list.iter().filter_map(Value::as_u64).map(anicraft_doc::ElementId)); + } + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": layers, "files": files.len()})) +} + +/// A drop on a layer's frame in the timeline (ADR 0065). +fn onto_timeline(s: &mut Session, p: &Value, files: &[PathBuf], x: f32, y: f32) -> Result { + let layer = anicraft_doc::LayerId(opt_u64(p, "layer")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'layer' (an id)".into()))?); + let frame = opt_u32(p, "frame")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'frame' (from 0)".into()))?; + if frame > crate::MAX_FRAME { + return Err(EngineError::Param(format!("'frame' must be at most {}", crate::MAX_FRAME))); + } + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State(format!("no layer with id {} here", layer.0)))?; + let refuse = match l.kind { + anicraft_doc::LayerKind::Folder => Some("is a folder: drop on one of its layers"), + anicraft_doc::LayerKind::Camera => Some("is the camera layer: drop on a layer below it"), + anicraft_doc::LayerKind::Armature => Some("holds an armature, posed by its bones: drop on another layer"), + _ if l.locked || tl.locked_by_folder(layer) => Some("is locked: unlock it to drop onto it"), + _ => None, + }; + if let Some(why) = refuse { + return Err(EngineError::State(format!("“{}” {why}", l.name))); + } + if files.iter().filter(|f| kind_of(f) == DropKind::Sound).count() > 1 { + return Err(EngineError::Param("a keyframe holds one sound: drop sounds one at a time, or on different layers".into())); + } + s.layer = layer; + s.frame = frame; + // Artwork goes into a keyframe starting at the frame: made there when the frame is inside + // another's span (keeping what it showed, as Insert Keyframe does). + let artwork = files.iter().any(|f| kind_of(f) != DropKind::Sound); + let made = artwork && s.timeline().layer(layer).is_some_and(|l| l.keyframe_starting_at(frame).is_none()); + if made { + crate::cmds_timeline::insert_keyframe_at(s.layer_mut(Some(layer))?, frame, true)?; + } + let (mut elements, mut items) = (Vec::new(), Vec::new()); + let placed_ids = |v: &Value| -> Vec { v["elements"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(anicraft_doc::ElementId).collect() }; + for f in files { + let path = f.display().to_string(); + let nothing = || EngineError::State(format!("{path} added nothing to the Library")); + match kind_of(f) { + DropKind::Drawing if crate::cmds_file::one_layer(&crate::cmds_file::read_svg(f)?) => { + crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + elements.extend(s.selection.ids()); + } + DropKind::Drawing => { + // Its layers can't all go on one layer: a graphic symbol holding them goes there. + let v = crate::cmds_file::import_svg_symbol(s, f, None)?; + let sym = v["symbol"].as_u64().ok_or_else(nothing)?; + items.push(json!({"symbol": sym})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"symbol": sym, "x": x, "y": y}))?)); + } + DropKind::Sound => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let snd = v["sound"].as_u64().ok_or_else(nothing)?; + items.push(json!({"sound": snd})); + // Onto the keyframe the frame is in (one is made past the layer's end), as long + // as the sound when it is the layer's last. + crate::cmds_sound::place(s, &json!({"sound": snd, "layer": layer.0, "frame": frame, "extend": true}))?; + } + _ => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let b = v["bitmap"].as_u64().ok_or_else(nothing)?; + items.push(json!({"bitmap": b})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"bitmap": b, "x": x, "y": y}))?)); + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": 0, "files": files.len(), "layer": layer.0, "frame": frame, "keyframe_made": made})) +} diff --git a/crates/engine/src/cmds_envelope.rs b/crates/engine/src/cmds_envelope.rs new file mode 100644 index 00000000..bc71d8b3 --- /dev/null +++ b/crates/engine/src/cmds_envelope.rs @@ -0,0 +1,258 @@ +//! Envelope (ADR 0080): Modify › Transform › Envelope bends the selected shapes and drawing +//! objects by a mesh of handles around them (`anicraft_geom::envelope`, a bicubic Bézier patch). +//! +//! The envelope is open while its shapes are the ones it made: each move bends the shapes as they +//! were when it opened (so moves never compound their approximation), and is one undo step. Like +//! Animate, it is baked: the shapes stay ordinary paths, so there is nothing to delete (no Delete +//! Envelope). Undo and redo go back to the mesh that made the shapes they restore: the session +//! keeps each mesh with the shapes it made, and finds the one whose shapes are on the stage. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Shape}; +use anicraft_geom::envelope::{self, Mesh}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "modify.envelope", + "Envelope", + "Modify/Transform", + None, + "{} opens an envelope around the selected shapes and drawing objects on the active layer (ADR 0080): a mesh of 4 × 4 Bézier control points over their bounds, at rest → {points: [[x, y] × 16] (row by row from the top-left), bounds: [x, y, w, h], shapes}. Then modify.envelope_move bends them. Symbols, text, groups and bitmaps can't be bent: break them apart first", + false, + open as crate::RunFn, + ), + c( + "modify.envelope_move", + "Envelope", + "", + None, + "{points: [[x, y] × 16] (the whole mesh) | index: 0..15, x, y (one control point; a corner or side handle moves the inner points with it, as a Coons patch), tolerance? (stage units, default 0.05)} bends the open envelope's shapes from where they were when it opened → {points, shapes}. One undo step", + true, + move_points, + ), + c( + "modify.envelope_close", + "Close Envelope", + "", + None, + "{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}", + true, + close, + ), + ] +} + +/// Most meshes remembered for undo and redo. +const MAX_STATES: usize = 256; +/// Most shapes one envelope bends. +const MAX_SHAPES: usize = 10_000; + +/// An open envelope. +#[derive(Clone, Debug)] +pub struct Envelope { + pub layer: LayerId, + /// The rest rectangle (keyframe space) and the shapes as they were when it opened. + pub rest: Rect, + originals: Vec>, + /// Each mesh used, with the shapes it made (the first is the rest mesh and the originals). + states: Vec<(Mesh, Vec>)>, + /// The gesture (by the state it started from) whose move made the last of `states`: a + /// drag's moves are one undo step, so only its last needs remembering. + live: Option, +} + +impl Envelope { + #[cfg(test)] + pub(crate) fn states_len(&self) -> usize { + self.states.len() + } + + /// The mesh that made the shapes now on `els`, if they are still what one of its moves made. + fn current(&self, els: &[Arc]) -> Option { + let now: Vec>> = self.originals.iter().map(|o| els.iter().find(|e| e.id == o.id)).collect(); + self.states + .iter() + .rev() + .find(|(_, made)| made.len() == now.len() && made.iter().zip(&now).all(|(m, n)| n.is_some_and(|n| Arc::ptr_eq(m, n) || **m == **n))) + .map(|(mesh, _)| *mesh) + } +} + +impl Session { + /// The open envelope's layer, rest rectangle and current mesh (keyframe space), while its + /// shapes are selected and still the ones it made (an edit to them, or a new selection, + /// ends it). + pub fn envelope(&self) -> Option<(LayerId, Rect, Mesh)> { + let env = self.envelope.as_ref()?; + if env.layer != self.layer || !env.originals.iter().all(|o| self.selection.contains(env.layer, o.id)) { + return None; + } + let mesh = env.current(&self.elements_on(env.layer))?; + Some((env.layer, env.rest, mesh)) + } +} + +fn mesh_json(m: &Mesh) -> Value { + json!(m.iter().map(|p| [p.x, p.y]).collect::>()) +} + +/// What an envelope can bend: shapes (raw and drawing objects). +fn bendable(e: &Element) -> bool { + matches!(e.kind, ElementKind::Shape(_)) +} + +/// The tight bounds of shapes' outlines in keyframe space. +fn outline_bounds(els: &[Arc]) -> Rect { + let mut r = Rect::EMPTY; + for e in els { + if let ElementKind::Shape(sh) = &e.kind { + for pl in sh.path.flatten(&e.transform, 0.05) { + pl.points.iter().for_each(|p| r.include(*p)); + } + } + } + r +} + +fn open(s: &mut Session, _: &Value) -> Result { + let here = s.layer; + let sel = s.selection.on(here); + let els = s.elements_on(here); + let picked: Vec> = els.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + if picked.is_empty() { + return Err(EngineError::State("select the shapes or drawing objects to bend with an envelope".into())); + } + if !picked.iter().all(|e| bendable(e)) { + return Err(EngineError::State("an envelope bends shapes and drawing objects only: break symbols, text, groups and bitmaps apart first (Modify › Break Apart)".into())); + } + // A warp (ADR 0079) bends the outline as drawn on every keyframe of its layer: baking an + // envelope into one of them would fight it. + if picked.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_some())) { + return Err(EngineError::State("an envelope can't bend warped artwork (Asset Warp): remove its warp first (Modify › Asset Warp › Remove Warp)".into())); + } + if picked.len() > MAX_SHAPES { + return Err(EngineError::State(format!("an envelope bends at most {MAX_SHAPES} shapes at once"))); + } + let mut rest = outline_bounds(&picked); + // A straight line has no height (or width): give the mesh some room. + if rest.is_empty() || !rest.min.x.is_finite() { + return Err(EngineError::State("the selection has no outline to bend".into())); + } + let pad = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) }; + let ((x0, x1), (y0, y1)) = (pad(rest.min.x, rest.max.x), pad(rest.min.y, rest.max.y)); + rest = Rect::new(x0, y0, x1, y1); + let mesh = envelope::rest_mesh(&rest); + s.envelope = Some(Envelope { layer: here, rest, originals: picked.clone(), states: vec![(mesh, picked.clone())], live: None }); + Ok(json!({"points": mesh_json(&mesh), "bounds": [rest.min.x, rest.min.y, rest.width(), rest.height()], "shapes": picked.len()})) +} + +/// The mesh asked for: the whole of it, or the current one with one point moved. +fn asked(p: &Value, current: &Mesh) -> Result { + if let Some(list) = p.get("points") { + let bad = || EngineError::Param("param 'points' must be 16 points [x, y], row by row from the top-left".into()); + let list = list.as_array().filter(|l| l.len() == 16).ok_or_else(bad)?; + let mut m = [Vec2::ZERO; 16]; + for (slot, v) in m.iter_mut().zip(list) { + let xy = v.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() && f.abs() <= crate::cmds_draw::MAX_EXTENT); + *slot = Vec2::new(n(0).ok_or_else(bad)?, n(1).ok_or_else(bad)?); + } + return Ok(m); + } + let i = opt_u32(p, "index")?.ok_or_else(|| EngineError::Param("give the whole mesh ('points') or one point ('index', 'x', 'y')".into()))? as usize; + if i >= 16 { + return Err(EngineError::Param("param 'index' must be 0 to 15".into())); + } + let to = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if !(to.x.abs() <= crate::cmds_draw::MAX_EXTENT && to.y.abs() <= crate::cmds_draw::MAX_EXTENT) { + return Err(EngineError::Param("the point is too far away".into())); + } + let mut m = *current; + if let Some(slot) = m.get_mut(i) { + *slot = to; + } + // A boundary handle bends the inside with it; an inner point moves alone. + if envelope::BOUNDARY.contains(&i) { + envelope::coons_interior(&mut m); + } + Ok(m) +} + +/// `shape` (placed by `m`) bent in keyframe space, as an element placed at its centre. +fn bent(e: &Element, sh: &Shape, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + let path = envelope::warp(&sh.path.transformed(&e.transform), mesh, rest, tol)?; + let c = path.bounds().center(); + let to_local = Affine::translate(-c.x, -c.y); + let k = e.transform.mean_scale(); + let shape = Shape { + path: Arc::new(path.transformed(&to_local)), + // Gradients and bitmaps stay where they were on the stage (they don't bend, as in Animate). + fill: sh.fill.as_ref().map(|f| f.transformed(&to_local.mul(&e.transform))), + stroke: sh.stroke.as_ref().map(|st| st.scaled(k)), + ..sh.clone() + }; + Some(Element { id: e.id, name: e.name.clone(), transform: Affine::translate(c.x, c.y), color: e.color, kind: ElementKind::Shape(shape) }) +} + +fn move_points(s: &mut Session, p: &Value) -> Result { + let none = || EngineError::State("no envelope is open: select shapes and choose Modify › Transform › Envelope".into()); + let (_, rest, current) = s.envelope().ok_or_else(none)?; + let mesh = asked(p, ¤t)?; + let tol = match opt_f32(p, "tolerance")? { + None => 0.05, + Some(t) if (0.001..=100.0).contains(&t) => t, + Some(_) => return Err(EngineError::Param("param 'tolerance' must be between 0.001 and 100".into())), + }; + let originals = s.envelope.as_ref().map(|e| e.originals.clone()).unwrap_or_default(); + let made: Vec> = originals + .iter() + .map(|o| match &o.kind { + ElementKind::Shape(sh) => bent(o, sh, &mesh, &rest, tol).map(Arc::new).ok_or_else(|| EngineError::State("the envelope bends those shapes too far to draw; move the handles back a little".into())), + _ => Ok(o.clone()), + }) + .collect::>()?; + let kf = s.editable_keyframe()?; + for m in &made { + if let Some(slot) = kf.elements.iter_mut().find(|e| e.id == m.id) { + *slot = m.clone(); + } + } + let gesture = s.gesture.as_ref().map(|g| g.state); + if let Some(env) = s.envelope.as_mut() { + // Another move of the same drag replaces the one before it. + if gesture.is_some() && env.live == gesture && env.states.len() > 1 { + env.states.pop(); + } + env.live = gesture; + if env.states.len() >= MAX_STATES { + // Keep the rest state; forget the oldest move. + env.states.remove(1); + } + env.states.push((mesh, made.clone())); + } + Ok(json!({"points": mesh_json(&mesh), "shapes": made.len()})) +} + +fn close(s: &mut Session, _: &Value) -> Result { + let Some(env) = s.envelope.take() else { return Ok(json!({"closed": false})) }; + let ids: Vec = env.originals.iter().map(|e| e.id).collect(); + // Bent raw shapes merge where they now lie, as after a move (ADR 0031). + let here = s.elements_on(env.layer); + let raw = here.iter().any(|e| ids.contains(&e.id) && crate::merge::mergeable(e).is_some()); + if raw && env.layer == s.layer { + let keep = s.selection.clone(); + s.selection = crate::Selection::only(env.layer, ids.iter().copied()); + crate::merge::drop_selected(s)?; + // What the merge selected, else what was selected. + if s.selection.is_empty() { + s.selection = keep; + } + } + Ok(json!({"closed": true})) +} diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index 1d18a625..be5be5d4 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -247,7 +247,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result { let near = sh.path.bounds().transformed(&e.transform).inflate(hw + slop).contains(at); near && ((sh.fill.is_some() && sh.path.contains(at, &e.transform, sh.fill_rule)) || (sh.stroke.is_some() && sh.path.distance_to_edge(at, &e.transform) <= hw + slop)) } - ElementKind::Symbol { .. } | ElementKind::Text(_) => s.element_bounds(e.id).contains(at), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Group { .. } => s.element_bounds(e.id).contains(at), ElementKind::Camera => false, }); let Some(hit) = hit else { @@ -283,7 +283,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result { let (scene, frame) = (s.scene, s.frame); let mut erased = 0; for (id, _) in &layers { - let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(*id) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).ok().and_then(|tl| tl.layer_mut(*id)) else { continue }; let Some(i) = layer.keyframe_index_at(frame) else { continue }; let Some(kf) = layer.keyframe_mut(i) else { continue }; erased += kf.elements.len(); diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 5a046c8c..190caf69 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -10,7 +10,7 @@ use std::path::PathBuf; use std::sync::Arc; pub fn specs() -> Vec { - vec![ + let mut v = vec![ CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc }, CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{which?: demo (default) | interactive (a menu with a Play button, for Test Movie)}", mutates: false, run: new_sample }, CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path, unsaved? (opens it as unsaved work: a restored copy), untitled? (with no file name, so Save asks for one)}", mutates: false, run: open }, @@ -33,7 +33,7 @@ pub fn specs() -> Vec { label: "Import to Stage…", menu: "File/Import", shortcut: Some("Ctrl+R"), - params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred)}", + params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}", mutates: true, run: import_to_stage, }, @@ -74,6 +74,24 @@ pub fn specs() -> Vec { mutates: false, run: export_gif, }, + CommandSpec { + id: "file.export_apng", + label: "Export Animated PNG…", + menu: "File/Export", + shortcut: None, + params: "{path (.png or .apng), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Apng), + }, + CommandSpec { + id: "file.export_webp", + label: "Export Animated WebP…", + menu: "File/Export", + shortcut: None, + params: "{path (.webp; lossless), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Webp), + }, CommandSpec { id: "file.export_lottie", label: "Export Lottie Animation…", @@ -104,7 +122,19 @@ pub fn specs() -> Vec { run: set_stage, }, CommandSpec { id: "doc.info", label: "Document Info", menu: "", shortcut: None, params: "{}", mutates: false, run: |s, _| Ok(s.info()) }, - ] + ]; + // In the File menu as in Animate: New from Template under New, Save as Template under + // Save As (ADR 0065). + for t in crate::cmds_template::specs() { + let after = match t.id { + "file.new_from_template" => "file.new_sample", + "file.save_as_template" => "file.save_as", + _ => "doc.info", + }; + let at = v.iter().position(|c| c.id == after).map_or(v.len(), |i| i + 1); + v.insert(at, t); + } + v } fn stage_edge(p: &Value, key: &str, default: u32) -> Result { @@ -149,7 +179,7 @@ pub fn is_animate(path: &std::path::Path) -> bool { matches!(ext.as_deref(), Some("fla" | "xfl")) || (crate::vfs::is_dir(path) && crate::vfs::is_file(&path.join("DOMDocument.xml"))) } -fn open(s: &mut Session, p: &Value) -> Result { +pub(crate) fn open(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false); let untitled = opt_bool(p, "untitled")?.unwrap_or(false); @@ -173,6 +203,8 @@ fn open(s: &mut Session, p: &Value) -> Result { // as it was in Animate (ADR 0042). let merged = crate::merge::merge_document(&mut doc); s.replace_document(doc, None); + // Open Recent reopens the Animate file (ADR 0059). + s.recent.add(&path); let mut info = s.info(); info["imported"] = json!(path.display().to_string()); info["report"] = json!(report.summary()); @@ -184,9 +216,11 @@ fn open(s: &mut Session, p: &Value) -> Result { return Ok(info); } let doc = format::load(&path)?; - s.replace_document(doc, (!untitled).then_some(path)); + s.replace_document(doc, (!untitled).then(|| path.clone())); if unsaved { s.mark_unsaved(); + } else if !untitled { + s.recent.add(&path); } Ok(s.info()) } @@ -199,10 +233,11 @@ fn save(s: &mut Session, p: &Value) -> Result { format::save(&s.doc, &path)?; s.path = Some(path.clone()); s.mark_saved(); + s.recent.add(&path); Ok(json!({"saved": path.display().to_string()})) } -fn scale_param(p: &Value) -> Result { +pub(crate) fn scale_param(p: &Value) -> Result { match opt_f32(p, "scale")? { None => Ok(1.0), Some(v) if v > 0.0 && v <= 8.0 => Ok(v), @@ -233,7 +268,7 @@ const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing /// with clip paths or masks becomes a folder named after the file, with mask layers over the /// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner. -fn import_to_stage(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if crate::cmds_sound::is_sound(&path) { return crate::cmds_sound::import_to_stage(s, &path); @@ -257,8 +292,20 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); } let stage = s.doc.stage; - let x = opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5); - let y = opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5); + // `cx`/`cy` centre it on a point (a drop, ADR 0059); `x`/`y` give its top-left corner. + let x = match opt_f32(p, "cx")? { + Some(cx) => cx - drawing.width * 0.5, + None => opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5), + }; + let y = match opt_f32(p, "cy")? { + Some(cy) => cy - drawing.height * 0.5, + None => opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5), + }; + let onto_active = match opt_str(p, "layer")? { + None | Some("new") => false, + Some("active") => true, + Some(other) => return Err(EngineError::Param(format!("param 'layer' must be new or active, not '{other}'"))), + }; if !(x.is_finite() && y.is_finite()) { return Err(EngineError::Param("'x' and 'y' must be numbers".into())); } @@ -270,7 +317,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { list.into_iter() .map(|e| { let id = anicraft_doc::ElementId(s.doc.alloc_id()); - Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect { alpha: e.alpha, ..Default::default() }, kind: e.kind }) + Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind }) }) .collect() }; @@ -285,7 +332,13 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { let masks = drawing.layers.iter().filter(|l| l.mask.is_some()).count(); let (width, height, report) = (drawing.width, drawing.height, drawing.report); let mut layers = drawing.layers; - let (layer_id, ids, made, folder) = if layers.len() == 1 && masks == 0 { + let (layer_id, ids, made, folder) = if onto_active && layers.len() == 1 && masks == 0 { + // Onto the active layer's keyframe at the playhead, as a drop on the stage puts it. + let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); + let ids: Vec = els.iter().map(|e| e.id).collect(); + s.editable_keyframe()?.elements.extend(els); + (s.layer, ids, 0, None) + } else if layers.len() == 1 && masks == 0 { // One layer, named after the file, as Import to Stage always made. crate::cmds_timeline::new_layer(s, &json!({"name": name}))?; let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); @@ -331,6 +384,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { let mut ml = new_layer(s, label, anicraft_doc::LayerKind::Mask, Some(fid)); // Mask layers are locked, as Animate keeps them: the mask shows, its edge hides. ml.locked = true; + ml.mask_mode = mask.mode; ml.keyframes = keys(elements(s, mask.elements)); inside = Some(ml.id); stack.push(ml); @@ -343,7 +397,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { cl.keyframes = keys(els); stack.push(cl); } - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; for (k, l) in stack.into_iter().enumerate() { tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l)); } @@ -369,6 +423,74 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { })) } +/// An SVG drawing read from `path` (size-checked), with at least one shape. +pub(crate) fn read_svg(path: &std::path::Path) -> Result { + if crate::vfs::len(path)? > MAX_IMPORT_BYTES { + return Err(EngineError::Format(format!("{} is too large to import", path.display()))); + } + let drawing = anicraft_svg::import(&crate::vfs::read(path)?).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + if drawing.is_empty() { + return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); + } + Ok(drawing) +} + +/// Whether a drawing fits on one layer (one run of artwork, nothing masked). +pub(crate) fn one_layer(d: &anicraft_svg::SvgImport) -> bool { + d.layers.len() == 1 && d.layers.iter().all(|l| l.mask.is_none()) +} + +/// Import to Library with an SVG (ADR 0065): a graphic symbol named after the file (a free +/// name at the Library's top level) holding the drawing's shapes, its registration point at +/// the drawing's centre. Clips and masks keep their mask layers inside the symbol. +pub(crate) fn import_svg_symbol(s: &mut Session, path: &std::path::Path, name: Option<&str>) -> Result { + use anicraft_doc::{Layer, LayerId, LayerKind, Symbol, SymbolId, SymbolKind, Timeline}; + let drawing = read_svg(path)?; + let stem: String = path.file_stem().map_or_else(|| "Drawing".into(), |n| n.to_string_lossy().chars().take(128).collect()); + let name = s.doc.unique_name(None, name.map_or(stem.as_str(), str::trim)); + let place = anicraft_geom::Affine::translate(-drawing.width * 0.5, -drawing.height * 0.5); + let elements = |s: &mut Session, list: Vec| -> Vec> { + list.into_iter() + .map(|e| Arc::new(anicraft_doc::Element { id: anicraft_doc::ElementId(s.doc.alloc_id()), name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind })) + .collect() + }; + let one_key = |els: Vec>| { + let mut k = anicraft_doc::Keyframe::new(0, 1); + k.elements = els; + vec![Arc::new(k)] + }; + let count = drawing.elements().count(); + let (width, height, report) = (drawing.width, drawing.height, drawing.report); + let runs = drawing.layers.len(); + // Top first: the drawing lists its runs in paint order (bottom first). + let mut layers: Vec> = Vec::new(); + for (n, l) in drawing.layers.into_iter().enumerate().rev() { + let mut parent = None; + if let Some(mask) = l.mask { + let mut ml = Layer::new(LayerId(s.doc.alloc_id()), if mask.name.is_empty() { "Mask".to_string() } else { mask.name.clone() }); + ml.kind = LayerKind::Mask; + ml.locked = true; + ml.mask_mode = mask.mode; + ml.keyframes = one_key(elements(s, mask.elements)); + parent = Some(ml.id); + layers.push(Arc::new(ml)); + } + let mut cl = Layer::new(LayerId(s.doc.alloc_id()), if runs == 1 { "Layer 1".to_string() } else { format!("Layer {}", n + 1) }); + cl.parent = parent; + cl.keyframes = one_key(elements(s, l.elements)); + layers.push(Arc::new(cl)); + } + let mut timeline = Timeline { layers }; + timeline.repair_masks(); + let id = SymbolId(s.doc.alloc_id()); + s.doc.library.push(Arc::new(Symbol { id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline })); + Ok(json!({"symbol": id.0, "name": name, "elements": count, "layers": timeline_len(s, id), "width": width, "height": height, "report": report.summary(), "skipped": report.skipped})) +} + +fn timeline_len(s: &Session, id: anicraft_doc::SymbolId) -> usize { + s.doc.library.iter().find(|x| x.id == id).map_or(0, |x| x.timeline.layers.len()) +} + /// A PNG or JPEG as a bitmap in the document, and the one shape that shows it: a rectangle of /// the image's size filled with it. JPEGs are kept as PNG (lossless, so nothing degrades). fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Result { @@ -383,6 +505,7 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Resu stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }; Ok(anicraft_svg::SvgImport::single(w, h, vec![anicraft_svg::ImportedElement { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, kind: anicraft_doc::ElementKind::Shape(shape) }])) } @@ -439,7 +562,16 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result { } // Frames render in parallel, then go onto the sheet in order. let doc = &s.doc; - let frames: Vec = (from..=to).into_par_iter().map(|f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm)).collect::>()?; + // A publish counts the frames, and stops between them when cancelled (ADR 0060). + let job = s.job.as_deref(); + let frames: Vec = (from..=to) + .into_par_iter() + .map(|f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm) + }) + .collect::>()?; let mut sheet = anicraft_render::Pixmap::new(sheet_w as u32, sheet_h as u32)?; let stride = sheet_w as usize; let delays = gif_delays(n, doc.stage.fps); @@ -567,6 +699,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result { text }); let doc = &s.doc; + let job = s.job.as_deref(); let mut written = 0u32; let mut failure: Option = None; if let Some(mut stdin) = child.stdin.take() { @@ -585,11 +718,22 @@ fn export_video(s: &mut Session, p: &Value) -> Result { } written += 1; } + if let Err(e) = crate::publish::tick(job, batch.len() as u64) { + failure = Some(e); + break; + } } } + if matches!(failure, Some(EngineError::Cancelled)) { + // Cancelled while publishing: ffmpeg stops, and its unfinished file goes. + let _ = child.kill(); + } let status = child.wait()?; let log = messages.join().unwrap_or_default(); if let Some(e) = failure { + if matches!(e, EngineError::Cancelled) { + let _ = crate::vfs::remove_file(&path); + } return Err(e); } if !status.success() || written != to - from + 1 { @@ -616,6 +760,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { // Output is identical to a serial export. Files are written here, on the command's thread, // where `vfs` knows whether they go to disk or to the browser (ADR 0036). let doc = &s.doc; + let job = s.job.as_deref(); let mut files = 0usize; let frames: Vec = (from..=to).collect(); for batch in frames.chunks(64) { @@ -624,6 +769,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?; files += 1; } + crate::publish::tick(job, batch.len() as u64)?; } Ok(json!({"frames": files, "dir": dir.display().to_string()})) } @@ -723,6 +869,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { } // Render and colour-quantize frames in parallel; encode in order. let doc = &s.doc; + let job = s.job.as_deref(); let delays = gif_delays(n as usize, doc.stage.fps); let frames: Vec> = (from..to.saturating_add(1)) .into_par_iter() @@ -732,6 +879,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { let mut rgba = pm.to_rgba8(); let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10); frame.delay = delay; + crate::publish::tick(job, 1)?; Ok(frame) }) .collect::>>()?; diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs index b3d0b131..764cebf2 100644 --- a/crates/engine/src/cmds_frames.rs +++ b/crates/engine/src/cmds_frames.rs @@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { // The pasted keys are its frames (no stray blank frame at 1). l.keyframes.clear(); } - crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.push(Arc::new(l)); + crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?.layers.push(Arc::new(l)); } let mut keys = Vec::with_capacity(sl.keys.len()); for k in &sl.keys { @@ -161,7 +161,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { } keys.push(Arc::new(k)); } - let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.get_mut(row).map(Arc::make_mut) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).ok().and_then(|tl| tl.layers.get_mut(row).map(Arc::make_mut)) else { continue }; crate::cmds_camera::keys_fit(layer.kind, keys.iter().map(|k| &**k))?; if layer.keyframe_index_at(frame).is_some() { insert_keyframe_at(layer, frame, true)?; diff --git a/crates/engine/src/cmds_group.rs b/crates/engine/src/cmds_group.rs new file mode 100644 index 00000000..a77f893d --- /dev/null +++ b/crates/engine/src/cmds_group.rs @@ -0,0 +1,375 @@ +//! Groups and Combine Objects (ADR 0073): Modify › Group (Ctrl+G) and Ungroup (Ctrl+Shift+G), and +//! Modify › Combine Objects › Union, Intersect, Punch and Crop on drawing objects. +//! +//! A group is an element holding other elements without a Library symbol +//! ([`ElementKind::Group`]): its transform and colour effect apply to its members, raw shapes +//! inside merge only with each other, and double-clicking it opens it in place like a symbol +//! (`symbol.edit`, ADR 0045). Combine Objects is exact boolean geometry on the planar map of merge +//! drawing (`anicraft_geom::planar`, ADR 0031). + +use crate::merge::{Part, remerge_with}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, LayerId, MAX_GROUP_DEPTH, Shape}; +use anicraft_geom::planar::{self, Item}; +use anicraft_geom::{Affine, FillRule, Path}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "modify.group", + "Group", + "Modify", + Some("Ctrl+G"), + "{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly: the group's transform starts as the identity. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place", + true, + (|s, p| s.each_layer(true, |s| group(s, p))) as crate::RunFn, + ), + c( + "modify.ungroup", + "Ungroup", + "Modify", + Some("Ctrl+Shift+G"), + "{} puts each selected group's members back on its layer where it was, each placed and coloured as the group showed it, and selects them; raw shapes among them merge with the drawing there → {members}", + true, + |s, p| s.each_layer(true, |s| ungroup(s, p)), + ), + c( + "modify.combine", + "Combine Objects", + "", + None, + "{op: union|intersect|punch|crop} combines the selected shapes on the active layer, bottom to top as they are stacked (ADR 0073). union: one drawing object of everything (a group of the merged pieces when they have more than one colour or keep lines); intersect: the area every one covers, in the topmost's fill and stroke; punch: the topmost's area cut out of each of the others; crop: each of the others cut to the topmost's area. Punch and crop remove the topmost. A result of one fill (or one line) is a drawing object, one of several is a group of raw shapes → {op, created}", + true, + combine_cmd, + ), + c("modify.union", "Union", "Modify/Combine Objects", None, "{} combine with op union", true, |s, _| combine(s, Op::Union)), + c("modify.intersect", "Intersect", "Modify/Combine Objects", None, "{} combine with op intersect", true, |s, _| combine(s, Op::Intersect)), + c("modify.punch", "Punch", "Modify/Combine Objects", None, "{} combine with op punch", true, |s, _| combine(s, Op::Punch)), + c("modify.crop", "Crop", "Modify/Combine Objects", None, "{} combine with op crop", true, |s, _| combine(s, Op::Crop)), + ] +} + +// ----- Group and Ungroup ---------------------------------------------------------------------- + +/// How deep groups nest inside `e` (0 for anything that is not a group). +pub(crate) fn group_depth(e: &Element) -> usize { + fn depth(e: &Element, at: usize) -> usize { + if at > MAX_GROUP_DEPTH { + return at; + } + match &e.kind { + ElementKind::Group { .. } => 1 + e.kind.group_members().iter().map(|m| depth(m, at + 1)).max().unwrap_or(0), + _ => 0, + } + } + depth(e, 0) +} + +/// How many groups are open around the timeline being edited (inside the innermost open symbol). +pub(crate) fn open_groups(s: &Session) -> usize { + s.editing.iter().rev().take_while(|l| l.open.is_group()).count() +} + +fn group(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); + if sel.is_empty() { + return Err(EngineError::State("select what to group".into())); + } + let layer_id = LayerId(s.doc.alloc_id()); + let id = ElementId(s.doc.alloc_id()); + let around = open_groups(s); + let kf = s.editable_keyframe()?; + let picked: Vec> = kf.elements.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + if picked.is_empty() { + return Err(EngineError::State("the selection is not on this keyframe".into())); + } + if picked.iter().any(|e| matches!(e.kind, ElementKind::Camera)) { + return Err(EngineError::State("the camera can't be grouped".into())); + } + let deepest = picked.iter().map(|e| group_depth(e)).max().unwrap_or(0); + if around + deepest + 1 > MAX_GROUP_DEPTH { + return Err(EngineError::State(format!("groups nest at most {MAX_GROUP_DEPTH} deep"))); + } + // Where the topmost member was, among what stays. + let top = kf.elements.iter().rposition(|e| sel.contains(&e.id)).unwrap_or(0); + let below = kf.elements.iter().take(top).filter(|e| !sel.contains(&e.id)).count(); + kf.elements.retain(|e| !sel.contains(&e.id)); + let n = picked.len(); + let g = Element { id, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer_id, picked) }; + let at = below.min(kf.elements.len()); + kf.elements.insert(at, Arc::new(g)); + s.select_only([id]); + Ok(json!({"group": id.0, "members": n})) +} + +fn ungroup(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); + let kf = s.editable_keyframe()?; + if !kf.elements.iter().any(|e| sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. })) { + return Err(EngineError::State("select a group to ungroup".into())); + } + let taken: HashSet = kf.elements.iter().filter(|e| !(sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. }))).map(|e| e.id).collect(); + let old = std::mem::take(&mut kf.elements); + let mut out = Vec::with_capacity(old.len()); + let mut members: Vec<(ElementId, bool)> = Vec::new(); + let mut clash: Vec = Vec::new(); + let mut seen = taken; + for e in old { + if !(sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. })) { + out.push(e); + continue; + } + for m in e.kind.group_members() { + let mut m = Arc::unwrap_or_clone(m); + m.transform = e.transform.mul(&m.transform); + m.color = e.color.nested(&m.color); + // Members keep their ids, unless a copy of this group was ungrouped here already. + if !seen.insert(m.id) { + clash.push(out.len()); + } + members.push((m.id, crate::merge::mergeable(&m).is_some())); + out.push(Arc::new(m)); + } + } + for i in clash { + let fresh = ElementId(s.doc.alloc_id()); + if let Some(e) = out.get_mut(i) { + let old = e.id; + Arc::make_mut(e).id = fresh; + // (The member list follows: the first entry still named the old id is this one.) + if let Some(m) = members.iter_mut().rev().find(|m| m.0 == old) { + m.0 = fresh; + } + } + } + s.editable_keyframe()?.elements = out; + // Raw shapes merge with the drawing they now stand in (Animate: what was grouped cuts and joins + // the shapes under it once it is apart), on top, as a dropped selection does. + let raw: Vec = members.iter().filter(|m| m.1).map(|m| m.0).collect(); + let mut selected: Vec = members.iter().filter(|m| !m.1).map(|m| m.0).collect(); + if !raw.is_empty() { + let kf = s.editable_keyframe()?; + let mut moving = Vec::new(); + kf.elements.retain(|e| { + let take = raw.contains(&e.id); + if take { + moving.push((**e).clone()); + } + !take + }); + selected.extend(crate::merge::merge_in(s, moving)?); + } + let n = selected.len(); + s.select_only(selected); + Ok(json!({"members": n})) +} + +// ----- Combine Objects ------------------------------------------------------------------------ + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Op { + Union, + Intersect, + Punch, + Crop, +} + +fn combine_cmd(s: &mut Session, p: &Value) -> Result { + let op = match str_req(p, "op")?.trim().to_ascii_lowercase().as_str() { + "union" => Op::Union, + "intersect" => Op::Intersect, + "punch" => Op::Punch, + "crop" => Op::Crop, + other => return Err(EngineError::Param(format!("unknown op '{other}' (union, intersect, punch or crop)"))), + }; + combine(s, op) +} + +/// `e`'s shape, as a raw shape in keyframe space would merge it. +fn as_raw(e: &Element, sh: &Shape) -> Element { + let mut raw = e.clone(); + let mut sh = sh.clone(); + sh.merge = true; + raw.kind = ElementKind::Shape(sh); + raw +} + +/// `paths` one after another, as one path. +fn joined<'a>(paths: impl IntoIterator) -> Path { + let mut out = Path::default(); + for p in paths { + out.cmds.extend(p.cmds.iter().copied()); + } + out +} + +/// The area `path` (keyframe space) fills with `rule`, as outlines that don't overlap, so even-odd +/// and non-zero agree on it: open subpaths closed, overlaps resolved. `None` when it is too large +/// to merge, empty when it covers nothing. +fn area(path: &Path, rule: FillRule) -> Option { + let m = planar::merge(&[Item { path, fill: Some(0), fill_rule: rule, stroke: None }])?; + Some(joined(m.fills.iter().map(|p| &p.path))) +} + +/// A drawing object of `path` (keyframe space), its local origin at the centre of its bounds as the +/// drawing tools place shapes. +fn object(doc: &mut anicraft_doc::Document, path: &Path, fill: Option, stroke: Option, color: ColorEffect) -> Element { + let c = path.bounds().center(); + let to_local = Affine::translate(-c.x, -c.y); + Element { + id: ElementId(doc.alloc_id()), + name: String::new(), + transform: Affine::translate(c.x, c.y), + color, + kind: ElementKind::Shape(Shape { path: Arc::new(path.transformed(&to_local)), fill: fill.map(|f| f.transformed(&to_local)), stroke, fill_rule: FillRule::NonZero, merge: false, warp: None }), + } +} + +/// Raw pieces (from a merge) as one result: a lone piece becomes a drawing object, several a group +/// of the raw pieces (they keep merging with each other inside it). `None` for no pieces. +fn result_of(s: &mut Session, pieces: Vec>) -> Option { + match pieces.len() { + 0 => None, + 1 => pieces.into_iter().next().map(|p| { + let mut e = Arc::unwrap_or_clone(p); + if let ElementKind::Shape(sh) = &mut e.kind { + sh.merge = false; + } + e + }), + _ => { + // Fills of one look, with no line left, are one object. + let first = pieces.first().and_then(|p| match &p.kind { + ElementKind::Shape(sh) if sh.stroke.is_none() => sh.fill.clone().map(|f| (f.transformed(&p.transform), p.color)), + _ => None, + }); + let same = first.as_ref().is_some_and(|(f0, c0)| { + pieces.iter().all(|p| matches!(&p.kind, ElementKind::Shape(sh) if sh.stroke.is_none() && p.color == *c0 && sh.fill.as_ref().is_some_and(|f| crate::merge::same_paint(&f.transformed(&p.transform), f0)))) + }); + if let (true, Some((fill, color))) = (same, first) { + let outline: Vec = pieces.iter().filter_map(|p| match &p.kind { + ElementKind::Shape(sh) => Some(sh.path.transformed(&p.transform)), + _ => None, + }).collect(); + return Some(object(&mut s.doc, &joined(outline.iter()), Some(fill), None, color)); + } + let layer = LayerId(s.doc.alloc_id()); + Some(Element { id: ElementId(s.doc.alloc_id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer, pieces) }) + } + } +} + +const TOO_LARGE: &str = "the shapes are too complex to combine at once"; + +fn combine(s: &mut Session, op: Op) -> Result { + let sel = s.selection.on(s.layer); + if s.selected_layers().len() > 1 { + return Err(EngineError::State("Combine Objects works on one layer: select shapes on one layer".into())); + } + let els = s.editable_keyframe()?.elements.clone(); + // The selected shapes, bottom to top, with their index. + let mut shapes: Vec<(usize, Arc)> = Vec::new(); + for (i, e) in els.iter().enumerate().filter(|(_, e)| sel.contains(&e.id)) { + match &e.kind { + ElementKind::Shape(_) => shapes.push((i, e.clone())), + _ => return Err(EngineError::State("Combine Objects works on shapes and drawing objects: break symbols, text and groups apart first (Ctrl+B)".into())), + } + } + if shapes.len() < 2 { + return Err(EngineError::State("select two or more shapes to combine".into())); + } + let shape = |e: &Element| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }; + // (index in the keyframe, what replaces it) + let mut results: Vec<(usize, Option)> = Vec::new(); + match op { + Op::Union => { + let raw: Vec = shapes.iter().filter_map(|(_, e)| shape(e).map(|sh| as_raw(e, &sh))).collect(); + let parts: Vec = raw.iter().map(|e| Part::Shape(e, false)).collect(); + let merged = remerge_with(s, &parts, None).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let top = shapes.last().map_or(0, |x| x.0); + let one = result_of(s, merged.out); + results.push((top, one)); + } + Op::Intersect => { + let (bottom, rest) = shapes.split_first().ok_or_else(|| EngineError::State("select two or more shapes to combine".into()))?; + let sh = shape(&bottom.1).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("Intersect needs shapes with fills".into()))?; + let mut region = area(&sh.path.transformed(&bottom.1.transform), sh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + for (_, e) in rest { + let sh = shape(e).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("Intersect needs shapes with fills".into()))?; + let cutter = area(&sh.path.transformed(&e.transform), sh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let m = planar::merge_cut(&[Item { path: ®ion, fill: Some(0), fill_rule: FillRule::EvenOdd, stroke: None }], &cutter).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + region = joined(m.fills.iter().filter(|p| p.inside).map(|p| &p.path)); + } + if region.cmds.is_empty() { + return Err(EngineError::State("the shapes don't all overlap: nothing is left to intersect".into())); + } + // In the topmost's fill and stroke (Animate). + let (top_i, top) = shapes.last().map(|(i, e)| (*i, e.clone())).ok_or_else(|| EngineError::State("nothing to combine".into()))?; + let tsh = shape(&top).ok_or_else(|| EngineError::State("nothing to combine".into()))?; + let fill = tsh.fill.map(|f| f.transformed(&top.transform)); + let stroke = tsh.stroke.map(|st| st.scaled(top.transform.mean_scale())); + let made = object(&mut s.doc, ®ion, fill, stroke, top.color); + results.push((top_i, Some(made))); + } + Op::Punch | Op::Crop => { + let (top, lower) = shapes.split_last().ok_or_else(|| EngineError::State("select two or more shapes to combine".into()))?; + let tsh = shape(&top.1).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("the topmost shape cuts with its fill: give it one".into()))?; + let cutter = area(&tsh.path.transformed(&top.1.transform), tsh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + results.push((top.0, None)); + for (i, e) in lower { + let Some(sh) = shape(e) else { continue }; + let raw = as_raw(e, &sh); + let merged = remerge_with(s, &[Part::Shape(&raw, false)], Some(&cutter)).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let keep: Vec> = merged.out.into_iter().filter(|p| merged.inside.contains(&p.id) == (op == Op::Crop)).collect(); + let one = result_of(s, keep); + results.push((*i, one)); + } + } + } + // The sources go; each result takes its source's place. + let gone: HashSet = shapes.iter().map(|x| x.0).collect(); + let mut created = Vec::new(); + let mut out = Vec::with_capacity(els.len()); + for (i, e) in els.into_iter().enumerate() { + if !gone.contains(&i) { + out.push(e); + continue; + } + if let Some(r) = results.iter_mut().find(|(at, _)| *at == i).and_then(|(_, r)| r.take()) { + created.push(r.id); + out.push(Arc::new(r)); + } + } + if created.is_empty() && op != Op::Punch { + return Err(EngineError::State("nothing would be left".into())); + } + s.editable_keyframe()?.elements = out; + s.select_only(created.iter().copied()); + Ok(json!({"op": format!("{op:?}").to_ascii_lowercase(), "created": created.iter().map(|e| e.0).collect::>()})) +} + +/// The area `path` fills even-odd, from its flattening: each loop's area, added or taken away by +/// how many other loops hold it (an analytic check for the tests). +#[cfg(test)] +pub(crate) fn even_odd_area(path: &Path, m: &Affine) -> f64 { + let loops: Vec> = path.flatten(m, 0.005).into_iter().map(|l| l.points).filter(|p| p.len() > 2).collect(); + let signed = |pts: &[anicraft_geom::Vec2]| -> f64 { pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y)).sum::() * 0.5 }; + let holds = |pts: &[anicraft_geom::Vec2], p: anicraft_geom::Vec2| pts.iter().zip(pts.iter().cycle().skip(1)).filter(|(a, b)| (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x)).count() % 2 == 1; + let mut total = 0.0; + for (i, l) in loops.iter().enumerate() { + // A point just inside the loop's first edge would do; its middle vertex is near enough for + // loops that don't touch (the merge's pieces never cross). + let Some(&p) = l.first() else { continue }; + let depth = loops.iter().enumerate().filter(|(j, o)| *j != i && holds(o, p)).count(); + total += signed(l).abs() * if depth % 2 == 0 { 1.0 } else { -1.0 }; + } + total +} diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs new file mode 100644 index 00000000..68879759 --- /dev/null +++ b/crates/engine/src/cmds_layer.rs @@ -0,0 +1,200 @@ +//! Layer view properties saved in the document (ADR 0061): each layer's onion skin toggle, its +//! colour (outlines and the timeline bar), View as Outlines, its row height, and Layer +//! Properties, which sets several of them (and the name, type, show and lock) as one step. +//! A mask layer's mask type (ADR 0070) is set here too: by area (Animate's masks), by the +//! artwork's opacity, or by its brightness. +//! +//! Behaviour learned from Adobe's public help pages on layers and onion skinning and from +//! watching the program; nothing was copied. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT, MaskMode}; +use serde_json::{Value, json}; +use std::sync::Arc; + +/// Layer colours offered next to the colour picker (sRGB): those new layers take in turn, +/// then a few more, all bright enough to read as outlines on a dark or a light stage. +pub const LAYER_COLORS: [u32; 12] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65, 0xf06292, 0xaed581, 0x9575cd, 0xe0e0e0, 0x8d6e63]; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "layer.set_onion", + "Onion Skin Layer", + "", + None, + "{onion?: bool (default: the other way), solo?: bool, layer?} whether onion skin draws the layer's frames around the playhead. solo: only this layer is onion-skinned (every other layer off); solo again on the only layer on turns them all back on (Alt-click)", + true, + set_onion as crate::RunFn, + ), + c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), + c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_mask", + "Mask Type", + "", + None, + "{mask: coverage|alpha|luminance, layer?} how a mask layer reveals the layers it masks: coverage (its fills' area, as in Animate), alpha (its artwork's opacity: gradients and faded shapes make soft edges) or luminance (its brightness: white shows, black hides; SVG's mask) (ADR 0070)", + true, + set_mask, + ), + c( + "layer.set_properties", + "Layer Properties", + "Modify/Timeline", + None, + "{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", + true, + set_properties, + ), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + ] +} + +fn layer_id(s: &Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + s.timeline().layer(id).map(|_| id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) +} + +/// Whether a layer of this kind has frames onion skin can show (folders and the camera don't). +fn onion_able(l: &Layer) -> bool { + !matches!(l.kind, LayerKind::Folder | LayerKind::Camera) +} + +fn set_onion(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + let solo = opt_bool(p, "solo")?.unwrap_or(false); + let on = opt_bool(p, "onion")?; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; + if solo { + // Animate's Alt-click: this layer alone; again on the only one left on, every layer. + let alone = tl.layers.iter().filter(|l| onion_able(l)).all(|l| l.onion == (l.id == id)); + for l in tl.layers.iter_mut().filter(|l| onion_able(l)) { + let want = alone || l.id == id; + if l.onion != want { + Arc::make_mut(l).onion = want; + } + } + } else { + let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + l.onion = on.unwrap_or(!l.onion); + } + let on: Vec = tl.layers.iter().filter(|l| onion_able(l) && l.onion).map(|l| l.id.0).collect(); + let onion = tl.layer(id).is_some_and(|l| l.onion); + Ok(json!({"layer": id.0, "onion": onion, "onion_layers": on})) +} + +fn set_color(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' (like \"#ff8800\") is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + // A layer colour is opaque: it draws hairlines and a bar. + l.color = color.with_alpha(1.0); + Ok(json!({"color": l.color.to_hex()})) +} + +/// `height` in percent (100, 200 or 300) as rows. +fn height_param(p: &Value) -> Result> { + match opt_u32(p, "height")? { + None => Ok(None), + Some(h) if h > 0 && h % 100 == 0 && h / 100 <= u32::from(MAX_LAYER_HEIGHT) => Ok(u8::try_from(h / 100).ok()), + Some(_) => Err(EngineError::Param("param 'height' must be 100, 200 or 300 (percent)".into())), + } +} + +fn set_height(s: &mut Session, p: &Value) -> Result { + let rows = height_param(p)?.ok_or_else(|| EngineError::Param("param 'height' (100, 200 or 300) is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + l.height_rows = rows; + Ok(json!({"height": u32::from(l.height()) * 100})) +} + +/// `mask`: a mask type's key. +fn mask_param(p: &Value) -> Result> { + opt_str(p, "mask")?.map(|k| MaskMode::from_key(k).ok_or_else(|| EngineError::Param(format!("'mask' is coverage, alpha or luminance, not '{k}'")))).transpose() +} + +fn set_mask(s: &mut Session, p: &Value) -> Result { + let mode = mask_param(p)?.ok_or_else(|| EngineError::Param("param 'mask' (coverage, alpha or luminance) is required".into()))?; + let id = layer_id(s, p)?; + let l = s.layer_mut(Some(id))?; + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = mode; + Ok(json!({"layer": id.0, "mask": mode.key()})) +} + +fn set_properties(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + // Every param is read (and checked) before anything changes. + let name: Option = opt_str(p, "name")?.map(|n| n.chars().take(128).collect()); + if name.as_ref().is_some_and(|n| n.trim().is_empty()) { + return Err(EngineError::Param("layer name must not be empty".into())); + } + let ty = opt_str(p, "type")?; + let color = opt_color(p, "color")?; + let outline = opt_bool(p, "outline")?; + let height = height_param(p)?; + let mask = mask_param(p)?; + let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); + if let Some(ty) = ty { + let now = crate::cmds_timeline::layer_type_json(s, id); + if now.get("type").and_then(Value::as_str) != Some(ty) { + crate::cmds_timeline::set_type(s, id, ty)?; + } + } + let l = s.layer_mut(Some(id))?; + if let Some(m) = mask { + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = m; + } + if let Some(n) = name { + l.name = n; + } + if let Some(c) = color { + l.color = c.with_alpha(1.0); + } + if let Some(o) = outline { + l.outline = o; + } + if let Some(h) = height { + l.height_rows = h; + } + if let Some(v) = visible { + l.visible = v; + } + if let Some(v) = locked { + l.locked = v; + } + if let Some(v) = onion { + l.onion = v; + } + properties(s, id) +} + +fn properties(s: &Session, id: LayerId) -> Result { + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let ty = crate::cmds_timeline::layer_type_json(s, id).get("type").cloned().unwrap_or(Value::Null); + Ok(json!({ + "layer": id.0, + "name": l.name, + "type": ty, + "mask": (l.kind == LayerKind::Mask).then(|| l.mask_mode.key()), + "color": l.color.to_hex(), + "outline": l.outline, + "height": u32::from(l.height()) * 100, + "visible": l.visible, + "locked": l.locked, + "onion": l.onion, + })) +} + +#[cfg(test)] +#[path = "cmds_layer_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs new file mode 100644 index 00000000..92006344 --- /dev/null +++ b/crates/engine/src/cmds_layer_tests.rs @@ -0,0 +1,302 @@ +//! Layer view properties (ADR 0061): onion toggles and solo, colour, View as Outlines (on the +//! stage only), row height, Layer Properties as one step, the file, and onion skin of the +//! timeline around a symbol open in place. + +use crate::Session; +use crate::onion::{Markers, OnionSkin}; +use anicraft_doc::{ElementId, LayerId, Rgba}; +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}")) +} + +fn rect(s: &mut Session, x: f32) -> ElementId { + ElementId(run(s, "draw.rect", json!({"x": x, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()) +} + +/// Two layers, each a square that moves 40 px right on frames 0, 2 and 4: `top` starts at x 0, +/// `bottom` at x 200. The playhead is on frame 2. +fn two_walks() -> (Session, LayerId, LayerId) { + let mut s = Session::default(); + let bottom = s.layer; + let b = rect(&mut s, 200.0); + let top = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let t = rect(&mut s, 0.0); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + for (l, e) in [(bottom, b), (top, t)] { + run(&mut s, "layer.select", json!({"layer": l.0})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [e.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + } + run(&mut s, "timeline.goto", json!({"frame": 2})); + (s, top, bottom) +} + +fn layer(s: &Session, id: LayerId) -> &anicraft_doc::Layer { + s.timeline().layer(id).unwrap() +} + +/// What the stage shows with `skin`: the layers and left edges of the onion frames (tinted items). +fn ghosts(s: &Session, skin: &OnionSkin) -> Vec<(LayerId, f32)> { + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(skin)); + dl.items.iter().filter(|i| !i.color.is_identity()).map(|i| (i.layer, i.path.bounds().transformed(&i.transform).min.x)).collect() +} + +#[test] +fn a_layer_with_onion_off_is_not_onion_skinned() { + let (mut s, top, bottom) = two_walks(); + let skin = OnionSkin { keyframes_only: true, ..OnionSkin::default() }; + let mut both = ghosts(&s, &skin); + both.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(both, vec![(top, 0.0), (top, 80.0), (bottom, 200.0), (bottom, 280.0)], "frames 0 and 4 on both layers"); + let r = run(&mut s, "layer.set_onion", json!({"layer": bottom.0})); + assert_eq!(r["onion"], false, "toggles"); + assert!(!layer(&s, bottom).onion && layer(&s, top).onion); + assert!(ghosts(&s, &skin).iter().all(|(l, _)| *l == top), "only the top layer's frames show"); + // Its playhead frame still shows, at full strength. + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&skin)); + assert!(dl.items.iter().any(|i| i.layer == bottom && i.color.is_identity())); + // Edit Multiple Frames isn't onion skin: it still shows and edits the layer's keyframes. + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert!(s.multi_frame_items(0, 4).iter().any(|(it, _)| it.layer == bottom && it.frame == 0)); + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&multi)); + assert_eq!(dl.items.iter().filter(|i| i.layer == bottom).count(), 3); + // Undo brings it back. + run(&mut s, "edit.undo", json!({})); + assert!(layer(&s, bottom).onion); + assert!(s.execute("layer.set_onion", &json!({"layer": 999_999})).is_err()); + assert!(s.execute("layer.set_onion", &json!({"onion": "yes"})).is_err()); +} + +#[test] +fn solo_onion_keeps_one_layer_and_again_brings_back_all() { + let (mut s, top, bottom) = two_walks(); + let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap()); + let r = run(&mut s, "layer.set_onion", json!({"layer": top.0, "solo": true})); + assert_eq!(r["onion_layers"], json!([top.0])); + assert!(layer(&s, top).onion && !layer(&s, bottom).onion); + assert!(layer(&s, folder).onion, "a folder has no frames to onion-skin; solo leaves it"); + // Solo on another layer moves the solo there. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(!layer(&s, top).onion && layer(&s, bottom).onion); + // Again on the only layer left on: every layer is on again. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(layer(&s, top).onion && layer(&s, bottom).onion); + // Setting it outright. + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + assert!(!layer(&s, top).onion); +} + +#[test] +fn outlines_use_the_layer_colour_on_the_stage_only() { + let mut s = Session::default(); + let l = s.layer; + rect(&mut s, 10.0); + run(&mut s, "layer.set_color", json!({"color": "#ff8800"})); + run(&mut s, "layer.toggle_outline", json!({})); + let orange = Rgba::hex(0xff8800); + assert_eq!(layer(&s, l).color, orange); + // The stage: hairlines in the layer's colour. + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(s.display_list().items.iter().all(|i| i.outline == Some(orange))); + // The movie (every export), and the player, draw the artwork as it is. + let movie = anicraft_doc::evaluate(&s.doc, 0); + assert!(!movie.items.is_empty() && movie.items.iter().all(|i| i.outline.is_none())); + let player = anicraft_doc::evaluate_player(&s.doc, &anicraft_doc::player::PlayerState::default()); + assert!(player.items.iter().all(|i| i.outline.is_none())); + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(!svg.to_ascii_lowercase().contains("ff8800"), "no outline colour in an SVG export"); + let png = |s: &Session| { + let view = anicraft_render::View { transform: anicraft_geom::Affine::IDENTITY, width: 40, height: 40, background: Some(Rgba::WHITE) }; + anicraft_render::render(&anicraft_doc::evaluate(&s.doc, 0), &view).unwrap().0.to_rgba8() + }; + let outlined = png(&s); + run(&mut s, "layer.toggle_outline", json!({})); + assert_eq!(outlined, png(&s), "an export looks the same with or without outline mode"); + // Inside a symbol on an outlined layer, the stage outlines everything in the layer's colour. + run(&mut s, "layer.toggle_outline", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(!stage.items.is_empty() && stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(anicraft_doc::evaluate(&s.doc, 0).items.iter().all(|i| i.outline.is_none())); + // A colour is opaque, and a bad one is refused. + run(&mut s, "layer.set_color", json!({"color": "#00ff0080"})); + assert_eq!(layer(&s, l).color.a, 1.0); + assert!(s.execute("layer.set_color", &json!({"color": "green"})).is_err()); + assert!(s.execute("layer.set_color", &json!({})).is_err()); +} + +#[test] +fn layer_height_is_100_200_or_300_percent() { + let mut s = Session::default(); + let l = s.layer; + assert_eq!(layer(&s, l).height(), 1); + assert_eq!(run(&mut s, "layer.set_height", json!({"height": 300}))["height"], 300); + assert_eq!(layer(&s, l).height(), 3); + for bad in [json!(0), json!(150), json!(400), json!(-100), json!("tall")] { + assert!(s.execute("layer.set_height", &json!({"height": bad})).is_err(), "{bad}"); + } + assert!(s.execute("layer.set_height", &json!({})).is_err()); + assert_eq!(layer(&s, l).height(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, l).height(), 1); +} + +#[test] +fn layer_properties_set_everything_as_one_step_or_nothing() { + let (mut s, top, bottom) = two_walks(); + let undo = s.history.undo_len(); + let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "mask": null, "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); + // The same type again changes nothing (a masked layer stays masked by the same mask). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "guide"})); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["type"], "guide"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let back = run(&mut s, "layer.properties", json!({"layer": bottom.0})); + assert_eq!((back["name"].as_str(), back["type"].as_str(), back["height"].as_u64()), (Some("Layer 1"), Some("normal"), Some(100))); + // A bad value anywhere changes nothing. + for bad in [json!({"name": " "}), json!({"name": "X", "height": 250}), json!({"name": "X", "color": "red"}), json!({"name": "X", "type": "masked"}), json!({"name": "X", "type": "banana"}), json!({"name": "X", "locked": 1})] { + let mut p = bad.clone(); + p["layer"] = json!(top.0); + assert!(s.execute("layer.set_properties", &p).is_err(), "{bad}"); + assert_eq!(layer(&s, top).name, "Layer 2", "{bad}"); + } + assert!(s.execute("layer.properties", &json!({"layer": 999_999})).is_err()); +} + +#[test] +fn a_mask_layer_takes_a_mask_type() { + let (mut s, top, bottom) = two_walks(); + // Only a mask layer has one. + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "alpha"})).is_err()); + assert!(s.execute("layer.set_properties", &json!({"layer": top.0, "name": "X", "mask": "alpha"})).is_err()); + assert_eq!(layer(&s, top).name, "Layer 2", "nothing changed"); + // Made a mask and soft in one step; then by itself. + let r = run(&mut s, "layer.set_properties", json!({"layer": top.0, "type": "mask", "mask": "luminance"})); + assert_eq!((r["type"].as_str(), r["mask"].as_str()), (Some("mask"), Some("luminance"))); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); + assert_eq!(run(&mut s, "layer.set_mask", json!({"layer": top.0, "mask": "alpha"}))["mask"], "alpha"); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "soft"})).is_err()); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0})).is_err()); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["mask"], Value::Null); + // The stage shows it at once: the masked square at its edge (art opaque → fully shown). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "masked"})); + let dl = s.display_list(); + assert_eq!(dl.clip_mode(0), anicraft_doc::MaskMode::Alpha); + // Undo goes back to luminance, then to coverage. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); +} + +#[test] +fn onion_and_height_are_saved_and_older_files_open_with_the_defaults() { + let (mut s, top, bottom) = two_walks(); + run(&mut s, "layer.set_onion", json!({"layer": top.0})); + run(&mut s, "layer.set_height", json!({"layer": bottom.0, "height": 200})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let tl = back.timeline(0); + assert!(!tl.layer(top).unwrap().onion && tl.layer(bottom).unwrap().onion); + assert_eq!((tl.layer(top).unwrap().height(), tl.layer(bottom).unwrap().height()), (1, 2)); + // Defaults are left out of the file, so older files and files without them read the same. + let v: Value = serde_json::from_str(&text).unwrap(); + fn find(v: &Value, id: u64) -> Option { + match v { + Value::Object(m) if m.get("id") == Some(&json!(id)) && m.contains_key("keyframes") => Some(v.clone()), + Value::Object(m) => m.values().find_map(|x| find(x, id)), + Value::Array(a) => a.iter().find_map(|x| find(x, id)), + _ => None, + } + } + let by_id = |id: LayerId| find(&v, id.0).unwrap_or_default(); + assert!(by_id(top).get("name").is_some()); + assert_eq!((by_id(top).get("onion"), by_id(top).get("height")), (Some(&json!(false)), None)); + assert_eq!((by_id(bottom).get("onion"), by_id(bottom).get("height")), (None, Some(&json!(2)))); + let old: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Old"})).unwrap(); + assert!(old.onion && old.height() == 1); + // A height out of range in a file reads as the nearest one. + let tall: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Tall", "height": 200})).unwrap(); + assert_eq!(tall.height(), 3); +} + +/// A scene with a square walking on a second layer (x 0, 40, 80 on frames 0, 2, 4), and an +/// instance of a symbol on the first, open in place on frame 2 of the scene. +fn parent_walk() -> (Session, LayerId) { + let mut s = Session::default(); + let host = s.layer; + rect(&mut s, 300.0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let inst = s.selection.ids().next().unwrap(); + let walker = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let w = rect(&mut s, 0.0); + run(&mut s, "timeline.insert_frame", json!({"layer": host.0, "frame": 0, "count": 4})); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [w.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "layer.select", json!({"layer": host.0})); + run(&mut s, "timeline.goto", json!({"frame": 2})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + assert_eq!(s.editing.len(), 1); + (s, walker) +} + +#[test] +fn onion_skin_inside_a_symbol_shows_the_parent_timeline_frames_dimmed() { + let (s, walker) = parent_walk(); + let pic = s.stage_picture(); + let front = pic.front.clone().unwrap(); + let parent = front.parent.clone().expect("the scene shows around the symbol"); + assert_eq!(parent.frame, 2); + let skin = OnionSkin { markers: Markers::Relative { before: 2, after: 2 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin); + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + // The walker on the scene: frame 2 (x 40) dimmed, frames 0 and 4 (x 0, 80) tinted and fainter. + let mut walk: Vec<(f32, f32, bool)> = dl.items.iter().filter(|i| left(i) < 150.0).map(|i| (left(i), dl.effective_alpha(i), i.color.changes_colour())).collect(); + walk.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert_eq!(walk.iter().map(|w| w.0).collect::>(), vec![0.0, 40.0, 80.0], "the parent's onion frames around its frame 2"); + let dim = parent.dim; + assert!((walk[1].1 - dim).abs() < 1e-4 && !walk[1].2, "the parent's own frame as dim as without onion skin"); + assert!(walk[0].2 && walk[2].2 && walk[0].1 < dim && walk[2].1 < dim, "its onion frames tinted, dimmer still"); + // The open symbol is in front at full strength. + let box_item = dl.items.iter().find(|i| left(i) >= 290.0).unwrap(); + assert!((dl.effective_alpha(box_item) - 1.0).abs() < 1e-4); + assert!(dl.items.last().is_some_and(|i| left(i) >= 290.0), "drawn over everything around it"); + // Without onion skin the picture is as before; the parent's layer toggle and Edit Multiple + // Frames (the open symbol's frames only) leave its onion frames out. + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + assert_eq!(plain.items.len(), 2); + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi).items.len(), 2); + let mut off = s; + run(&mut off, "symbol.exit", json!({})); + let inst = off.selection.ids().next().unwrap(); + run(&mut off, "layer.set_onion", json!({"layer": walker.0})); + run(&mut off, "symbol.edit", json!({"id": inst.0})); + let pic = off.stage_picture(); + let front = pic.front.clone().unwrap(); + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin).items.len(), 2); +} + +#[test] +fn plug_ins_may_set_layer_properties() { + for id in ["layer.set_onion", "layer.set_color", "layer.set_height", "layer.set_properties", "layer.properties"] { + assert!(crate::find_command(id).is_some(), "{id}"); + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index a607bec6..46f2fa89 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -182,7 +182,7 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { Ok(json!({"folder": id.0, "name": name})) } -fn rename(s: &mut Session, p: &Value) -> Result { +pub(crate) fn rename(s: &mut Session, p: &Value) -> Result { let e = entry_of(p)?; if !s.doc.has_entry(e) { return Err(EngineError::State(format!("the Library has no {}", describe(e)))); @@ -284,13 +284,19 @@ pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec) -> usize { + strip_in(tl, gone, 0) +} + +/// [`strip`], inside groups too (ADR 0073): a group keeps its other members. +fn strip_in(tl: &mut Timeline, gone: &HashSet, depth: usize) -> usize { let refers = |e: &anicraft_doc::Element| match &e.kind { ElementKind::Symbol { symbol, .. } => gone.contains(&LibraryItem::Symbol(*symbol)), ElementKind::Shape(sh) => matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if gone.contains(&LibraryItem::Bitmap(*bitmap))), - ElementKind::Text(_) | ElementKind::Camera => false, + ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => false, }; + let inside = |e: &anicraft_doc::Element| matches!(&e.kind, ElementKind::Group { members } if depth < anicraft_doc::MAX_GROUP_DEPTH && strip_needed(members, gone)); let sounds = |k: &anicraft_doc::Keyframe| k.sound.as_ref().is_some_and(|f| gone.contains(&LibraryItem::Sound(f.sound))); - let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e)); + let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e) || inside(e)); let mut n = 0; for l in tl.layers.iter_mut().filter(|l| l.keyframes.iter().any(|k| hit(k))) { for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| hit(k)) { @@ -302,6 +308,11 @@ fn strip(tl: &mut Timeline, gone: &HashSet) -> usize { let before = k.elements.len(); k.elements.retain(|e| !refers(e)); n += before - k.elements.len(); + for e in k.elements.iter_mut().filter(|e| inside(e)) { + if let ElementKind::Group { members } = &mut Arc::make_mut(e).kind { + n += strip_in(members, gone, depth + 1); + } + } } } n @@ -412,29 +423,14 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result { /// the old bitmap's. Any other shape filled with a bitmap keeps its outline and fill transform. fn swap_bitmap(s: &mut Session, p: &Value) -> Result { let to = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); - let Some(new) = s.doc.bitmap(to).map(|b| (b.name.clone(), b.width as f32, b.height as f32)) else { + if s.doc.bitmap(to).is_none() { return Err(EngineError::State(format!("no bitmap with id {}", to.0))); - }; + } let sizes: std::collections::HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); let mut swapped = 0; for e in s.selected_elements_mut()? { - let ElementKind::Shape(sh) = &mut e.kind else { continue }; - let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { continue }; - let old = *bitmap; - *bitmap = to; - swapped += 1; - if old == to { - continue; - } - if let Some((name, w, h)) = sizes.get(&old) - && !*repeat - && *matrix == anicraft_geom::Affine::IDENTITY - && *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h) - { - sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2)); - if e.name == *name { - e.name.clone_from(&new.0); - } + if swap_bitmap_of(e, to, &sizes) { + swapped += 1; } } if swapped == 0 { @@ -443,6 +439,32 @@ fn swap_bitmap(s: &mut Session, p: &Value) -> Result { Ok(json!({"swapped": swapped, "bitmap": to.0})) } +/// Makes a bitmap-filled shape show bitmap `to` (Swap Bitmap, and Find and Replace, ADR 0058): +/// a placed bitmap (a rectangle of the old bitmap's size, filled once at the origin) takes the +/// new one's size and, when it had the old one's name, its name; any other shape keeps its +/// outline and fill transform. `sizes` are every bitmap's name, width and height. False when `e` +/// isn't filled with a bitmap. +pub(crate) fn swap_bitmap_of(e: &mut anicraft_doc::Element, to: BitmapId, sizes: &std::collections::HashMap) -> bool { + let ElementKind::Shape(sh) = &mut e.kind else { return false }; + let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { return false }; + let old = *bitmap; + *bitmap = to; + if old == to { + return true; + } + if let (Some((name, w, h)), Some(new)) = (sizes.get(&old), sizes.get(&to)) + && !*repeat + && *matrix == anicraft_geom::Affine::IDENTITY + && *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h) + { + sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2)); + if e.name == *name { + e.name.clone_from(&new.0); + } + } + true +} + #[cfg(test)] #[path = "library_tests.rs"] mod tests; diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index defc4498..6ee3ee81 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -68,17 +68,19 @@ impl Clipboard { } } -fn symbol_refs(e: &Element) -> Option { +/// The symbols `e` places: itself, or what is inside it as a group (ADR 0073). +fn symbol_refs(e: &Element) -> Vec { match &e.kind { - ElementKind::Symbol { symbol, .. } => Some(*symbol), - ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Symbol { symbol, .. } => vec![*symbol], + ElementKind::Group { .. } => anicraft_doc::expand_groups(std::slice::from_ref(&Arc::new(e.clone()))).iter().filter_map(|m| if let ElementKind::Symbol { symbol, .. } = m.kind { Some(symbol) } else { None }).collect(), + ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => Vec::new(), } } /// Symbols reachable from `roots` (bounded walk; libraries may be cyclic). pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec> { let mut seen: HashSet = HashSet::new(); - let mut stack: Vec = roots.iter().filter_map(symbol_refs).collect(); + let mut stack: Vec = roots.iter().flat_map(symbol_refs).collect(); let mut out = Vec::new(); while let Some(id) = stack.pop() { if !seen.insert(id) || seen.len() > 10_000 { @@ -87,7 +89,7 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec let Some(sym) = s.doc.library.iter().find(|x| x.id == id) else { continue }; for l in &sym.timeline.layers { for k in &l.keyframes { - stack.extend(k.elements.iter().filter_map(|e| symbol_refs(e))); + stack.extend(k.elements.iter().flat_map(|e| symbol_refs(e))); } } out.push(sym.clone()); @@ -183,7 +185,7 @@ fn layer_targets(s: &mut Session, src: &[(LayerId, String)]) -> Result Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - 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.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", 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, its anchors pinned to frames (pins) and where the object is", false, info), @@ -75,7 +75,7 @@ pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Optio /// the base back. On the span's first frame a property without keys changes the base itself. pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let scene = s.scene; - let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(e.layer) else { return }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).ok().and_then(|tl| tl.layer_mut(e.layer)) else { return }; let Some(kf) = layer.keyframe_starting_at(e.start).and_then(|i| layer.keyframe_mut(i)) else { return }; let Some(idx) = kf.elements.iter().position(|x| x.id == e.target) else { return }; let Some(after) = kf.elements.get(idx).map(|x| (**x).clone()) else { return }; @@ -111,7 +111,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let v = was.get(p) + d; if e.offset == 0 && m.track(p).is_none() { new_base.set(p, v); - if matches!(p, Property::Alpha | Property::Tint) { + if p.style().is_some() { base_color = true; } else { base_xf = true; @@ -120,8 +120,8 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { m.set_key(p, e.offset, v, base_props.get(p)); } } - let tracks_xf = m.tracks.iter().any(|t| !matches!(t.property, Property::Alpha | Property::Tint)); - let tracks_color = m.tracks.iter().any(|t| matches!(t.property, Property::Alpha | Property::Tint)); + let tracks_xf = m.tracks.iter().any(|t| t.property.style().is_none()); + let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some()); let mut base = after; // Exact where nothing is keyed on the first frame: the edited object is the new base. base.transform = match (base_xf, e.offset == 0 && !tracks_xf) { @@ -131,8 +131,9 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { }; base.color = match (base_color, e.offset == 0 && !tracks_color) { (true, true) => base.color, - (true, false) => ColorEffect { alpha: (new_base.get(Property::Alpha) / 100.0).clamp(0.0, 1.0), tint: base.color.tint, tint_amount: (new_base.get(Property::Tint) / 100.0).clamp(0.0, 1.0) }, - (false, _) => ColorEffect { tint: base.color.tint, ..e.base.color }, + // The edit's style, from the new values (ADR 0056). + (true, false) => new_base.color_effect(&[base.color.style()]), + (false, _) => e.base.color, }; if let Some(slot) = kf.elements.get_mut(idx) { *slot = Arc::new(base); diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index d878ed7d..411447a6 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -1,4 +1,5 @@ -//! Paint Bucket, Ink Bottle and Eyedropper. +//! Paint Bucket, Ink Bottle and Eyedropper; the fill swatch's gradients and bitmaps, Lock Fill +//! and the Gradient Transform tool (ADR 0074). //! //! AniCraft shapes are independent objects (like object drawing), so a fill for an area //! enclosed by several shapes has to be found, not looked up: @@ -18,7 +19,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, DisplayItem, Element, ElementId, ElementKind, Paint, Shape, Stroke}; +use anicraft_doc::{BitmapId, ColorEffect, DisplayItem, Element, ElementId, ElementKind, GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Shape, Spread, Stroke}; use anicraft_geom::trace::contours; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2, fit_curve}; use anicraft_render::raster::{Coverage, IRect}; @@ -42,6 +43,25 @@ pub fn specs() -> Vec { 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, |s, p| s.each_layer(false, |s| apply_style(s, p))), + c( + "paint.set_fill", + "Fill", + "", + None, + "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", + true, + set_fill, + ), + c( + "paint.transform_fill", + "Gradient Transform", + "", + None, + "{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}", + true, + |s, p| s.each_layer(false, |s| transform_fill(s, p)), + ), + c("paint.lock_fill", "Lock Fill", "", None, "{on?: bool (default: toggle)} Lock Fill: a gradient or bitmap from the fill swatch is poured where it lies on the stage, running on across shapes; off, each shape gets it fitted to its bounds → {on}", false, lock_fill), ] } @@ -73,13 +93,15 @@ fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances keep their own colours; break it apart (Ctrl+B) or edit the symbol to paint it".into())), ElementKind::Text(_) => Err(EngineError::State("text has its own colour (Properties); break it apart (Ctrl+B) to paint it as a shape".into())), ElementKind::Camera => Err(EngineError::State("the camera has no paint (its tint is in Properties)".into())), + ElementKind::Group { .. } => Err(EngineError::State("a group keeps its members' colours; double-click it to paint inside, or ungroup it (Ctrl+Shift+G)".into())), } } fn bucket(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); - // The fill swatch (a picked gradient or bitmap stays where it is on the stage). - let paint = opt_color(p, "color")?.map_or_else(|| s.style.fill_paint(), Paint::Solid); + // The fill swatch: a gradient or bitmap stays where it is on the stage with Lock Fill, else + // it is fitted to the shape it fills (ADR 0074). + let given = opt_color(p, "color")?.map(Paint::Solid); let gap = opt_f32(p, "gap")?.unwrap_or(0.0); if !(0.0..=1000.0).contains(&gap) { return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into())); @@ -89,8 +111,12 @@ fn bucket(s: &mut Session, p: &Value) -> Result { // 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); + let style = s.style.clone(); let sh = element_shape_mut(s, id)?; - sh.fill = Some(paint.transformed(&to_local)); + sh.fill = Some(match &given { + Some(c) => c.clone(), + None => style.fill_paint_for(&to_local, &sh.path.bounds()), + }); if sh.merge { crate::cmds_raw::remerge_in_place(s, &[id])?; return Ok(json!({"recolored": id.0, "merged": true})); @@ -113,7 +139,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result { 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: !object }), + kind: ElementKind::Shape(Shape { fill: Some(given.unwrap_or_else(|| s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()))), path: Arc::new(local), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), }; if !object { // Raw: behind the drawing, so it takes only what is empty and joins the fills of its @@ -375,6 +401,10 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { } st.fill = color; st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone()); + // As in Animate, a picked gradient or bitmap is locked where it was on the stage. + if st.fill_paint.is_some() { + st.lock_fill = true; + } st.use_fill = true; Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()})) } @@ -415,7 +445,6 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("apply the fill, the stroke or both".into())); } let style = s.style.clone(); - let paint = style.fill_paint(); let line = style.new_stroke(style.stroke, style.stroke_width); let mut changed = 0; for e in s.selected_elements_mut()? { @@ -426,7 +455,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { && sh.fill.is_some() && let Some(m) = to_local { - sh.fill = Some(paint.transformed(&m)); + sh.fill = Some(style.fill_paint_for(&m, &sh.path.bounds())); hit = true; } // Raw fills stay fill-only: the lines round them are shapes of their own (ADR 0031). @@ -441,3 +470,328 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { } Ok(json!({"changed": changed})) } + +// ----- the fill swatch, Lock Fill and the Gradient Transform tool (ADR 0074) --------------- + +/// Animate's default gradient: white to black. +fn default_stops() -> Vec { + vec![GradientStop { offset: 0.0, color: Rgba::WHITE }, GradientStop { offset: 1.0, color: Rgba::BLACK }] +} + +/// The `stops` param: 2 to 15 stops, each `{offset, color}`, put in order of offset. +pub(crate) fn opt_stops(p: &Value) -> Result>> { + let bad = || EngineError::Param(format!("param 'stops' must be a list of 2 to {MAX_GRADIENT_STOPS} stops like {{\"offset\": 0.5, \"color\": \"#ff8800\"}}")); + let list = match p.get("stops") { + None | Some(Value::Null) => return Ok(None), + Some(Value::Array(a)) if (2..=MAX_GRADIENT_STOPS).contains(&a.len()) => a, + Some(_) => return Err(bad()), + }; + let mut stops = Vec::with_capacity(list.len()); + for v in list { + let offset = opt_f32(v, "offset").map_err(|_| bad())?.ok_or_else(bad)?; + if !(0.0..=1.0).contains(&offset) { + return Err(EngineError::Param("a stop's 'offset' must be between 0 and 1".into())); + } + let color = opt_color(v, "color").map_err(|_| bad())?.ok_or_else(bad)?; + stops.push(GradientStop { offset, color }); + } + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + Ok(Some(stops)) +} + +/// The kinds of fill `paint.set_fill` makes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FillKind { + Solid, + Linear, + Radial, + Bitmap, +} + +fn fill_kind(p: &Paint) -> FillKind { + match p { + Paint::Solid(_) => FillKind::Solid, + Paint::Linear { .. } => FillKind::Linear, + Paint::Radial { .. } => FillKind::Radial, + Paint::Bitmap { .. } => FillKind::Bitmap, + } +} + +/// What `paint.set_fill` asks for: a kind of fill and the parts given. +struct FillSpec { + kind: FillKind, + color: Option, + stops: Option>, + spread: Option, + linear_rgb: Option, + focal: Option, + bitmap: Option, +} + +impl FillSpec { + /// `base` with these changes. A fill of the same kind keeps its geometry; another kind + /// comes out on the unit box (to be placed); a gradient keeps the colours and options of + /// the gradient it replaces, else starts white to black. `None`: a bitmap fill with no + /// bitmap given or held. + fn apply(&self, base: &Paint) -> Option { + let mut p = match self.kind { + FillKind::Solid => return Some(Paint::Solid(self.color.unwrap_or_else(|| base.primary_color()))), + k if k == fill_kind(base) => base.clone(), + FillKind::Linear | FillKind::Radial => { + let stops = base.stops().map_or_else(default_stops, <[GradientStop]>::to_vec); + let mut q = if self.kind == FillKind::Linear { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) }; + if let (Paint::Linear { spread: a, linear_rgb: b, .. } | Paint::Radial { spread: a, linear_rgb: b, .. }, Paint::Linear { spread, linear_rgb, .. } | Paint::Radial { spread, linear_rgb, .. }) = (&mut q, base) { + *a = *spread; + *b = *linear_rgb; + } + q + } + FillKind::Bitmap => Paint::Bitmap { bitmap: self.bitmap?, repeat: true, matrix: Affine::IDENTITY }, + }; + match &mut p { + Paint::Linear { stops, spread, linear_rgb, .. } => self.set_common(stops, spread, linear_rgb), + Paint::Radial { stops, spread, linear_rgb, focal, .. } => { + self.set_common(stops, spread, linear_rgb); + if let Some(f) = self.focal { + *focal = f; + } + } + Paint::Bitmap { bitmap, .. } => { + if let Some(b) = self.bitmap { + *bitmap = b; + } + } + Paint::Solid(_) => {} + } + Some(p) + } + + fn set_common(&self, stops: &mut Vec, spread: &mut Spread, linear_rgb: &mut bool) { + if let Some(st) = &self.stops { + stops.clone_from(st); + } + if let Some(sp) = self.spread { + *spread = sp; + } + if let Some(l) = self.linear_rgb { + *linear_rgb = l; + } + } +} + +/// `#rrggbb`, or `#rrggbbaa` when not opaque. +fn hex_alpha(c: Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +/// A fill as `paint.set_fill` reports it (in its own params' terms). +pub fn fill_json(p: &Paint) -> Value { + let stops = |st: &[GradientStop]| -> Vec { st.iter().map(|s| json!({"offset": s.offset, "color": hex_alpha(s.color)})).collect() }; + match p { + Paint::Solid(c) => json!({"type": "solid", "color": hex_alpha(*c)}), + Paint::Linear { stops: st, spread, linear_rgb, .. } => json!({"type": "linear", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb}), + Paint::Radial { stops: st, spread, linear_rgb, focal, .. } => json!({"type": "radial", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}), + Paint::Bitmap { bitmap, repeat, .. } => json!({"type": "bitmap", "bitmap": bitmap.0, "repeat": repeat}), + } +} + +pub(crate) fn opt_focal(p: &Value) -> Result> { + let f = opt_f32(p, "focal")?; + if f.is_some_and(|f| !(-MAX_FOCAL..=MAX_FOCAL).contains(&f)) { + return Err(EngineError::Param(format!("param 'focal' must be between -{MAX_FOCAL} and {MAX_FOCAL}"))); + } + Ok(f) +} + +/// `paint.set_fill`: the Colour panel's fill (type, stops, overflow, linear RGB, bitmap). +pub(crate) fn set_fill(s: &mut Session, p: &Value) -> Result { + let swatch = s.style.fill_paint(); + let kind = match opt_str(p, "type")? { + None => fill_kind(&swatch), + Some("solid") => FillKind::Solid, + Some("linear") => FillKind::Linear, + Some("radial") => FillKind::Radial, + Some("bitmap") => FillKind::Bitmap, + Some(other) => return Err(EngineError::Param(format!("unknown fill type '{other}' (solid, linear, radial or bitmap)"))), + }; + let spread = match opt_str(p, "spread")? { + None => None, + Some(k) => Some(Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?), + }; + let bitmap = match opt_u64(p, "bitmap")? { + None => None, + Some(id) => Some(s.doc.bitmap(BitmapId(id)).ok_or_else(|| EngineError::Param(format!("there is no bitmap {id} in the Library")))?.id), + }; + let spec = FillSpec { kind, color: opt_color(p, "color")?, stops: opt_stops(p)?, spread, linear_rgb: opt_bool(p, "linear_rgb")?, focal: opt_focal(p)?, bitmap }; + let new = spec.apply(&swatch).ok_or_else(|| EngineError::Param("a bitmap fill needs 'bitmap' (a Library bitmap's id)".into()))?; + // The swatch keeps where its fill lies; a new kind lies across the stage. + let stage = Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32); + let placed = if fill_kind(&swatch) == kind { new } else { new.fitted(&stage) }; + match &placed { + Paint::Solid(c) => s.style.set_fill_color(*c), + other => { + s.style.fill = other.primary_color(); + s.style.fill_paint = Some(other.clone()); + } + } + s.style.use_fill = true; + let changed = if opt_bool(p, "selection")?.unwrap_or(true) && !s.selection.is_empty() { + // Counts from several layers are added up. + s.each_layer(false, |s| set_selected_fills(s, &spec))?.get("changed").and_then(Value::as_u64).unwrap_or(0) + } else { + 0 + }; + Ok(json!({"fill": fill_json(&placed), "changed": changed})) +} + +/// The selected shapes with a fill on the active layer get `spec`: the same kind of fill keeps +/// where it lies, another kind is fitted to the shape. +fn set_selected_fills(s: &mut Session, spec: &FillSpec) -> Result { + let sel: std::collections::HashSet = s.selection.on(s.layer).into_iter().collect(); + if sel.is_empty() { + return Ok(json!({"changed": 0})); + } + let mut changed = 0u64; + let mut merged = Vec::new(); + for e in s.editable_keyframe()?.elements_mut_where(|id| sel.contains(&id)) { + let id = e.id; + let ElementKind::Shape(sh) = &mut e.kind else { continue }; + let Some(old) = &sh.fill else { continue }; + let Some(mut new) = spec.apply(old) else { continue }; + if fill_kind(old) != spec.kind { + new = new.fitted(&sh.path.bounds()); + } + if sh.fill.as_ref() != Some(&new) { + sh.fill = Some(new); + changed += 1; + if sh.merge { + merged.push(id); + } + } + } + // A raw fill joins the fills of its new paint it touches (as the Paint Bucket's recolour). + if !merged.is_empty() { + crate::cmds_raw::remerge_in_place(s, &merged)?; + } + Ok(json!({"changed": changed})) +} + +/// The size of the image a bitmap fill shows (`None`: not a bitmap, or missing). +pub fn image_size(doc: &anicraft_doc::Document, p: &Paint) -> Option<(f32, f32)> { + match p { + Paint::Bitmap { bitmap, .. } => doc.bitmap(*bitmap).map(|b| (b.width as f32, b.height as f32)), + _ => None, + } +} + +/// Where element `e`'s gradient or bitmap fill lies: its frame (see [`Paint::frame`]) in the +/// space being edited. `None` for anything else. +pub fn fill_frame(doc: &anicraft_doc::Document, e: &Element) -> Option { + let ElementKind::Shape(sh) = &e.kind else { return None }; + let f = sh.fill.as_ref()?; + Some(e.transform.mul(&f.frame(image_size(doc, f))?)) +} + +fn opt_vec2(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers)")); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() == 2 => { + let v = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= f64::from(crate::cmds_draw::MAX_EXTENT)).map(|x| x as f32); + match (v(0), v(1)) { + (Some(x), Some(y)) => Ok(Some(Vec2::new(x, y))), + _ => Err(bad()), + } + } + Some(_) => Err(bad()), + } +} + +/// The frame `paint.transform_fill`'s params ask for, from the current one `cur`. +fn new_frame(cur: &Affine, p: &Value) -> Result { + if let Some(v) = p.get("frame").filter(|v| !v.is_null()) { + let a = v.as_array().filter(|a| a.len() == 6).ok_or_else(|| EngineError::Param("param 'frame' must be [a, b, c, d, e, f]".into()))?; + let mut m = [0.0f32; 6]; + for (slot, x) in m.iter_mut().zip(a) { + *slot = x.as_f64().filter(|x| x.is_finite() && x.abs() <= 1e7).ok_or_else(|| EngineError::Param("param 'frame' must hold six finite numbers".into()))? as f32; + } + return Ok(Affine { m }); + } + let scale = |k: &str| -> Result { + match opt_f32(p, k)? { + None => Ok(1.0), + Some(v) if (1e-4..=1e4).contains(&v.abs()) => Ok(v), + Some(_) => Err(EngineError::Param(format!("param '{k}' must be a scale between 0.0001 and 10000 (negative flips)"))), + } + }; + let both = scale("scale")?; + let (sx, sy) = (scale("scale_x")? * both, scale("scale_y")? * both); + let skew = |k: &str| -> Result { + match opt_f32(p, k)? { + None => Ok(0.0), + Some(d) if d.abs() <= 85.0 => Ok(d.to_radians().tan()), + Some(_) => Err(EngineError::Param(format!("param '{k}' must be between -85 and 85 degrees"))), + } + }; + let own = Affine::scale(sx, sy).mul(&Affine { m: [1.0, skew("skew_y")?, skew("skew_x")?, 1.0, 0.0, 0.0] }); + let mut f = cur.mul(&own); + if let Some(deg) = opt_f32(p, "rotate")? { + let c = f.apply(Vec2::ZERO); + f = Affine::translate(c.x, c.y).mul(&Affine::rotate(deg.to_radians())).mul(&Affine::translate(-c.x, -c.y)).mul(&f); + } + if let Some(d) = opt_vec2(p, "move")? { + f = Affine::translate(d.x, d.y).mul(&f); + } + if let Some(at) = opt_vec2(p, "center")? { + let c = f.apply(Vec2::ZERO); + f = Affine::translate(at.x - c.x, at.y - c.y).mul(&f); + } + Ok(f) +} + +/// `paint.transform_fill`: the Gradient Transform tool's edit. +fn transform_fill(s: &mut Session, p: &Value) -> Result { + let focal = opt_focal(p)?; + let only = opt_u64(p, "element")?.map(ElementId); + let targets: std::collections::HashSet = match only { + Some(id) => [id].into(), + None => s.selection.on(s.layer).into_iter().collect(), + }; + if targets.is_empty() { + return Err(EngineError::State("select a shape with a gradient or bitmap fill".into())); + } + let doc = s.doc.clone(); + let mut frames = Vec::new(); + for e in s.editable_keyframe()?.elements_mut_where(|id| targets.contains(&id)) { + let (Some(cur), Some(to_local)) = (fill_frame(&doc, e), e.transform.inverse()) else { continue }; + let f = new_frame(&cur, p)?; + if !f.is_finite() || f.determinant().abs() < 1e-6 { + return Err(EngineError::Param("that would flatten the fill to nothing".into())); + } + let ElementKind::Shape(sh) = &mut e.kind else { continue }; + let Some(fill) = &sh.fill else { continue }; + let mut new = fill.with_frame(&to_local.mul(&f), image_size(&doc, fill)); + if let (Paint::Radial { focal: slot, .. }, Some(v)) = (&mut new, focal) { + *slot = v; + } + frames.push(json!(f.m)); + // Only where the fill lies changes, so a raw fill stays the shape it is (no re-merge: + // its id holds through a drag, and a moved gradient matches no neighbour's anyway). + sh.fill = Some(new); + } + if frames.is_empty() { + return Err(EngineError::State(match only { + Some(_) => "that shape has no gradient or bitmap fill on the active layer at this frame".into(), + None => "none of the selected shapes has a gradient or bitmap fill".into(), + })); + } + Ok(json!({"changed": frames.len(), "frames": frames})) +} + +/// `paint.lock_fill`. +fn lock_fill(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "on")?.unwrap_or(!s.style.lock_fill); + s.style.lock_fill = on; + Ok(json!({"on": on})) +} diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index 62e4ba18..a5bcdf34 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -130,6 +130,7 @@ fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())), ElementKind::Text(_) => Err(EngineError::State("text has no points to edit; break it apart (Ctrl+B) to edit its outlines".into())), ElementKind::Camera => Err(EngineError::State("the camera has no points to edit".into())), + ElementKind::Group { .. } => Err(EngineError::State("a group has no points of its own (double-click it to edit what is inside)".into())), } } diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 616bd168..805ecdab 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,16 +31,31 @@ 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", "bone", "script", "raw", "frames"]; + 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", "warp", "script", "raw", "frames", "find", "explorer"]; 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" | "frames.cut" | "frames.copy" | "frames.paste" => { Err("plug-ins don't use your clipboard") } _ => match id.split('.').next().unwrap_or("") { - "file" => Err("plug-ins can't open, save, import or export files"), + "file" => Err("plug-ins can't open, save, import, export or publish files"), + // Reading the settings is harmless; changing them changes what Publish writes where. + "publish" if id == "publish.settings_get" => Ok(()), + "publish" => Err("plug-ins can't change what Publish writes"), + "prefs" => Err("plug-ins can't read or change your preferences"), + // Listing the brushes is harmless (and painting with one is `draw.brush`); the + // user's own brushes are their preferences, and a brush set is a file. + "brush" if id == "brush.preset_list" => Ok(()), + "brush" => Err("plug-ins can't change your brushes or read and write brush sets"), + // The document's swatches are document data; swatch files are files. + "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), + "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), "control" => Err("plug-ins can't play the movie"), + // A scene's guides are the document's (ADR 0076); whether rulers, grid and guides + // show and snap is how you work. + "view" if matches!(id, "view.aids" | "view.guide_add" | "view.guide_move" | "view.guide_delete" | "view.guides_clear") => Ok(()), + "view" => Err("plug-ins can't change how your stage shows and snaps"), ns if DOCUMENT.contains(&ns) => Ok(()), _ => Err("plug-ins can't call this command"), }, @@ -78,7 +93,7 @@ fn document_view(s: &Session) -> Value { .timeline() .layers .iter() - .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)})) + .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "outline": l.outline, "onion": l.onion, "height": u32::from(l.height()) * 100, "parent": l.parent.map(|p| p.0)})) .collect(); json!({ "abi": anicraft_plugins::ABI_VERSION, @@ -126,7 +141,8 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result "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, + "alpha": e.color.alpha(), + "color_effect": crate::color_effect_json(&e.color), }); match &e.kind { ElementKind::Shape(sh) => { @@ -146,6 +162,10 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result v["text"] = json!(t.text); } ElementKind::Camera => v["kind"] = json!("camera"), + ElementKind::Group { .. } => { + v["kind"] = json!("group"); + v["members"] = json!(e.kind.group_members().len()); + } } out.push(v); } diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index 699c027c..794a0722 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -364,7 +364,7 @@ fn shared_points(s: &mut Session, at: Vec2) -> Result> { fn move_point(s: &mut Session, p: &Value) -> Result { 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 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)? { @@ -398,7 +398,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result { _ => 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 snapped = if s.snaps(radius) { snap_point(s, &els, to, radius, &points) } else { None }; let target = snapped.map_or(to, |(q, _)| q); let d = target - cur; let kf = s.editable_keyframe()?; @@ -440,23 +440,9 @@ fn move_point(s: &mut Session, p: &Value) -> Result { // ----- 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", - } - } -} +/// What a dragged point snapped to (the snap engine's, ADR 0076). +pub use crate::snap::SnapTo; +use crate::snap::{ObjectTargets, resolve}; /// Anchors and segments to snap to, in stage space. #[derive(Default)] @@ -492,30 +478,35 @@ fn targets(els: &[Arc], skip_el: impl Fn(ElementId) -> bool, skip_point 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)); +impl ObjectTargets for Targets { + /// The nearest anchor within `radius` of `p`. + fn nearest_point(&self, p: Vec2, radius: f32) -> Option<(Vec2, f32)> { + self.points.iter().map(|q| (*q, q.distance(p))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)) + } + /// The nearest point on a segment within `radius` of `p`. + fn nearest_line(&self, p: Vec2, radius: f32) -> Option<(Vec2, f32)> { + 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 + }; + self.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)) } - 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], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> { +/// Where a point being moved (`moving`: the anchors that go with it) snaps near `to`: the +/// artwork that stays put, the guides, the grid and pixels (ADR 0076). +fn snap_point(s: &Session, els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> { + if !s.style.snap_objects { + return resolve(s, to, radius, None); + } // The segments leaving the moving anchors move too. let mut segs: BTreeSet<(ElementId, usize)> = BTreeSet::new(); for e in els { @@ -526,19 +517,23 @@ fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, } } 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)) + resolve(s, to, radius, Some(&t)) } /// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR -/// 0045): the nearest anchor within `radius`, else the nearest point on a line or fill edge, of -/// what the stage shows near it. -pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo)> { +/// 0045; the Free Transform tool's handles): the nearest anchor within `radius`, else a guide, +/// a line or fill edge of what the stage shows near it, the grid or a pixel (ADR 0076). With +/// `moving`, the selection is what moves, so it isn't snapped to. +pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32, moving: bool) -> Option<(Vec2, SnapTo)> { if !(radius > 0.0 && p.is_finite()) { return None; } + if !s.style.snap_objects { + return resolve(s, p, radius, None); + } let dl = s.display_list(); let mut t = Targets::default(); - for item in dl.items.iter() { + for item in dl.items.iter().filter(|i| !(moving && s.selection.contains(i.layer, i.element))) { if t.points.len() + t.segs.len() > MAX_TARGETS { break; } @@ -551,14 +546,23 @@ pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, Sna t.points.extend(path.editable_anchors().into_iter().map(|(_, q)| item.transform.apply(q))); t.segs.extend((0..path.cmds.len().min(MAX_TARGETS)).filter_map(|k| rawgeom::segment_cubic(&path, k)).map(|c| rawgeom::transform(&c, &item.transform))); } - snap_to(&t, p, radius).map(|(q, k, _)| (q, k)) + resolve(s, p, radius, Some(&t)) } -/// 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`. +/// After the selection moved: the extra move that snaps one of its anchors or its bounding +/// box's corners or centre (the nearest to `from` when given, else whichever snaps best) onto +/// an anchor or line of the shapes that did not move, a guide, the grid or a pixel, within +/// `radius` (ADR 0041, 0076). pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Option<(Vec2, Vec2, SnapTo)> { let mut own: Vec = Vec::new(); + // The box's corners and centre: what symbols, text and bitmaps snap by. The selection has + // just moved, so the display list is looked at again. + s.dl_cache.replace(None); + let b = s.selection_bounds(); + if !b.is_empty() { + let c = Vec2::new((b.min.x + b.max.x) * 0.5, (b.min.y + b.max.y) * 0.5); + own.extend([b.min, Vec2::new(b.max.x, b.min.y), b.max, Vec2::new(b.min.x, b.max.y), c]); + } 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))); @@ -575,12 +579,15 @@ pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Op return None; } // What stays put on the layers the selection is on (ADR 0044). - let rest: Vec> = 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); + let t = s.style.snap_objects.then(|| { + let rest: Vec> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect(); + targets(&rest, |_| false, |_, _| false, |_, _| false) + }); + let t = t.as_ref().map(|t| t as &dyn ObjectTargets); 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)) + .filter_map(|c| resolve(s, c, radius, t).map(|(q, k)| (c, q, k, q.distance(c)))) + .min_by(|a, b| a.2.rank().cmp(&b.2.rank()).then(a.3.total_cmp(&b.3))) .map(|(c, q, k, _)| (q - c, q, k)) } diff --git a/crates/engine/src/cmds_rawpoints.rs b/crates/engine/src/cmds_rawpoints.rs index b4b9bbbe..fb04262d 100644 --- a/crates/engine/src/cmds_rawpoints.rs +++ b/crates/engine/src/cmds_rawpoints.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Snap Point", "", None, - "{x, y, snap} where a point drawn at (x, y) snaps while Snap to Objects is on: the nearest anchor within `snap` stage units, else the nearest point on a line or fill edge; returns {x, y, snapped: {x, y, to} | null}", + "{x, y, snap, moving?: bool} where a point drawn at (x, y) snaps within `snap` stage units, by the snap engine's priority (ADR 0076): an anchor (Snap to Objects), a guide (Snap to Guides), a line or fill edge, the grid (Snap to Grid), a whole pixel (Snap to Pixels); `moving`: the selection is what moves (a Free Transform handle), so it isn't a target; returns {x, y, snapped: {x, y, to: point|guide|line|grid|pixel} | null}", false, snap_cmd, ), @@ -238,8 +238,9 @@ fn convert_points(s: &mut Session, p: &Value) -> Result { fn snap_cmd(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); - let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); - Ok(match snap_drawn(s, at, radius) { + let radius = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0); + let moving = opt_bool(p, "moving")?.unwrap_or(false); + Ok(match snap_drawn(s, at, radius, moving) { Some((q, kind)) => json!({"x": q.x, "y": q.y, "snapped": {"x": q.x, "y": q.y, "to": kind.key()}}), None => json!({"x": at.x, "y": at.y, "snapped": null}), }) diff --git a/crates/engine/src/cmds_recent.rs b/crates/engine/src/cmds_recent.rs new file mode 100644 index 00000000..c2de5508 --- /dev/null +++ b/crates/engine/src/cmds_recent.rs @@ -0,0 +1,365 @@ +//! Recent files (ADR 0059): the documents opened or saved last, most recent first, with pinned +//! favourites kept above them. The list belongs to the session (it survives New and Open) and +//! is plain data: the desktop app keeps it in its preferences and puts it back at start, so the +//! engine never reads or writes the settings folder. `file.open` and `file.save` add to it; +//! these commands open, pin, remove and clear entries for menus, the CLI and MCP alike. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most recent (unpinned) files kept, as Animate's Open Recent shows. +pub const MAX_RECENT: usize = 10; +/// Most pinned favourites. +pub const MAX_PINNED: usize = 10; +/// Longest path kept (anything longer is not a path a user picked). +const MAX_PATH_BYTES: usize = 4096; + +/// One file in the list. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RecentFile { + pub path: PathBuf, + /// A favourite: it stays at the top, and adding or clearing recent files leaves it alone. + pub pinned: bool, +} + +/// Pinned favourites first (in the order they were pinned), then the recent files, most recent +/// first. At most [`MAX_PINNED`] + [`MAX_RECENT`] entries, never the same file twice. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RecentFiles { + entries: Vec, +} + +/// Whether two paths name the same file as the user sees it: Windows and macOS file names +/// ignore case (by default), and Windows takes either slash. +pub fn same_file(a: &Path, b: &Path) -> bool { + if cfg!(any(windows, target_os = "macos")) { + let norm = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase(); + norm(a) == norm(b) + } else { + a == b + } +} + +/// Whether a recent file is still there to open (a file, or an XFL folder). +pub fn exists(path: &Path) -> bool { + crate::vfs::is_file(path) || crate::vfs::is_dir(path) +} + +/// A short, stable key for a path (64-bit FNV-1a of its normalised text, as hex): the name its +/// thumbnail is kept under. +pub fn thumb_key(path: &Path) -> String { + let text = if cfg!(any(windows, target_os = "macos")) { path.to_string_lossy().replace('\\', "/").to_lowercase() } else { path.to_string_lossy().into_owned() }; + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in text.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{h:016x}") +} + +/// Largest edge of a recent file's thumbnail, in pixels. +pub const THUMB_W: u32 = 240; +pub const THUMB_H: u32 = 135; + +/// The document's first frame as a small PNG that fits [`THUMB_W`] × [`THUMB_H`] (the start +/// screen's picture of a recent file), rendered by the CPU oracle. +pub fn thumbnail_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (THUMB_W as f32 / w).min(THUMB_H as f32 / h).min(1.0); + crate::cmds_file::render_png(doc, 0, scale) +} + +impl RecentFiles { + pub fn entries(&self) -> &[RecentFile] { + &self.entries + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + fn position(&self, path: &Path) -> Option { + self.entries.iter().position(|e| same_file(&e.path, path)) + } + + fn pinned_count(&self) -> usize { + self.entries.iter().take_while(|e| e.pinned).count() + } + + /// A file was opened or saved: it becomes the most recent. A pinned file keeps its place; + /// the oldest recent file beyond [`MAX_RECENT`] drops off. Returns whether the list changed. + pub fn add(&mut self, path: &Path) -> bool { + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return false; + } + let before = self.entries.clone(); + if let Some(i) = self.position(path) { + if self.entries.get(i).is_some_and(|e| e.pinned) { + return false; + } + self.entries.remove(i); + } + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned: false }); + self.entries.truncate(at + MAX_RECENT); + before != self.entries + } + + /// Takes a file off the list (pinned or not). Returns whether it was there. + pub fn remove(&mut self, path: &Path) -> bool { + match self.position(path) { + Some(i) => { + self.entries.remove(i); + true + } + None => false, + } + } + + /// Pins a file (it goes below the other pinned files) or unpins it (it becomes the most + /// recent file). A file not on the list is added pinned. + pub fn pin(&mut self, path: &Path, pinned: bool) -> std::result::Result<(), String> { + let current = self.position(path).and_then(|i| self.entries.get(i)).map(|e| e.pinned); + if current == Some(pinned) { + return Ok(()); + } + if pinned && self.pinned_count() >= MAX_PINNED { + return Err(format!("at most {MAX_PINNED} files can be pinned; unpin one first")); + } + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return Err("that is not a file path".into()); + } + self.remove(path); + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned }); + let pins = self.pinned_count(); + self.entries.truncate(pins + MAX_RECENT); + Ok(()) + } + + /// Clears the recent files; pinned favourites stay unless `pinned` too. Returns how many + /// were taken off. + pub fn clear(&mut self, pinned: bool) -> usize { + let before = self.entries.len(); + self.entries.retain(|e| e.pinned && !pinned); + before - self.entries.len() + } + + /// The list as read from a preferences file that anyone may have edited: empty and overlong + /// paths and repeats dropped, pinned files first, each part within its limit. + pub fn sanitized(self) -> RecentFiles { + let mut out = RecentFiles::default(); + let (pins, recents): (Vec, Vec) = self.entries.into_iter().partition(|e| e.pinned); + for e in pins.into_iter().chain(recents) { + let bad = e.path.as_os_str().is_empty() || e.path.as_os_str().len() > MAX_PATH_BYTES; + if bad || out.position(&e.path).is_some() { + continue; + } + let pins = out.pinned_count(); + if (e.pinned && pins >= MAX_PINNED) || (!e.pinned && out.entries.len() - pins >= MAX_RECENT) { + continue; + } + out.entries.push(e); + } + out + } +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.open_recent", + label: "Open Recent", + // The File menu shows the files themselves (a submenu the shell draws). + menu: "", + shortcut: None, + params: "{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing", + mutates: false, + run: open_recent, + }, + CommandSpec { + id: "file.recent_list", + label: "Recent Files", + menu: "", + shortcut: None, + params: "{} → {files: [{index, path, name, pinned, missing, thumb}]}: pinned favourites first, then the last 10 files opened or saved, most recent first (`thumb` names the start screen's picture)", + mutates: false, + run: list, + }, + CommandSpec { + id: "prefs.recent_pin", + label: "Pin to Recent Files", + menu: "", + shortcut: None, + params: "{index? | path?, pinned? (default: toggle)}: a pinned file stays at the top of Open Recent", + mutates: false, + run: pin, + }, + CommandSpec { id: "prefs.recent_remove", label: "Remove from Recent Files", menu: "", shortcut: None, params: "{index? | path?}", mutates: false, run: remove }, + CommandSpec { + id: "prefs.recent_clear", + label: "Clear Recent Files", + menu: "", + shortcut: None, + params: "{pinned? (default false: pinned favourites stay)} → {removed}", + mutates: false, + run: clear, + }, + ] +} + +/// The entry `index` or `path` names. +fn which(s: &Session, p: &Value) -> Result { + match (opt_u64(p, "index")?, opt_str(p, "path")?) { + (Some(i), None) => usize::try_from(i).ok().and_then(|i| s.recent.entries().get(i)).map(|e| e.path.clone()).ok_or_else(|| EngineError::Param(format!("no recent file {i}; file.recent_list has {}", s.recent.len()))), + (None, Some(path)) if !path.trim().is_empty() => Ok(PathBuf::from(path)), + (None, Some(_)) => Err(EngineError::Param("param 'path' must name a file".into())), + _ => Err(EngineError::Param("name the file with 'index' or 'path' (one of them)".into())), + } +} + +fn open_recent(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !exists(&path) { + return Err(EngineError::State(format!("{} is no longer there (moved, renamed or deleted); remove it from Open Recent", path.display()))); + } + crate::cmds_file::open(s, &json!({"path": path.display().to_string()})) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let files: Vec = s + .recent + .entries() + .iter() + .enumerate() + .map(|(i, e)| { + let name = e.path.file_name().map_or_else(|| e.path.display().to_string(), |n| n.to_string_lossy().into_owned()); + json!({"index": i, "path": e.path.display().to_string(), "name": name, "pinned": e.pinned, "missing": !exists(&e.path), "thumb": thumb_key(&e.path)}) + }) + .collect(); + Ok(json!({"files": files})) +} + +fn pin(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + let now = s.recent.entries().iter().find(|e| same_file(&e.path, &path)).is_some_and(|e| e.pinned); + let pinned = opt_bool(p, "pinned")?.unwrap_or(!now); + s.recent.pin(&path, pinned).map_err(EngineError::State)?; + Ok(json!({"path": path.display().to_string(), "pinned": pinned})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !s.recent.remove(&path) { + return Err(EngineError::State(format!("{} is not in the recent files", path.display()))); + } + Ok(json!({"removed": path.display().to_string()})) +} + +fn clear(s: &mut Session, p: &Value) -> Result { + let pinned = opt_bool(p, "pinned")?.unwrap_or(false); + Ok(json!({"removed": s.recent.clear(pinned)})) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn paths(r: &RecentFiles) -> Vec { + r.entries().iter().map(|e| format!("{}{}", if e.pinned { "*" } else { "" }, e.path.display())).collect() + } + + #[test] + fn most_recent_first_ten_at_most_never_twice() { + let mut r = RecentFiles::default(); + for i in 0..14 { + assert!(r.add(Path::new(&format!("f{i}.anicraft")))); + } + assert_eq!(r.len(), MAX_RECENT); + assert_eq!(paths(&r).first().map(String::as_str), Some("f13.anicraft")); + assert_eq!(paths(&r).last().map(String::as_str), Some("f4.anicraft"), "the oldest drop off"); + // Opening one again moves it to the top, without a second entry. + assert!(r.add(Path::new("f8.anicraft"))); + assert_eq!(paths(&r)[..2], ["f8.anicraft", "f13.anicraft"]); + assert_eq!(r.len(), MAX_RECENT); + assert!(!r.add(Path::new("f8.anicraft")), "already the most recent"); + assert!(!r.add(Path::new("")), "no empty paths"); + } + + #[test] + fn pinned_files_stay_on_top_and_survive_clearing() { + let mut r = RecentFiles::default(); + for f in ["a", "b", "c"] { + r.add(Path::new(f)); + } + r.pin(Path::new("a"), true).unwrap(); + assert_eq!(paths(&r), ["*a", "c", "b"]); + // New files go below the pins; opening a pinned file leaves it where it is. + r.add(Path::new("d")); + assert!(!r.add(Path::new("a"))); + assert_eq!(paths(&r), ["*a", "d", "c", "b"]); + // Pins don't count towards the ten recent files. + for i in 0..12 { + r.add(Path::new(&format!("n{i}"))); + } + assert_eq!(r.len(), 1 + MAX_RECENT); + assert_eq!(r.clear(false), MAX_RECENT); + assert_eq!(paths(&r), ["*a"]); + // Unpinning makes it the most recent file. + r.add(Path::new("z")); + r.pin(Path::new("a"), false).unwrap(); + assert_eq!(paths(&r), ["a", "z"]); + assert!(r.remove(Path::new("z"))); + assert!(!r.remove(Path::new("z"))); + assert_eq!(r.clear(true), 1); + assert!(r.is_empty()); + for i in 0..MAX_PINNED { + r.pin(Path::new(&format!("p{i}")), true).unwrap(); + } + assert!(r.pin(Path::new("one too many"), true).is_err()); + } + + #[test] + fn a_hand_edited_list_is_cleaned_up() { + let raw = r#"[{"path": "b"}, {"path": "", "pinned": true}, {"path": "a", "pinned": true}, {"path": "b"}, {"nonsense": 1}]"#; + let r: RecentFiles = serde_json::from_str::(raw).unwrap().sanitized(); + assert_eq!(paths(&r), ["*a", "b"]); + let many: Vec = (0..40).map(|i| RecentFile { path: PathBuf::from(format!("{i}")), pinned: i % 2 == 0 }).collect(); + let r = RecentFiles { entries: many }.sanitized(); + assert_eq!(r.entries().iter().filter(|e| e.pinned).count(), MAX_PINNED); + assert_eq!(r.entries().iter().filter(|e| !e.pinned).count(), MAX_RECENT); + assert!(r.entries().iter().take(MAX_PINNED).all(|e| e.pinned), "pins first"); + assert!(RecentFiles { entries: vec![RecentFile { path: PathBuf::from("x".repeat(5000)), pinned: false }] }.sanitized().is_empty()); + } + + #[test] + fn thumbnail_keys_are_stable_and_distinct() { + assert_eq!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/b.anicraft"))); + assert_ne!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/c.anicraft"))); + assert_eq!(thumb_key(Path::new("x")).len(), 16); + } + + #[test] + fn thumbnails_fit_the_start_screen() { + let t = std::time::Instant::now(); + let png = thumbnail_png(&anicraft_doc::sample::demo()).unwrap(); + eprintln!("thumbnail of the sample: {:.2} ms, {} bytes", t.elapsed().as_secs_f64() * 1000.0, png.len()); + let img = image_size(&png); + assert!(img.0 <= THUMB_W && img.1 <= THUMB_H && img.0 > 0 && img.1 > 0, "{img:?}"); + } + + /// Width and height from a PNG's header. + fn image_size(png: &[u8]) -> (u32, u32) { + let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]); + (be(16), be(20)) + } +} diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index e5ff51fb..b619c6c8 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -31,7 +31,7 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result { } /// Opens scene `i` at its first frame, on its top layer. -fn open_scene(s: &mut Session, i: usize) { +pub(crate) fn open_scene(s: &mut Session, i: usize) { // A scene is edited from its own timeline: open symbols close first (ADR 0045). s.exit_all(); s.scene = i.min(s.doc.scenes.len().saturating_sub(1)); @@ -127,7 +127,7 @@ fn duplicate_scene(s: &mut Session, p: &Value) -> Result { let Some(src) = s.doc.scenes.get(i).cloned() else { return Err(EngineError::State("no such scene".into())) }; let timeline = reid(s, &src.timeline); let name = unused_name(s, &format!("{} copy", src.name)); - s.doc.scenes.insert(i + 1, Arc::new(Scene { name, timeline })); + s.doc.scenes.insert(i + 1, Arc::new(Scene { name, timeline, guides: src.guides.clone() })); open_scene(s, i + 1); Ok(scene_json(s)) } diff --git a/crates/engine/src/cmds_script.rs b/crates/engine/src/cmds_script.rs index 8ab992b3..0ddb7de1 100644 --- a/crates/engine/src/cmds_script.rs +++ b/crates/engine/src/cmds_script.rs @@ -13,8 +13,10 @@ use crate::cmds_actions::{Scope, keyframe_in}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript}; -use anicraft_doc::{Linkage, SymbolId}; +use anicraft_doc::player::{TimelineRef, link_problems}; +use anicraft_doc::{Document, Linkage, SymbolId, SymbolKind}; use serde_json::{Value, json}; use std::sync::Arc; @@ -24,7 +26,7 @@ pub fn specs() -> 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); 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, 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.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, the names it takes from other frames of its timeline (`uses`), and what it compiles to (`steps`, `program`); 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), ] } @@ -47,14 +49,33 @@ fn what(script: &Option) -> Value { } /// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is -/// the whole script). -fn status(c: &CompileResult) -> Value { +/// the whole script). `links`: why it doesn't run on its timeline although it compiles (a +/// name from another frame that isn't there, ADR 0052). +fn status(c: &CompileResult, links: &[Problem]) -> Value { match c { - Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) if links.is_empty() => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) => json!({"runs": false, "problems": links, "notes": c.notes}), Err(p) => json!({"runs": false, "problems": p, "notes": []}), } } +/// The timeline a keyframe's script belongs to, for linking (graphic and button timelines +/// don't run scripts: `None`). +fn timeline_of(doc: &Document, symbol: Option) -> Option { + match symbol { + None => Some(TimelineRef::Root), + Some(id) => doc.symbol(id).filter(|s| s.kind == SymbolKind::MovieClip).map(|_| TimelineRef::Symbol(id)), + } +} + +/// Why a compiled script doesn't link on its timeline. +fn links(doc: &Document, which: Option, c: &CompileResult) -> Vec { + match (which, c) { + (Some(w), Ok(c)) => link_problems(doc, w, c), + _ => Vec::new(), + } +} + fn check(_: &mut Session, p: &Value) -> Result { let text = str_req(p, "text")?; if text.len() > actions::MAX_SOURCE_BYTES { @@ -62,10 +83,11 @@ fn check(_: &mut Session, p: &Value) -> Result { } let script = SourceScript::new(language(p)?.unwrap_or_default(), text); let c = script.compiled(); - let mut v = status(c); + 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::>()); + v["steps"] = json!(c.steps); + v["uses"] = json!(c.free); + v["program"] = json!(c); } Ok(v) } @@ -103,10 +125,12 @@ fn set(s: &mut Session, p: &Value) -> Result { let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text); script.check().map_err(EngineError::Param)?; 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())) { + let script = Arc::new(script); + k.script = Some(FrameScript::Source(script.clone())); + let which = timeline_of(&s.doc, opt_u64(p, "symbol")?.map(SymbolId)); + if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled(), &links(&s.doc, which, script.compiled()))) { o.extend(st); } - k.script = Some(FrameScript::Source(Arc::new(script))); Ok(out) } @@ -122,13 +146,14 @@ fn clear(s: &mut Session, p: &Value) -> Result { fn list(s: &mut Session, p: &Value) -> Result { let with_text = opt_bool(p, "text")?.unwrap_or(true); let mut frames = Vec::new(); - let timelines = s.doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline)).chain(s.doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline))); - for (at, name, tl) in timelines { + let doc = &s.doc; + let timelines = doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline, Some(TimelineRef::Root))).chain(doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline, timeline_of(doc, Some(sym.id))))); + for (at, name, tl, which) in timelines { for l in &tl.layers { 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())) { + if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled(), &links(doc, which, src.compiled()))) { o.extend(st); } if with_text { diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index 47666910..abef14ef 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Import to Library…", "File/Import", None, - "{path (.wav, .ogg or .mp3 sound; .png or .jpg image), name?}", + "{path (.wav, .ogg or .mp3 sound; .png or .jpg image; .svg drawing: a graphic symbol named after the file holding its shapes), name?}", true, import_to_library as crate::RunFn, ), @@ -99,7 +99,7 @@ fn sound_json(s: &Sound) -> Value { } /// Import to Library: a sound (or an image) goes into the library without being placed. -fn import_to_library(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if is_sound(&path) { let id = add_sound(s, &path, opt_str(p, "name")?)?; @@ -115,7 +115,11 @@ fn import_to_library(s: &mut Session, p: &Value) -> Result { s.doc.bitmaps.push(Arc::new(bitmap)); return Ok(json!({"bitmap": id.0, "width": w, "height": h})); } - Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, and PNG and JPEG images".into())) + if ext.as_deref() == Some("svg") { + // A drawing becomes a graphic symbol holding its shapes (ADR 0065). + return crate::cmds_file::import_svg_symbol(s, &path, opt_str(p, "name")?); + } + Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, PNG and JPEG images, and SVG drawings (as a graphic symbol)".into())) } /// Import to Stage with a sound: into the library, and onto a new layer named after the file, diff --git a/crates/engine/src/cmds_swatch.rs b/crates/engine/src/cmds_swatch.rs new file mode 100644 index 00000000..01697060 --- /dev/null +++ b/crates/engine/src/cmds_swatch.rs @@ -0,0 +1,302 @@ +//! The Swatches panel's commands (ADR 0078): the document's saved colours and gradients. +//! +//! Swatches live in the document (`Document::swatches`), so every change here is an undo step +//! and is saved with the file, as Animate keeps them per document. Applying a swatch is +//! `paint.set_fill` (fill) or `element.set_stroke` (stroke) underneath, so the selection and +//! the tool colour change exactly as they do from the Colour panel. +//! +//! A swatch set moves between documents and computers as a small JSON file +//! (`swatch.export` / `swatch.import`); GIMP palettes (`.gpl`, an open plain-text format) +//! import too. Adobe's `.aco`, `.ase` and `.clr` formats are proprietary and not read. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::swatch::{MAX_PALETTE_BYTES, clean_name, default_set, parse_gpl}; +use anicraft_doc::{GradientStop, MAX_SWATCHES, Rgba, Spread, Swatch, SwatchPaint}; +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c("swatch.list", "Swatches", "{} the document's swatches, in the Swatches panel's order → {swatches: [{index, name, type, color | stops, ..}], count}", false, list as crate::RunFn), + c( + "swatch.add", + "Add Swatch", + "{from?: fill|stroke (default fill: the fill swatch's colour or gradient; stroke: the stroke colour), or the swatch itself: type?: solid|linear|radial, color? (\"#rrggbb\" | \"#rrggbbaa\", solid), stops?: [{offset: 0..1, color}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial); name?, at? (index; default: the end)} → {index, count}", + true, + add, + ), + c("swatch.remove", "Delete Swatch", "{index} → {count}", true, remove), + c("swatch.move", "Move Swatch", "{from, to} (indices: the swatch at `from` ends up at `to`) → {index}", true, move_swatch), + c("swatch.duplicate", "Duplicate Swatch", "{index} puts a copy right after it → {index, count}", true, duplicate), + c("swatch.rename", "Rename Swatch", "{index, name} (empty: no name, the hex shows on hover)", true, rename), + c( + "swatch.apply", + "Apply Swatch", + "{index, target?: fill|stroke (default fill), selection?: bool (default true)} sets the fill swatch (as paint.set_fill: a gradient is fitted to each shape) or the stroke colour, and unless `selection` is false the selected shapes' fills or strokes. A gradient swatch can't be a stroke (strokes are one colour) → {target, changed}", + true, + apply, + ), + c("swatch.clear", "Clear Swatches", "{} removes every swatch but black and white (Animate's Clear Colors; undoable)", true, clear), + c("swatch.reset", "Default Swatches", "{} replaces the swatches with a new document's set (undoable)", true, reset), + c("swatch.import", "Import Swatches", "{path: a swatch file (.json, from swatch.export) or a GIMP palette (.gpl), replace?: bool (default false: added at the end)} → {imported, count}", true, import), + c("swatch.export", "Export Swatches", "{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}", false, export), + ] +} + +/// `#rrggbb`, or `#rrggbbaa` when not opaque. +pub fn hex(c: Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +fn stops_json(stops: &[GradientStop]) -> Value { + json!(stops.iter().map(|s| json!({"offset": s.offset, "color": hex(s.color)})).collect::>()) +} + +/// A swatch as commands and swatch files write it. +pub fn swatch_json(s: &Swatch) -> Value { + let mut v = match &s.paint { + SwatchPaint::Solid { color } => json!({"type": "solid", "color": hex(*color)}), + SwatchPaint::Linear { stops, spread, linear_rgb } => json!({"type": "linear", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb}), + SwatchPaint::Radial { stops, spread, linear_rgb, focal } => json!({"type": "radial", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}), + }; + if !s.name.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("name".into(), json!(s.name)); + } + v +} + +/// A swatch from its JSON (see `swatch.add`). `None` when `v` names no paint (no type, colour +/// or stops), so the caller can fall back to the current one. +pub fn swatch_from_json(v: &Value) -> Result> { + let kind = opt_str(v, "type")?; + let color = opt_color(v, "color")?; + let stops = crate::cmds_paint::opt_stops(v)?; + let spread = match opt_str(v, "spread")? { + None => Spread::Pad, + Some(k) => Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?, + }; + let linear_rgb = opt_bool(v, "linear_rgb")?.unwrap_or(false); + let focal = crate::cmds_paint::opt_focal(v)?.unwrap_or(0.0); + let kind = match (kind, &color, &stops) { + (None, None, None) => return Ok(None), + (Some(k), ..) => k, + (None, _, Some(_)) => "linear", + (None, Some(_), None) => "solid", + }; + let need_stops = || stops.clone().ok_or_else(|| EngineError::Param(format!("a {kind} swatch needs 'stops' (2 to 15 like {{\"offset\": 0, \"color\": \"#ff0000\"}})"))); + let paint = match kind { + "solid" => SwatchPaint::Solid { color: color.ok_or_else(|| EngineError::Param("a solid swatch needs 'color' (like \"#ff8800\")".into()))? }, + "linear" => SwatchPaint::Linear { stops: need_stops()?, spread, linear_rgb }, + "radial" => SwatchPaint::Radial { stops: need_stops()?, spread, linear_rgb, focal }, + other => return Err(EngineError::Param(format!("unknown swatch type '{other}' (solid, linear or radial)"))), + }; + let name = opt_str(v, "name")?.unwrap_or(""); + Swatch::new(name, paint).sanitized().map(Some).ok_or_else(|| EngineError::Param("that swatch can't be kept (a gradient needs two stops)".into())) +} + +fn index_param(s: &Session, p: &Value, key: &str) -> Result { + let n = s.doc.swatches.len(); + let i = opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required (a swatch's index)")))?; + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| if n == 0 { EngineError::State("the document has no swatches".into()) } else { EngineError::Param(format!("param '{key}' must be a swatch index, 0 to {}", n - 1)) }) +} + +fn swatches_mut(s: &mut Session) -> &mut Vec { + Arc::make_mut(&mut s.doc.swatches) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let v: Vec = s + .doc + .swatches + .iter() + .enumerate() + .map(|(i, sw)| { + let mut j = swatch_json(sw); + if let Some(o) = j.as_object_mut() { + o.insert("index".into(), json!(i)); + } + j + }) + .collect(); + Ok(json!({"count": v.len(), "swatches": v})) +} + +/// The swatch `swatch.add` makes from the current colours: the fill swatch, or the stroke. +fn current(s: &Session, from: &str) -> Result { + match from { + "fill" => SwatchPaint::from_paint(&s.style.fill_paint()).map(|p| Swatch { name: String::new(), paint: p }).ok_or_else(|| EngineError::State("a bitmap fill can't be a swatch (swatches hold colours and gradients)".into())), + "stroke" => Ok(Swatch::solid(s.style.stroke)), + other => Err(EngineError::Param(format!("param 'from' must be fill or stroke, not '{other}'"))), + } +} + +fn add(s: &mut Session, p: &Value) -> Result { + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let mut sw = match (opt_str(p, "from")?, swatch_from_json(p)?) { + (Some(_), Some(_)) => return Err(EngineError::Param("give either 'from' or the swatch's own type, colour or stops, not both".into())), + (None, Some(sw)) => sw, + (from, None) => current(s, from.unwrap_or("fill"))?, + }; + if let Some(n) = opt_str(p, "name")? { + sw.name = clean_name(n); + } + let n = s.doc.swatches.len(); + let at = match opt_u64(p, "at")? { + None => n, + Some(i) => usize::try_from(i).ok().filter(|i| *i <= n).ok_or_else(|| EngineError::Param(format!("param 'at' must be 0 to {n}")))?, + }; + swatches_mut(s).insert(at, sw); + Ok(json!({"index": at, "count": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let v = swatches_mut(s); + v.remove(i); + Ok(json!({"count": v.len()})) +} + +fn move_swatch(s: &mut Session, p: &Value) -> Result { + let from = index_param(s, p, "from")?; + let to = index_param(s, p, "to")?; + if from != to { + let v = swatches_mut(s); + let sw = v.remove(from); + v.insert(to, sw); + } + Ok(json!({"index": to})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let v = swatches_mut(s); + let copy = v.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + v.insert(i + 1, copy); + Ok(json!({"index": i + 1, "count": v.len()})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let name = clean_name(str_req(p, "name")?); + if let Some(sw) = swatches_mut(s).get_mut(i) { + sw.name = name.clone(); + } + Ok(json!({"index": i, "name": name})) +} + +fn apply(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let sw = s.doc.swatches.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + let selection = opt_bool(p, "selection")?.unwrap_or(true); + match opt_str(p, "target")?.unwrap_or("fill") { + "fill" => { + let mut fill = swatch_json(&sw); + if let Some(o) = fill.as_object_mut() { + o.remove("name"); + o.insert("selection".into(), json!(selection)); + } + let r = crate::cmds_paint::set_fill(s, &fill)?; + Ok(json!({"target": "fill", "changed": r.get("changed").cloned().unwrap_or(json!(0))})) + } + "stroke" => { + let SwatchPaint::Solid { color } = sw.paint else { + return Err(EngineError::State("strokes are one colour: apply a gradient swatch to the fill instead".into())); + }; + s.style.stroke = color; + s.style.use_stroke = true; + let changed = if selection && !s.selection.is_empty() { + s.each_layer(false, |s| crate::cmds_draw::set_stroke(s, &json!({"color": hex(color)})))?; + s.selection.len() + } else { + 0 + }; + Ok(json!({"target": "stroke", "changed": changed})) + } + other => Err(EngineError::Param(format!("param 'target' must be fill or stroke, not '{other}'"))), + } +} + +fn clear(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + Ok(json!({"count": 2})) +} + +fn reset(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(default_set()); + Ok(json!({"count": s.doc.swatches.len()})) +} + +/// The JSON swatch file: `{"format": "anicraft-swatches", "version": 1, "swatches": [..]}`. +pub fn file_json(swatches: &[Swatch]) -> String { + let v = json!({"format": FORMAT, "version": 1, "swatches": swatches.iter().map(swatch_json).collect::>()}); + serde_json::to_string_pretty(&v).unwrap_or_default() +} + +const FORMAT: &str = "anicraft-swatches"; + +/// The swatches in a swatch file (JSON) or a GIMP palette, told apart by their content. +pub fn parse_file(text: &str) -> Result> { + if text.len() > MAX_PALETTE_BYTES { + return Err(EngineError::Param("the swatch file is too large".into())); + } + if text.trim_start_matches('\u{feff}').trim_start().starts_with("GIMP Palette") { + return parse_gpl(text).map(|(_, v)| v).map_err(EngineError::Param); + } + let v: Value = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("this isn't a swatch file or a GIMP palette ({e})")))?; + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(EngineError::Param(format!("this JSON isn't a swatch file (its \"format\" must be \"{FORMAT}\")"))); + } + let list = v.get("swatches").and_then(Value::as_array).ok_or_else(|| EngineError::Param("the swatch file has no \"swatches\" list".into()))?; + let mut out = Vec::new(); + for item in list.iter().take(MAX_SWATCHES) { + // A swatch this version can't read is skipped, so a newer file still opens. + if let Ok(Some(sw)) = swatch_from_json(item) { + out.push(sw); + } + } + if out.is_empty() { + return Err(EngineError::Param("the swatch file has no swatches in it".into())); + } + Ok(out) +} + +fn import(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if crate::vfs::len(&path)? > MAX_PALETTE_BYTES as u64 { + return Err(EngineError::Param(format!("{} is too large to be a swatch file", path.display()))); + } + let found = parse_file(&crate::vfs::read_to_string(&path)?)?; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let v = swatches_mut(s); + if replace { + v.clear(); + } + let room = MAX_SWATCHES.saturating_sub(v.len()); + if room == 0 { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let n = found.len().min(room); + v.extend(found.into_iter().take(n)); + Ok(json!({"imported": n, "count": v.len()})) +} + +fn export(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if s.doc.swatches.is_empty() { + return Err(EngineError::State("the document has no swatches to export".into())); + } + let text = file_json(&s.doc.swatches); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "swatches": s.doc.swatches.len(), "bytes": text.len()})) +} diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs new file mode 100644 index 00000000..881eb2ba --- /dev/null +++ b/crates/engine/src/cmds_template.rs @@ -0,0 +1,207 @@ +//! Templates (ADR 0065): new documents from the templates AniCraft ships with +//! (`anicraft_doc::templates`, built by code) and from the user's own, which File › Save as +//! Template keeps as plain `.anicraft` files with a picture beside them: +//! `//.anicraft` and `.png`. The shell passes the folder (its +//! settings folder's `Templates`); the engine never looks for it, as with recent files. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, format}; +use anicraft_doc::templates::{self, TEMPLATES}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Longest template or category name, in characters. +pub const MAX_NAME_CHARS: usize = 64; +/// Most categories and templates listed (a folder with more is not one we made). +const MAX_CATEGORIES: usize = 64; +const MAX_TEMPLATES: usize = 500; +/// The category a template is saved in when none is given. +pub const DEFAULT_CATEGORY: &str = "My Templates"; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.new_from_template", + label: "New from Template…", + menu: "File", + shortcut: None, + params: "{template? (a built-in template's id, from file.templates) | path? (a template file: any .anicraft opens as a new, untitled document)}", + mutates: false, + run: new_from_template, + }, + CommandSpec { + id: "file.templates", + label: "List Templates", + menu: "", + shortcut: None, + params: "{folder? (the user templates folder)} → {builtin: [{id, name, category, description, width, height, fps, frames}], user: [{name, category, path, thumbnail}]}", + mutates: false, + run: list, + }, + CommandSpec { + id: "file.save_as_template", + label: "Save as Template…", + menu: "File", + shortcut: None, + params: "{folder (the user templates folder), name, category? (default “My Templates”), confirm? (to replace a template of that name)} → {path, thumbnail}: the document as it is, kept as //.anicraft with a picture of its first frame; the open document is unchanged", + mutates: false, + run: save_as_template, + }, + CommandSpec { id: "file.delete_template", label: "Delete Template", menu: "", shortcut: None, params: "{folder, name, category?, confirm}: removes a user template and its picture (cannot be undone)", mutates: false, run: delete_template }, + ] +} + +/// A name usable as a file or folder name on every system, or why not. +fn clean_name(raw: &str, what: &str) -> Result { + let name = raw.trim(); + if name.is_empty() { + return Err(EngineError::Param(format!("give the {what} a name"))); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err(EngineError::Param(format!("a {what} name has at most {MAX_NAME_CHARS} characters"))); + } + if name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) { + return Err(EngineError::Param(format!("a {what} name can't use / \\ : * ? \" < > |"))); + } + if name.starts_with('.') || name.ends_with('.') { + return Err(EngineError::Param(format!("a {what} name can't start or end with a dot"))); + } + // Names Windows keeps for devices, with or without an extension. + let stem = name.split('.').next().unwrap_or(name).trim().to_ascii_uppercase(); + let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 && stem.ends_with(|c: char| c.is_ascii_digit())); + if reserved { + return Err(EngineError::Param(format!("“{name}” is a name the system keeps for itself: pick another {what} name"))); + } + Ok(name.to_string()) +} + +/// Where a user template of this category and name is kept. +pub fn template_path(folder: &Path, category: &str, name: &str) -> Result { + let category = clean_name(category, "category")?; + let name = clean_name(name, "template")?; + Ok(folder.join(category).join(format!("{name}.anicraft"))) +} + +/// The picture kept beside a template file. +pub fn thumbnail_path(template: &Path) -> PathBuf { + template.with_extension("png") +} + +/// A user template found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UserTemplate { + pub name: String, + pub category: String, + pub path: PathBuf, + /// Its picture, when there is one. + pub thumbnail: Option, +} + +/// The user's templates, by category then name (ignoring case). +pub fn user_templates(folder: &Path) -> Vec { + let mut out = Vec::new(); + for dir in crate::vfs::list(folder, MAX_CATEGORIES).into_iter().filter(|d| crate::vfs::is_dir(d)) { + let Some(category) = dir.file_name().map(|n| n.to_string_lossy().into_owned()) else { continue }; + for f in crate::vfs::list(&dir, MAX_TEMPLATES) { + if out.len() >= MAX_TEMPLATES { + break; + } + let is_template = f.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) && crate::vfs::is_file(&f); + let Some(name) = f.file_stem().map(|n| n.to_string_lossy().into_owned()).filter(|_| is_template) else { continue }; + let thumb = thumbnail_path(&f); + out.push(UserTemplate { name, category: category.clone(), thumbnail: crate::vfs::is_file(&thumb).then_some(thumb), path: f }); + } + } + out.sort_by_key(|t| (t.category.to_lowercase(), t.name.to_lowercase())); + out +} + +/// A template's picture: its first frame fitting the recent files' thumbnail size, guides +/// drawn, their lines widened to stay visible at that size. +pub fn picture_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (crate::cmds_recent::THUMB_W as f32 / w).min(crate::cmds_recent::THUMB_H as f32 / h).min(1.0); + crate::cmds_recent::thumbnail_png(&templates::with_guides_shown(doc, 1.5 / scale.max(1e-3))) +} + +fn new_from_template(s: &mut Session, p: &Value) -> Result { + let (doc, name) = match (opt_str(p, "template")?, opt_str(p, "path")?) { + (Some(id), None) => { + let t = templates::find(id).ok_or_else(|| EngineError::Param(format!("no template '{id}' (file.templates lists them)")))?; + ((t.build)(), t.name.to_string()) + } + (None, Some(path)) => { + let path = PathBuf::from(path); + if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) { + return Err(EngineError::Param("a template is an .anicraft document".into())); + } + let name = path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + (format::load(&path)?, name) + } + _ => return Err(EngineError::Param("name a built-in 'template' or a template file's 'path'".into())), + }; + // A new document: untitled, so Save asks for a name and never writes over the template. + s.replace_document(doc, None); + // Ready to draw: the top layer that takes artwork is active (not a locked guide). + if let Some(l) = s.timeline().layers.iter().find(|l| l.kind == anicraft_doc::LayerKind::Normal && !l.locked) { + s.layer = l.id; + } + let mut info = s.info(); + info["template"] = json!(name); + Ok(info) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let builtin: Vec = TEMPLATES + .iter() + .map(|t| { + let d = (t.build)(); + json!({"id": t.id, "name": t.name, "category": t.category, "description": t.description, "width": d.stage.width, "height": d.stage.height, "fps": d.stage.fps, "frames": d.frame_count()}) + }) + .collect(); + let user: Vec = match opt_str(p, "folder")? { + Some(f) => user_templates(Path::new(f)).into_iter().map(|t| json!({"name": t.name, "category": t.category, "path": t.path.display().to_string(), "thumbnail": t.thumbnail.map(|p| p.display().to_string())})).collect(), + None => Vec::new(), + }; + Ok(json!({"builtin": builtin, "user": user})) +} + +fn category(p: &Value) -> Result<&str> { + Ok(opt_str(p, "category")?.filter(|c| !c.trim().is_empty()).unwrap_or(DEFAULT_CATEGORY)) +} + +/// The template file the params name. +pub(crate) fn target(p: &Value) -> Result { + template_path(Path::new(str_req(p, "folder")?), category(p)?, str_req(p, "name")?) +} + +fn save_as_template(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if let Some(dir) = path.parent() { + crate::vfs::create_dir_all(dir)?; + } + format::save(&s.doc, &path)?; + // Its picture shows the guides too (they are much of what a template is). + let thumb = thumbnail_path(&path); + let picture = picture_png(&s.doc).and_then(|png| Ok(crate::vfs::write(&thumb, png)?)); + Ok(json!({"path": path.display().to_string(), "thumbnail": picture.is_ok().then(|| thumb.display().to_string())})) +} + +fn delete_template(_: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if !crate::vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no template “{}” in “{}”", str_req(p, "name")?.trim(), category(p)?.trim()))); + } + crate::vfs::remove_file(&path)?; + let thumb = thumbnail_path(&path); + if crate::vfs::is_file(&thumb) { + crate::vfs::remove_file(&thumb)?; + } + // An emptied category goes with its last template. + if let Some(dir) = path.parent() + && crate::vfs::list(dir, 1).is_empty() + { + let _ = std::fs::remove_dir(dir); + } + Ok(json!({"deleted": path.display().to_string()})) +} diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index e2b4dacc..9fa7feb9 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -1,10 +1,18 @@ //! Text commands (ADR 0012): create and edit text blocks, list fonts. Laying text out happens //! here, when it changes; the document keeps the outlines, so rendering never needs fonts. +//! +//! Dynamic and input text fields (ADR 0066): `text.field` sets a block's Text type and field +//! options. A field's box is fixed and its text is laid out inside the gutter, aligned in the box; +//! [`field_layout`] does that for the commands and for the player while a movie plays. +//! +//! Text on a path (ADR 0070): `text.attach_path` sets static text along a shape's outline (a +//! copy of it, in the text's own space), `text.path` moves it along, flips it or releases it. +//! The glyphs are set by arc length and stored as outlines, as all text is. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Rgba, TextAlign, TextBlock}; -use anicraft_geom::{Affine, Path}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath}; +use anicraft_geom::{Affine, Path, Vec2}; use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; use std::sync::Arc; @@ -32,9 +40,21 @@ impl Default for TextStyle { pub fn specs() -> Vec { 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.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, 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, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), + c( + "text.attach_path", + "Attach Text to Path", + "Modify/Text", + None, + "{path?: element id of a shape (default: the other selected element, a shape), x?, y? (pick the shape at this stage point instead), offset? (px along the path; default by the text's alignment: its start, middle or end), flip?: bool} sets the selected static text along a copy of the shape's outline (its first contour); the shape stays as it is (ADR 0070)", + true, + attach_path as crate::RunFn, + ), + c("text.path", "Text on Path", "", None, "{offset? (px along the path), flip?: bool (along the path backwards, on its other side), release?: bool (back to lines of text where it starts)} on the selected text on a path (ADR 0070)", true, |s, p| s.each_layer(false, |s| set_path(s, p))), + c("text.release_path", "Release Text from Path", "Modify/Text", None, "{} the selected text on a path goes back to lines of text (ADR 0070)", true, |s, _| s.each_layer(false, |s| set_path(s, &json!({"release": true})))), + c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), ] } @@ -130,22 +150,355 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu outline: Arc::new(layout.outline), box_width: layout.width, box_height: layout.height, + field: None, + on_path: None, }; Ok((block, note)) } -fn style_of(t: &TextBlock) -> TextStyle { +/// A field's text laid out (ADR 0066): `shown` in the block's style, wrapped at the box less its +/// gutters when it is multiline, aligned in the box, with the outline moved into the gutter. +/// The carets are from the text's left edge (the alignment applied, not the gutter). +pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result { + let wrap = field.wrap_width(box_width); + let mut l = fonts.layout( + shown, + &anicraft_text::Style { + family: style.font.clone(), + size: style.size, + bold: style.bold, + italic: style.italic, + align: match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: wrap, + }, + )?; + // Lines that don't wrap align against the widest; the widest aligns in the box. + let inner = (box_width - 2.0 * FIELD_GUTTER).max(0.0); + let shift = match (wrap, style.align) { + (Some(_), _) | (None, TextAlign::Left) => 0.0, + (None, TextAlign::Center) => ((inner - l.width) * 0.5).max(0.0), + (None, TextAlign::Right) => (inner - l.width).max(0.0), + }; + l.outline = l.outline.transformed(&Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER)); + if shift != 0.0 { + for line in &mut l.carets { + for s in &mut line.stops { + s.1 += shift; + } + } + l.width += shift; + } + Ok(l) +} + +/// A field block for `text`: laid out in its box (`box_width` × `box_height`). +pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, box_width: f32, box_height: f32) -> Result<(TextBlock, Option)> { + let fonts = Fonts::get(); + let text: String = text.chars().take(MAX_FIELD_CHARS).collect(); + let l = field_layout(fonts, style, field, box_width, &field.shown(&text)).map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !l.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), l.family)); + let block = TextBlock { + text, + font: l.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: field.wrap_width(box_width), + outline: Arc::new(l.outline), + box_width, + box_height, + field: Some(field.clone()), + on_path: None, + }; + Ok((block, note)) +} + +/// Text on a path (ADR 0070): `text` on one line (line breaks become spaces) set along `on`'s +/// path. The block's space is moved so its box (the path and the glyphs together) starts at +/// the origin, as every text box does: the second value is where that origin was, which the +/// element's transform must move by (`transform × translate(shift)`) for nothing to move. +pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> Result<(TextBlock, Option, Vec2)> { + let fonts = Fonts::get(); + let line: String = text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + let layout = fonts + .layout_glyphs(&line, &anicraft_text::Style { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, align: Align::Left, letter_spacing: style.letter_spacing, line_spacing: 0.0, width: None }) + .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let align = match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }; + let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; + let set = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; + let shift = set.shift; + let block = TextBlock { + text: text.to_string(), + font: layout.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: None, + outline: Arc::new(set.outline), + box_width: set.width, + box_height: set.height, + field: None, + on_path: Some(TextPath { path: set.path, offset, flip: on.flip }), + }; + Ok((block, note, shift)) +} + +/// The block `t` with new text or style: a field keeps its box (or takes `width` as its new +/// width); static text wraps at `width`; text on a path stays on it. With where the block's +/// origin moved to ([`lay_out_on_path`]; zero for the others). +pub(crate) fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option, Vec2)> { + match (&t.field, &t.on_path) { + (_, Some(on)) => lay_out_on_path(text, style, on), + (Some(f), None) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height).map(|(b, n)| (b, n, Vec2::ZERO)), + (None, None) => lay_out(text, style, width).map(|(b, n)| (b, n, Vec2::ZERO)), + } +} + +/// What Find and Replace lays text out with: as before (static text, its fields' boxes +/// dropped), except that text on a path stays on its path. +pub(crate) fn relay_static(t: &TextBlock, text: &str, style: &TextStyle) -> Result<(TextBlock, Option, Vec2)> { + match &t.on_path { + Some(on) => lay_out_on_path(text, style, on), + None => lay_out(text, style, t.width).map(|(b, n)| (b, n, Vec2::ZERO)), + } +} + +/// The selected static text, along a copy of a shape's outline (ADR 0070). +fn attach_path(s: &mut Session, p: &Value) -> Result { + let by_id = opt_u64(p, "path")?.map(ElementId); + let at = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => Some(Vec2::new(x, y)), + (None, None) => None, + _ => return Err(EngineError::Param("give both 'x' and 'y', or neither".into())), + }; + let flip = opt_bool(p, "flip")?.unwrap_or(false); + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + // The shape: by id or by point, on any layer of what is being edited; else the selection's. + let wanted = match (by_id, at) { + (Some(id), _) => Some(id), + (None, Some(pt)) => Some(s.hit_test(pt, 2.0).map(|(_, e)| e).ok_or_else(|| EngineError::State("there is no shape there to set the text along".into()))?), + (None, None) => None, + }; + let texts: Vec = s.selected_elements_mut()?.iter().filter(|e| matches!(&e.kind, ElementKind::Text(t) if t.field.is_none())).map(|e| e.id).collect(); + let [text_id] = texts.as_slice() else { + return Err(EngineError::State(if texts.is_empty() { "select a static text block to set along a path".into() } else { "select one text block to set along a path".into() })); + }; + // The shapes on the timeline being edited at this frame (in its space, as the text is): + // the one asked for, or the selected one. + let selected = s.selection.on(s.layer); + let mut candidates: Vec = Vec::new(); + for l in &s.timeline().layers { + let Some((_, els)) = anicraft_doc::evaluate_layer_elements(l, s.frame) else { continue }; + for e in els.iter() { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let pick = match wanted { + Some(w) => w == e.id, + None => l.id == s.layer && selected.contains(&e.id), + }; + if pick { + candidates.push(sh.path.transformed(&e.transform)); + } + } + } + let path = match candidates.as_slice() { + [path] => path.clone(), + [] => return Err(EngineError::State("pick a shape to set the text along".into())), + _ => return Err(EngineError::State("select the text and one shape (or pick the shape)".into())), + }; + // Its first contour, in the timeline's space (the text takes the path's place). + let first: Path = Path { cmds: path.cmds.iter().enumerate().take_while(|(i, c)| *i == 0 || !matches!(c, anicraft_geom::PathCmd::MoveTo(_))).map(|(_, c)| *c).collect() }; + let length = anicraft_geom::walk::CurveWalk::new(&first).map(|w| w.length()).ok_or_else(|| EngineError::State("the shape's outline has no length to set text along".into()))?; + let mut out = Value::Null; + for e in s.selected_elements_mut()? { + if e.id != *text_id { + continue; + } + let ElementKind::Text(t) = &e.kind else { continue }; + let style = style_of(t); + let offset = offset.unwrap_or(match t.align { + TextAlign::Left => 0.0, + TextAlign::Center => length * 0.5, + TextAlign::Right => length, + }); + let (block, note, shift) = lay_out_on_path(&t.text, &style, &TextPath { path: first.clone(), offset, flip })?; + // The path is in stage space; the text's new space is the path's, moved to its box. + e.transform = Affine::translate(shift.x, shift.y); + out = json!({"element": e.id.0, "length": length, "offset": offset, "flip": flip, "note": note}); + e.kind = ElementKind::Text(Arc::new(block)); + } + s.select_only([*text_id]); + Ok(out) +} + +/// Moves, flips or releases the selected text on a path. +fn set_path(s: &mut Session, p: &Value) -> Result { + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + let flip = opt_bool(p, "flip")?; + let release = opt_bool(p, "release")?.unwrap_or(false); + let mut changed = 0; + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let Some(on) = &t.on_path else { continue }; + let style = style_of(t); + if release { + // Back to a line of text, its box where the text started along the path. + let start = t.outline.bounds(); + let (block, _) = lay_out(&t.text, &style, None)?; + let at = if start.min.x.is_finite() { start.min } else { Vec2::ZERO }; + e.transform = e.transform.mul(&Affine::translate(at.x, at.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } else { + let on = TextPath { offset: offset.unwrap_or(on.offset), flip: flip.unwrap_or(on.flip), ..on.clone() }; + let (block, _, shift) = lay_out_on_path(&t.text, &style, &on)?; + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text on a path".into())); + } + Ok(json!({"changed": changed})) +} + +/// The box a block becomes a field in: the text's own size and the gutters (at least 20 px wide). +fn field_box(t: &TextBlock) -> (f32, f32) { + ((t.width.unwrap_or(t.box_width) + 2.0 * FIELD_GUTTER).max(20.0), t.box_height + 2.0 * FIELD_GUTTER) +} + +fn kind_param(p: &Value) -> Result> { + opt_str(p, "type")?.map(|k| TextKind::from_key(k).ok_or_else(|| EngineError::Param(format!("'type' is static, dynamic or input, not '{k}'")))).transpose() +} + +fn set_field(s: &mut Session, p: &Value) -> Result { + let kind = kind_param(p)?; + let lines = opt_str(p, "lines")?.map(|k| LineType::from_key(k).ok_or_else(|| EngineError::Param(format!("'lines' is single, multiline, multiline_no_wrap or password, not '{k}'")))).transpose()?; + let size = |key: &str| -> Result> { + match opt_f32(p, key)? { + Some(v) if (1.0..=100_000.0).contains(&v) => Ok(Some(v)), + Some(_) => Err(EngineError::Param(format!("'{key}' must be between 1 and 100000 px"))), + None => Ok(None), + } + }; + let (width, height) = (size("width")?, size("height")?); + let max_chars = opt_u32(p, "max_chars")?; + if max_chars.is_some_and(|n| n as usize > MAX_FIELD_CHARS) { + return Err(EngineError::Param(format!("'max_chars' is at most {MAX_FIELD_CHARS}"))); + } + let variable = opt_str(p, "variable")?.map(|v| v.trim().chars().take(MAX_FIELD_NAME).collect::()); + let (selectable, border, background) = (opt_bool(p, "selectable")?, opt_bool(p, "border")?, opt_bool(p, "background")?); + let (border_color, background_color) = (opt_color(p, "border_color")?, opt_color(p, "background_color")?); + let mut changed = 0; + let mut notes = Vec::new(); + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + if t.on_path.is_some() && kind.is_some_and(|k| k != TextKind::Static) { + return Err(EngineError::State("text on a path is static text (release it from the path first)".into())); + } + let to = kind.unwrap_or(t.kind()); + let style = style_of(t); + let (block, note) = if to == TextKind::Static { + if t.field.is_none() { + continue; + } + // Back to static text: laid out as before fields, the words where they were. + e.transform = e.transform.mul(&Affine::translate(FIELD_GUTTER, FIELD_GUTTER)); + e.name.clear(); + lay_out(&t.text, &style, t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)))? + } else { + let (bw, bh) = if t.field.is_some() { (t.box_width, t.box_height) } else { field_box(t) }; + // Wrapped text becomes a multiline field, text with line breaks a multiline one + // that doesn't wrap, the rest a single line. + let lines_of = if t.width.is_some() { + LineType::Multiline + } else if t.text.contains('\n') { + LineType::MultilineNoWrap + } else { + LineType::Single + }; + let mut f = t.field.clone().unwrap_or_else(|| TextField { lines: lines_of, ..TextField::new(to) }); + if t.field.is_none() { + // The text stays where it was; the box grows round it. + e.transform = e.transform.mul(&Affine::translate(-FIELD_GUTTER, -FIELD_GUTTER)); + } + f.kind = to; + if let Some(l) = lines { + if l == LineType::Password && to != TextKind::Input { + return Err(EngineError::Param("only input text can be a password field".into())); + } + f.lines = l; + } + if f.lines == LineType::Password && to != TextKind::Input { + f.lines = LineType::Single; + } + f.selectable = selectable.unwrap_or(f.selectable); + f.border = border.unwrap_or(f.border); + f.background = background.unwrap_or(f.background); + f.border_color = border_color.unwrap_or(f.border_color); + f.background_color = background_color.unwrap_or(f.background_color); + f.max_chars = max_chars.unwrap_or(f.max_chars); + if let Some(v) = &variable { + f.variable.clone_from(v); + } + lay_out_field(&t.text, &style, &f.sanitized(), width.unwrap_or(bw), height.unwrap_or(bh))? + }; + notes.extend(note); + e.kind = ElementKind::Text(Arc::new(block)); + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text to change".into())); + } + notes.dedup(); + Ok(json!({"changed": changed, "note": notes.first()})) +} + +pub(crate) fn style_of(t: &TextBlock) -> TextStyle { TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } } fn create(s: &mut Session, p: &Value) -> Result { let text: String = str_req(p, "text")?.to_string(); - if text.trim().is_empty() { + let kind = kind_param(p)?.unwrap_or_default(); + // An input field may start empty (the viewer fills it in); static text may not. + if text.trim().is_empty() && kind == TextKind::Static { return Err(EngineError::Param("'text' is empty".into())); } let style = style_param(p, &s.text_style)?; let width = width_param(p, None)?; let (block, note) = lay_out(&text, &style, width)?; + let (block, note) = if kind == TextKind::Static { + (block, note) + } else { + let (bw, bh) = field_box(&block); + let f = TextField { lines: if width.is_some() { LineType::Multiline } else if text.contains('\n') { LineType::MultilineNoWrap } else { LineType::Single }, ..TextField::new(kind) }; + lay_out_field(&text, &style, &f, bw, bh)? + }; let x = opt_f32(p, "x")?.unwrap_or((s.doc.stage.width as f32 - block.box_width) * 0.5); let y = opt_f32(p, "y")?.unwrap_or((s.doc.stage.height as f32 - block.box_height) * 0.5); let id = ElementId(s.doc.alloc_id()); @@ -158,21 +511,23 @@ fn create(s: &mut Session, p: &Value) -> Result { } fn edit(s: &mut Session, p: &Value) -> Result { - let new_text = match opt_str(p, "text")? { - Some(t) if t.trim().is_empty() => return Err(EngineError::Param("'text' is empty (delete the text instead)".into())), - t => t.map(str::to_string), - }; + let new_text = opt_str(p, "text")?.map(str::to_string); let mut notes = Vec::new(); let mut edited = 0; let mut last_style = None; for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; let style = style_param(p, &style_of(t))?; - let width = width_param(p, t.width)?; let text = new_text.clone().unwrap_or_else(|| t.text.clone()); - let (block, note) = lay_out(&text, &style, width)?; + // Fields may be empty (a script or the viewer fills them); static text may not. + if text.trim().is_empty() && t.field.is_none() { + return Err(EngineError::Param("'text' is empty (delete the text instead)".into())); + } + let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? }; + let (block, note, shift) = relay(t, &text, &style, width)?; notes.extend(note); last_style = Some(TextStyle { font: block.font.clone(), ..style }); + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); e.kind = ElementKind::Text(Arc::new(block)); edited += 1; } @@ -194,5 +549,5 @@ fn fonts(_: &mut Session, _: &Value) -> Result { /// A text block as a plain shape with the same outlines (Break Apart). pub(crate) fn to_shape(t: &TextBlock) -> anicraft_doc::Shape { let path: Arc = t.outline.clone(); - anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false } + anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None } } diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index 456ddd78..0cbd5802 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -9,10 +9,10 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..], frame?, count?}", true, insert_frame as crate::RunFn), + c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..] | all_layers?: true (every layer with frames at or after the frame, as F5 with no frame selection; the active layer when none has), frame?, count?, advance?: true (the playhead moves onto the last frame inserted, as the key does in the editor)}", true, insert_frame as crate::RunFn), c("timeline.remove_frame", "Remove Frame", "Insert/Timeline", Some("Shift+F5"), "{layer? | layers?: [..], frame?, count?}", true, remove_frame), - c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?}", true, insert_keyframe), - c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?}", true, insert_blank_keyframe), + c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?, advance?: true (on a keyframe the new key goes on the next frame, and the playhead moves onto it, as the key does in the editor)}", true, insert_keyframe), + c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?, advance?: true (on a keyframe the blank key goes on the next frame instead of clearing it, and the playhead moves onto it)}", true, insert_blank_keyframe), c("timeline.clear_keyframe", "Clear Keyframe", "Insert/Timeline", Some("Shift+F6"), "{layer? | layers?: [..], frame?, count?}", true, clear_keyframe), c("timeline.move_keyframes", "Move Keyframes", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}", true, move_keyframes), c("timeline.create_motion_tween", "Create Motion Tween", "Insert", None, "{layer?, frame?} (several objects on the key become one graphic symbol; a one-frame span grows to a second)", true, crate::cmds_motion::create), @@ -58,7 +58,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result { let ty = if is_mask { "normal" } else { "mask" }; set_type(s, id, ty)?; if !is_mask { - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; // The normal layer directly below, in the same folder, becomes masked. let mask_parent = tl.layer(id).and_then(|m| m.parent); if let Some(i) = tl.layers.iter().position(|l| l.id == id) @@ -100,7 +100,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result { if let Some(k) = guide.keyframe_mut(0) { k.duration = s.frame_count().max(1); } - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.insert(i, Arc::new(guide)); if let Some(l) = tl.layers.get_mut(i + 1) { Arc::make_mut(l).parent = Some(gid); @@ -126,8 +126,8 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { Ok(layer_type_json(s, id)) } -fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); +pub(crate) fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) { return Err(EngineError::State("a folder holds layers; it can't become another kind of layer".into())); @@ -161,7 +161,7 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { Ok(()) } -fn layer_type_json(s: &Session, id: LayerId) -> Value { +pub(crate) fn layer_type_json(s: &Session, id: LayerId) -> Value { let Some(l) = s.timeline().layer(id) else { return json!({}) }; let tl = s.timeline(); let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind); @@ -232,19 +232,54 @@ pub(crate) fn shift_after(layer: &mut Layer, from: u32, delta: i64) { } } -/// F5 over a range: `count` frames on each target layer. +/// F5 over a range: `count` frames on each target layer. With `all_layers` (F5 with no frame +/// selection) every layer that has frames at or after `frame` grows, so the layers stay in step; +/// layers that end before it are left alone. With `advance` the playhead moves onto the last +/// frame inserted, as holding F5 walks along the timeline. fn insert_frame(s: &mut Session, p: &Value) -> Result { let (_, frame) = target(s, p)?; let count = count_param(p)?; + let all = opt_bool(p, "all_layers")?.unwrap_or(false); + let ids = if all { layers_at_or_after(s, frame) } else { target_layers(s, p)? }; let mut frames = 0; - for id in target_layers(s, p)? { + for &id in &ids { let layer = s.layer_mut(Some(id))?; for _ in 0..count { - insert_frame_at(layer, frame)?; + if all && layer.keyframe_index_at(frame).is_none() && layer.end_frame() > frame { + // A gap (or the frames before the first key) under the playhead: insert an + // empty frame there, so what follows moves along with the other layers. + insert_empty_frame_at(layer, frame)?; + } else { + insert_frame_at(layer, frame)?; + } } frames = frames.max(layer.end_frame()); } - Ok(json!({"frames": frames})) + let mut out = json!({"frames": frames, "layers": ids.iter().map(|l| l.0).collect::>()}); + if opt_bool(p, "advance")?.unwrap_or(false) { + s.set_frame(frame.saturating_add(count).min(frames.saturating_sub(1))); + out["playhead"] = json!(s.frame); + } + Ok(out) +} + +/// The layers F5 with no frame selection extends: every layer of the timeline with frames at or +/// after `frame` (folders have none). When no layer reaches that far, the active layer, so F5 +/// past the end still lengthens what you are working on. +fn layers_at_or_after(s: &Session, frame: u32) -> Vec { + let tl = s.timeline(); + let ids: Vec = tl.layers.iter().filter(|l| l.kind != LayerKind::Folder && l.end_frame() > frame).map(|l| l.id).collect(); + if ids.is_empty() { vec![s.layer] } else { ids } +} + +/// One empty frame at `frame`: everything from there on moves one frame later. +fn insert_empty_frame_at(layer: &mut Layer, frame: u32) -> Result<()> { + if layer.end_frame() >= MAX_FRAME { + return Err(EngineError::State("the timeline is at its maximum length".into())); + } + shift_after(layer, frame, 1); + layer.normalize(); + Ok(()) } pub(crate) fn insert_frame_at(layer: &mut Layer, frame: u32) -> Result<()> { @@ -353,7 +388,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R // A motion tween split in two keeps moving the same way in both halves. let motion = if copy { k.motion.as_ref().map(|m| { - let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; 8]), |e| anicraft_doc::Props::of(e)); + let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; anicraft_doc::PROPERTIES]), |e| anicraft_doc::Props::of(e)); m.split_at(&base, frame - k.start) }) } else { @@ -393,7 +428,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R } fn insert_keyframe(s: &mut Session, p: &Value) -> Result { - let (_, frame) = target(s, p)?; + let frame = key_frame(s, p)?; for id in target_layers(s, p)? { let layer = s.layer_mut(Some(id))?; // Inside a motion tween F6 keys every property there; the span stays whole. @@ -401,15 +436,38 @@ fn insert_keyframe(s: &mut Session, p: &Value) -> Result { insert_keyframe_at(layer, frame, true)?; } } - Ok(json!({"keyframe": frame})) + advanced(s, p, frame) } fn insert_blank_keyframe(s: &mut Session, p: &Value) -> Result { - let (_, frame) = target(s, p)?; + let frame = key_frame(s, p)?; for id in target_layers(s, p)? { insert_keyframe_at(s.layer_mut(Some(id))?, frame, false)?; } - Ok(json!({"keyframe": frame})) + advanced(s, p, frame) +} + +/// Where F6 / F7 put the key. With `advance`, a frame that is already a keyframe on every target +/// layer means "the next one": pressing F6 again after drawing makes the next drawing's key. +fn key_frame(s: &Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + if !opt_bool(p, "advance")?.unwrap_or(false) { + return Ok(frame); + } + let ids = target_layers(s, p)?; + let tl = s.timeline(); + let on_keys = !ids.is_empty() && ids.iter().all(|id| tl.layer(*id).is_some_and(|l| l.keyframe_starting_at(frame).is_some())); + if on_keys && frame < MAX_FRAME { Ok(frame + 1) } else { Ok(frame) } +} + +/// The result of F6 / F7; with `advance` the playhead moves onto the new key. +fn advanced(s: &mut Session, p: &Value, frame: u32) -> Result { + let mut out = json!({"keyframe": frame}); + if opt_bool(p, "advance")?.unwrap_or(false) { + s.set_frame(frame); + out["playhead"] = json!(frame); + } + Ok(out) } /// Shift+F6 over a range: clears every keyframe starting in `frame..frame + count` on each @@ -656,8 +714,9 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { /// 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)) + // The first seven of the layer colours, in turn. + const TURN: usize = 7; + anicraft_doc::Rgba::hex(crate::LAYER_COLORS.get(n % TURN).copied().unwrap_or(0x4fa3ff)) } fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { @@ -688,7 +747,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { k.duration = s.frame_count().max(1); } layer.color = layer_color(n); - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -709,7 +768,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State("a document needs at least one layer to draw on".into())); } let up = tl.layers.get(i).and_then(|l| l.parent); - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; if !is_folder { for l in tl.layers.iter_mut().filter(|l| l.parent == Some(id)) { Arc::make_mut(l).parent = up; @@ -774,7 +833,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { /// where it landed: moving it in under a folder or mask puts it inside, moving it out frees it. fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let n = tl.layers.len(); if tl.layers.get(i).is_some_and(|l| matches!(l.kind, LayerKind::Mask | LayerKind::Folder)) { diff --git a/crates/engine/src/cmds_view.rs b/crates/engine/src/cmds_view.rs new file mode 100644 index 00000000..1e088563 --- /dev/null +++ b/crates/engine/src/cmds_view.rs @@ -0,0 +1,202 @@ +//! Rulers, grid and guides (ADR 0076): View › Rulers, View › Grid, View › Guides and the pixel +//! snapping in View › Snapping. Whether each shows and snaps is the session's (`ViewAids`, no +//! undo step); the guides, the grid's spacing and colour and the guides' colour are the +//! document's, so changing them is an undoable edit saved with the file. + +use crate::params::*; +use crate::snap::{Accuracy, ViewAids}; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::aids::{GRID_MAX, GRID_MIN}; +use anicraft_doc::{Guide, GuideAxis, MAX_GUIDES}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("view.rulers", "Rulers", "View", Some("Ctrl+Alt+Shift+R"), "{on?: bool} (default: toggle) rulers along the stage's top and left edges, in stage pixels from its top-left corner; drag from one to make a guide", false, (|s, p| toggle(s, p, |a| &mut a.rulers)) as crate::RunFn), + c("view.grid_show", "Show Grid", "View/Grid", Some("Ctrl+'"), "{on?: bool} (default: toggle) the grid on the stage (never in pictures or exports)", false, |s, p| toggle(s, p, |a| &mut a.show_grid)), + c("view.grid_snap", "Snap to Grid", "View/Grid", Some("Ctrl+Shift+'"), "{on?: bool} (default: toggle) points being drawn, dragged or moved snap to the grid's lines (shown or not)", false, |s, p| toggle(s, p, |a| &mut a.snap_grid)), + c( + "view.grid_set", + "Edit Grid…", + "View/Grid", + Some("Ctrl+Alt+G"), + "{spacing?, spacing_x?, spacing_y? (stage pixels, 1..=4096), color?: \"#rrggbb[aa]\", over_objects?: bool, show?: bool, snap?: bool, accuracy?: \"close\"|\"normal\"|\"distant\"|\"always\"} sets the grid; spacing and colour are saved with the document (one undo step), the rest is the editor's; returns everything as view.aids does", + true, + grid_set, + ), + c("view.guides_show", "Show Guides", "View/Guides", Some("Ctrl+;"), "{on?: bool} (default: toggle) this scene's guides on the stage (never in pictures or exports)", false, |s, p| toggle(s, p, |a| &mut a.show_guides)), + c("view.guides_lock", "Lock Guides", "View/Guides", Some("Ctrl+Alt+;"), "{on?: bool} (default: toggle) locked guides can't be dragged, moved or deleted one by one (new ones can still be added, and Clear Guides clears them)", false, |s, p| toggle(s, p, |a| &mut a.lock_guides)), + c("view.guides_snap", "Snap to Guides", "View/Guides", Some("Ctrl+Shift+;"), "{on?: bool} (default: toggle) points being drawn, dragged or moved snap to the guides", false, |s, p| toggle(s, p, |a| &mut a.snap_guides)), + c( + "view.guides_set", + "Edit Guides…", + "View/Guides", + Some("Ctrl+Alt+Shift+G"), + "{color?: \"#rrggbb[aa]\", show?: bool, lock?: bool, snap?: bool, accuracy?: \"close\"|\"normal\"|\"distant\"} sets the guides; the colour is saved with the document (one undo step), the rest is the editor's; returns everything as view.aids does", + true, + guides_set, + ), + c("view.guide_add", "Add Guide…", "View/Guides", None, "{axis: \"horizontal\"|\"vertical\", at} adds a guide to this scene at `at` stage pixels (y for a horizontal guide, x for a vertical one); returns {index, guides}", true, guide_add), + c("view.guide_move", "Move Guide", "", None, "{index, at} moves this scene's guide `index` (as view.aids lists them) to `at`; refused while guides are locked", true, guide_move), + c("view.guide_delete", "Delete Guide", "", None, "{index} removes this scene's guide `index`; refused while guides are locked", true, guide_delete), + c("view.guides_clear", "Clear Guides", "View/Guides", None, "{} removes every guide from this scene (undoable)", true, guides_clear), + c("view.snap_pixels", "Snap to Pixels", "View/Snapping", None, "{on?: bool} (default: toggle) points being drawn, dragged or moved go to whole stage pixels where nothing else snaps them", false, |s, p| toggle(s, p, |a| &mut a.snap_pixels)), + c("view.aids", "Rulers, Grid and Guides", "", None, "{} whether the rulers, grid and guides show and snap, the grid's and guides' settings, and this scene's guides [{axis, at}, ..]", false, |s, _| Ok(aids_json(s))), + ] +} + +fn toggle(s: &mut Session, p: &Value, field: fn(&mut ViewAids) -> &mut bool) -> Result { + let f = field(&mut s.aids); + *f = opt_bool(p, "on")?.unwrap_or(!*f); + Ok(aids_json(s)) +} + +/// Everything about the rulers, grid and guides, as `view.aids` returns it. +pub(crate) fn aids_json(s: &Session) -> Value { + let a = s.aids; + let g = s.doc.aids.grid; + json!({ + "rulers": a.rulers, + "grid": {"show": a.show_grid, "snap": a.snap_grid, "accuracy": a.grid_accuracy.key(), "spacing_x": g.spacing_x, "spacing_y": g.spacing_y, "color": color_hex(g.color), "over_objects": g.over_objects}, + "guides": {"show": a.show_guides, "lock": a.lock_guides, "snap": a.snap_guides, "accuracy": a.guide_accuracy.key(), "color": color_hex(s.doc.aids.guide_color), "list": guides_json(s)}, + "snap_pixels": a.snap_pixels, + "snap_objects": s.style.snap_objects, + }) +} + +fn color_hex(c: anicraft_doc::Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +fn guides_json(s: &Session) -> Value { + json!(s.guides().iter().map(|g| json!({"axis": g.axis.key(), "at": g.at})).collect::>()) +} + +fn accuracy(p: &Value, grid: bool) -> Result> { + let Some(k) = opt_str(p, "accuracy")? else { return Ok(None) }; + match Accuracy::parse(k) { + Some(Accuracy::Always) if !grid => Err(EngineError::Param("guides snap 'close', 'normal' or 'distant' (only the grid can 'always' snap)".into())), + Some(a) => Ok(Some(a)), + None => Err(EngineError::Param(format!("unknown accuracy '{k}' (close, normal, distant{})", if grid { " or always" } else { "" }))), + } +} + +fn spacing(p: &Value, key: &str) -> Result> { + match opt_f32(p, key)? { + Some(v) if !(GRID_MIN..=GRID_MAX).contains(&v) => Err(EngineError::Param(format!("'{key}' must be between {GRID_MIN} and {GRID_MAX} pixels"))), + v => Ok(v), + } +} + +fn grid_set(s: &mut Session, p: &Value) -> Result { + // Everything is read (and checked) before anything changes. + let both = spacing(p, "spacing")?; + let (sx, sy) = (spacing(p, "spacing_x")?.or(both), spacing(p, "spacing_y")?.or(both)); + let color = opt_color(p, "color")?; + let over = opt_bool(p, "over_objects")?; + let (show, snap, acc) = (opt_bool(p, "show")?, opt_bool(p, "snap")?, accuracy(p, true)?); + let mut g = s.doc.aids.grid; + g.spacing_x = sx.unwrap_or(g.spacing_x); + g.spacing_y = sy.unwrap_or(g.spacing_y); + g.color = color.map_or(g.color, anicraft_doc::Rgba::sanitized); + g.over_objects = over.unwrap_or(g.over_objects); + if g != s.doc.aids.grid { + Arc::make_mut(&mut s.doc.aids).grid = g; + } + let a = &mut s.aids; + a.show_grid = show.unwrap_or(a.show_grid); + a.snap_grid = snap.unwrap_or(a.snap_grid); + a.grid_accuracy = acc.unwrap_or(a.grid_accuracy); + Ok(aids_json(s)) +} + +fn guides_set(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?; + let (show, lock, snap, acc) = (opt_bool(p, "show")?, opt_bool(p, "lock")?, opt_bool(p, "snap")?, accuracy(p, false)?); + if let Some(c) = color.map(anicraft_doc::Rgba::sanitized) + && c != s.doc.aids.guide_color + { + Arc::make_mut(&mut s.doc.aids).guide_color = c; + } + let a = &mut s.aids; + a.show_guides = show.unwrap_or(a.show_guides); + a.lock_guides = lock.unwrap_or(a.lock_guides); + a.snap_guides = snap.unwrap_or(a.snap_guides); + a.guide_accuracy = acc.unwrap_or(a.guide_accuracy); + Ok(aids_json(s)) +} + +/// This scene's guides, copy-on-write. +fn guides_mut(s: &mut Session) -> Result<&mut Vec> { + let i = s.scene; + let scene = s.doc.scenes.get_mut(i).ok_or_else(|| EngineError::State("no scene is open".into()))?; + Ok(&mut Arc::make_mut(scene).guides) +} + +fn position(p: &Value) -> Result { + let at = f32_req(p, "at")?; + if at.abs() > anicraft_doc::GUIDE_REACH { + return Err(EngineError::Param(format!("'at' must be within {} pixels of the stage's corner", anicraft_doc::GUIDE_REACH))); + } + Ok(at) +} + +fn index(s: &Session, p: &Value) -> Result { + let n = s.guides().len(); + let i = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("missing param 'index'".into()))?; + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| EngineError::Param(if n == 0 { "this scene has no guides".into() } else { format!("no guide {i} (this scene has {n}: 0 to {})", n - 1) })) +} + +fn unlocked(s: &Session) -> Result<()> { + if s.aids.lock_guides { + return Err(EngineError::State("guides are locked: turn off View › Guides › Lock Guides to move or delete them".into())); + } + Ok(()) +} + +fn guide_add(s: &mut Session, p: &Value) -> Result { + let axis = str_req(p, "axis")?; + let axis = GuideAxis::parse(axis).ok_or_else(|| EngineError::Param(format!("unknown axis '{axis}' (horizontal or vertical)")))?; + let at = position(p)?; + let guide = Guide::new(axis, at).ok_or_else(|| EngineError::Param("'at' must be a number".into()))?; + if s.guides().len() >= MAX_GUIDES { + return Err(EngineError::State(format!("a scene has at most {MAX_GUIDES} guides"))); + } + let guides = guides_mut(s)?; + guides.push(guide); + let index = guides.len() - 1; + Ok(json!({"index": index, "guides": guides_json(s)})) +} + +fn guide_move(s: &mut Session, p: &Value) -> Result { + unlocked(s)?; + let i = index(s, p)?; + let at = position(p)?; + if let Some(g) = guides_mut(s)?.get_mut(i) + && g.at != at + { + g.at = at; + } + Ok(json!({"index": i, "guides": guides_json(s)})) +} + +fn guide_delete(s: &mut Session, p: &Value) -> Result { + unlocked(s)?; + let i = index(s, p)?; + let guides = guides_mut(s)?; + if i < guides.len() { + guides.remove(i); + } + Ok(json!({"deleted": i, "guides": guides_json(s)})) +} + +fn guides_clear(s: &mut Session, _: &Value) -> Result { + let n = s.guides().len(); + if n > 0 { + guides_mut(s)?.clear(); + } + Ok(json!({"cleared": n})) +} diff --git a/crates/engine/src/cmds_warp.rs b/crates/engine/src/cmds_warp.rs new file mode 100644 index 00000000..3d3d923b --- /dev/null +++ b/crates/engine/src/cmds_warp.rs @@ -0,0 +1,397 @@ +//! Asset Warp commands (ADR 0079): a warp mesh on a shape or a bitmap, pins on it, and moving +//! them to bend the artwork. +//! +//! The mesh belongs to the artwork: `warp.add` (and the first `warp.pin_add`) puts it on the +//! element at the playhead and on every keyframe of its layer that holds the same artwork, so +//! keyframes made from it bend the same mesh. Pins are added to and removed from all of those +//! keyframes (where the artwork shows there, so nothing moves), while `warp.pin_move` moves a +//! pin on the keyframe at the playhead only: that is the pose, and poses tween with classic +//! tweens. Inside a tween a move keys the frame with what it shows, as editing any tweened +//! object does. A drag sends many `warp.pin_move` calls inside one gesture: one undo step. +//! +//! A shape edited since by another tool (its outline no longer the one its warp gave it) starts +//! again from how it now looks: its pins stay where they show and become its rest. + +use crate::params::*; +use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; +use anicraft_doc::warp::{self, MAX_EXTENT, MAX_PINS, MAX_RESOLUTION, MAX_WARP_POINTS, MIN_RESOLUTION, PIN_SPACING, Pin, PinId, Warp}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Paint, Shape, evaluate_layer_elements}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c( + "warp.add", + "Add Warp Mesh", + "Modify/Asset Warp", + "{element? (a shape or bitmap; default the one selected), resolution? (cells along the longer side, 2…48; default 12)} → {element, created, resolution, columns, rows}. Covers the artwork with a warp mesh on every keyframe of its layer that holds it (it becomes a drawing object); on artwork that has one, changes the mesh's resolution", + true, + add as crate::RunFn, + ), + c( + "warp.pin_add", + "Add Warp Pin", + "", + "{element?, x, y (stage px, on the artwork)} → {element, pin, created}. Pins the artwork there (adding the mesh first if it has none), on every keyframe that bends the same mesh; nothing moves", + true, + pin_add, + ), + c("warp.pin_move", "Move Warp Pin", "", "{element?, pin, x?, y? (stage px: where the pin goes), dx?, dy? (stage px: by how much), frame?} → {element, pin, at}. Bends the artwork at the frame (keying it inside a tween); pins tween between keyframes", true, pin_move), + c("warp.pin_remove", "Remove Warp Pin", "", "{element?, pin} removes the pin from every keyframe that bends the same mesh; the artwork follows the pins that are left", true, pin_remove), + c("warp.remove", "Remove Warp", "Modify/Asset Warp", "{element?} takes the warp mesh and its pins off the artwork on every keyframe of its layer: it shows as drawn again", true, remove), + c("warp.info", "Warp Mesh", "", "{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)", false, info), + ] +} + +/// The element a warp command acts on: `element`, or the one selected element on the active +/// layer. +fn element_param(s: &Session, p: &Value) -> Result { + if let Some(id) = opt_u64(p, "element")? { + return Ok(ElementId(id)); + } + match s.selection.on(s.layer).as_slice() { + [one] => Ok(*one), + [] => Err(EngineError::State("select a shape or a bitmap first (or give 'element')".into())), + _ => Err(EngineError::State("select just one shape or bitmap to warp".into())), + } +} + +/// Where element `id` is at `frame`, as it shows (tweened): its layer and the element. +fn find(s: &Session, id: ElementId, frame: u32) -> Result<(LayerId, Arc)> { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + Some((l.id, els.iter().find(|e| e.id == id)?.clone())) + }) + .ok_or_else(|| EngineError::State(format!("no element with id {} on the stage at frame {}", id.0, frame + 1))) +} + +fn shape_of(el: &Element) -> Result<&Shape> { + match &el.kind { + ElementKind::Shape(sh) => Ok(sh), + _ => Err(EngineError::State("Asset Warp bends shapes and bitmaps; break a symbol or text apart first (Modify › Break Apart)".into())), + } +} + +fn frame_param(s: &Session, p: &Value) -> Result { + let f = opt_u32(p, "frame")?.unwrap_or(s.frame); + if f > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + Ok(f) +} + +/// The warp a command starts from on `sh`: its own while it shows it, rebased when the shape +/// was edited since, `None` without one. +fn current(sh: &Shape) -> Option { + let w = sh.warp.as_deref()?; + Some(if w.shows(&sh.path) { w.clone() } else { w.rebased(sh.path.clone()) }) +} + +fn check_artwork(path: &Path) -> Result<()> { + if warp::anchor_count(path) > MAX_WARP_POINTS { + return Err(EngineError::State(format!("that artwork has more than {MAX_WARP_POINTS} points: simplify it first (Modify › Shape › Optimize)"))); + } + if Warp::new(Arc::new(path.clone()), MIN_RESOLUTION).grid().is_none() { + return Err(EngineError::State("that artwork has no extent to warp".into())); + } + Ok(()) +} + +/// Runs `edit` on element `id` in the keyframe of `layer` that an edit at `frame` changes (keying +/// the frame inside a classic or shape tween), with the shape and the stage → local map. +fn edit_at(s: &mut Session, layer: LayerId, frame: u32, id: ElementId, edit: impl FnOnce(&mut Shape, &Affine) -> Result) -> Result { + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State("the layer went away".into()))?; + if l.keyframe_at(frame).is_some_and(|k| k.motion.is_some()) { + return Err(EngineError::State("Asset Warp pins tween with classic tweens: this frame is in a motion tween".into())); + } + let (was_layer, was_frame) = (s.layer, s.frame); + s.layer = layer; + s.frame = frame; + let out = (|| { + let kf = s.editable_keyframe_in(KeyEdit::Artwork)?; + let e = kf.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State("that element isn't on this keyframe".into()))?; + let el = Arc::make_mut(e); + let inv = el.transform.inverse().ok_or_else(|| EngineError::State("artwork scaled to nothing can't be warped".into()))?; + let ElementKind::Shape(sh) = &mut el.kind else { return Err(EngineError::State("Asset Warp bends shapes and bitmaps".into())) }; + edit(sh, &inv) + })(); + s.layer = was_layer; + s.frame = was_frame; + out +} + +/// Runs `f` on every other keyframe of `layer` (not the one starting at `skip`) whose element +/// `id` is warped on the same mesh as `rest` (it shows its warp), then bends it again. +fn each_other(s: &mut Session, layer: LayerId, skip: Option, id: ElementId, rest: &Arc, resolution: u32, mut f: impl FnMut(&mut Warp, &mut Shape)) -> Result { + let l = s.layer_mut(Some(layer))?; + let mut n = 0; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.live_warp().is_some_and(|w| anicraft_doc::arc_eq(&w.rest, rest) && w.resolution == resolution)); + if !k.elements.iter().any(same) { + continue; + } + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind + && let Some(mut w) = sh.warp.as_deref().cloned() + { + f(&mut w, sh); + if sh.warp.is_some() { + sh.set_warp(w); + } + n += 1; + } + } + } + Ok(n) +} + +/// The start of the keyframe of `layer` covering `frame`. +fn key_start(s: &Session, layer: LayerId, frame: u32) -> Option { + s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).map(|k| k.start) +} + +fn resolution_param(p: &Value) -> Result> { + match opt_u32(p, "resolution")? { + Some(r) if !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&r) => Err(EngineError::Param(format!("param 'resolution' must be {MIN_RESOLUTION}…{MAX_RESOLUTION}"))), + r => Ok(r), + } +} + +/// Puts a warp on element `id` at the playhead (and on every keyframe holding the same +/// artwork), or changes its resolution. Returns whether it was made, and the warp. +fn ensure(s: &mut Session, layer: LayerId, id: ElementId, resolution: Option) -> Result<(bool, Warp)> { + let frame = s.frame; + // The artwork as it is on the keyframe at the playhead (before any keying), to find copies. + let before: Option> = s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.elements.iter().find(|e| e.id == id)).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.path.clone()), + _ => None, + }); + let (created, w, old) = edit_at(s, layer, frame, id, |sh, _| { + let old = sh.live_warp().map(|w| (w.rest.clone(), w.resolution)); + let (created, mut w) = match current(sh) { + Some(w) => (false, w), + None => { + check_artwork(&sh.path)?; + (true, Warp::new(sh.path.clone(), resolution.unwrap_or(warp::DEFAULT_RESOLUTION))) + } + }; + if let Some(r) = resolution { + w.resolution = r; + } + // A warped shape is a drawing object: drawing over it never cuts its outline. + sh.merge = false; + sh.set_warp(w.clone()); + Ok((created, w, old)) + })?; + let skip = key_start(s, layer, frame); + match old { + // A new resolution: every keyframe on the same mesh takes it. + Some((rest, r)) if !created && Some(r) != resolution && resolution.is_some() => { + each_other(s, layer, skip, id, &rest, r, |x, _| x.resolution = w.resolution)?; + } + Some(_) => {} + None => { + // A new mesh: every other keyframe holding the very artwork it covers gets it too. + let Some(path) = before else { return Ok((created, w)) }; + let l = s.layer_mut(Some(layer))?; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_none() && (Arc::ptr_eq(&sh.path, &path) || *sh.path == *path)); + if k.elements.iter().any(same) { + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind { + sh.merge = false; + let mut x = w.clone(); + x.rest = sh.path.clone(); + sh.set_warp(x); + } + } + } + } + } + } + Ok((created, w)) +} + +fn add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let resolution = resolution_param(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, w) = ensure(s, layer, id, resolution)?; + let g = w.grid(); + Ok(json!({"element": id.0, "created": created, "resolution": w.resolution, "columns": g.map_or(0, |g| g.nx), "rows": g.map_or(0, |g| g.ny)})) +} + +fn stage_point(p: &Value) -> Result { + let v = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if v.x.abs() > MAX_EXTENT || v.y.abs() > MAX_EXTENT { + return Err(EngineError::Param("the point must be within ±1,000,000 px".into())); + } + Ok(v) +} + +fn pin_add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let at = stage_point(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, _) = ensure(s, layer, id, None)?; + let pin = PinId(s.doc.alloc_id()); + let frame = s.frame; + let (rest, mesh) = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + if w.pins.len() >= MAX_PINS { + return Err(EngineError::State(format!("a warp has at most {MAX_PINS} pins"))); + } + let local = inv.apply(at); + let r = w.unmap(local).ok_or_else(|| EngineError::State("click on the artwork to pin it".into()))?; + if w.pins.iter().any(|q| q.rest.distance(r) < PIN_SPACING) { + return Err(EngineError::State("there is a pin there already".into())); + } + w.pins.push(Pin { id: pin, rest: r, at: local }); + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok((r, mesh)) + })?; + // The same pin on every other keyframe bending this mesh, where that point shows there. + let skip = key_start(s, layer, frame); + each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| { + if w.pins.len() < MAX_PINS && w.pin(pin).is_none() { + let shown = w.map(rest); + w.pins.push(Pin { id: pin, rest, at: shown }); + } + })?; + Ok(json!({"element": id.0, "pin": pin.0, "created": created})) +} + +fn pin_id(p: &Value) -> Result { + opt_u64(p, "pin")?.map(PinId).ok_or_else(|| EngineError::Param("param 'pin' (a pin id; see warp.info) is required".into())) +} + +fn pin_move(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let frame = frame_param(s, p)?; + let to = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => Some(Vec2::new(x, y)), + (None, None) => None, + _ => return Err(EngineError::Param("give both 'x' and 'y' (or 'dx' and 'dy')".into())), + }; + let by = Vec2::new(opt_f32(p, "dx")?.unwrap_or(0.0), opt_f32(p, "dy")?.unwrap_or(0.0)); + let (layer, el) = find(s, id, frame)?; + shape_of(&el)?; + let xf = el.transform; + let at = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh: add pins with the Warp tool first".into()))?; + let q = w.pins.iter_mut().find(|q| q.id == pin).ok_or_else(|| EngineError::State(format!("no pin with id {} on that artwork", pin.0)))?; + let local = match to { + Some(t) => inv.apply(t), + None => q.at + inv.apply_vector(by), + }; + if !(local.is_finite() && local.x.abs() <= MAX_EXTENT && local.y.abs() <= MAX_EXTENT) { + return Err(EngineError::Param("the pin must stay within ±1,000,000 px".into())); + } + q.at = local; + sh.set_warp(w); + Ok(local) + })?; + let shown = xf.apply(at); + Ok(json!({"element": id.0, "pin": pin.0, "at": [shown.x, shown.y]})) +} + +fn pin_remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let frame = s.frame; + let mesh = edit_at(s, layer, frame, id, |sh, _| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + let before = w.pins.len(); + w.pins.retain(|q| q.id != pin); + if w.pins.len() == before { + return Err(EngineError::State(format!("no pin with id {} on that artwork", pin.0))); + } + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok(mesh) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| w.pins.retain(|q| q.id != pin))?; + Ok(json!({"element": id.0, "pin": pin.0, "keyframes": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let (layer, el) = find(s, id, s.frame)?; + let sh = shape_of(&el)?; + let frame = s.frame; + let Some(w) = sh.live_warp().cloned() else { + if sh.warp.is_some() { + // Edited since by another tool: the stale warp just goes; the shape stays as it is. + edit_at(s, layer, frame, id, |sh, _| { + sh.warp = None; + Ok(()) + })?; + return Ok(json!({"element": id.0, "keyframes": 1})); + } + return Err(EngineError::State("that artwork has no warp mesh".into())); + }; + edit_at(s, layer, frame, id, |sh, _| { + sh.path = w.rest.clone(); + sh.warp = None; + Ok(()) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &w.rest, w.resolution, |w, sh| { + sh.path = w.rest.clone(); + sh.warp = None; + })?; + Ok(json!({"element": id.0, "keyframes": n + 1})) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let frame = frame_param(s, p)?; + let (layer, el) = find(s, id, frame)?; + let sh = shape_of(&el)?; + let bitmap = matches!(sh.fill, Some(Paint::Bitmap { .. })); + let Some(w) = sh.live_warp() else { + return Ok(json!({"element": id.0, "layer": layer.0, "warped": false, "bitmap": bitmap, "stale": sh.warp.is_some()})); + }; + let g = w.grid(); + let pins: Vec = w + .pins + .iter() + .map(|q| { + let at = el.transform.apply(q.at); + json!({"pin": q.id.0, "at": [at.x, at.y], "rest": [q.rest.x, q.rest.y]}) + }) + .collect(); + Ok(json!({ + "element": id.0, + "layer": layer.0, + "warped": true, + "bitmap": bitmap, + "bent": !w.at_rest(), + "resolution": w.resolution, + "columns": g.map_or(0, |g| g.nx), + "rows": g.map_or(0, |g| g.ny), + "vertices": g.map_or(0, |g| (g.nx + 1) * (g.ny + 1)), + "triangles": g.map_or(0, |g| 2 * g.nx * g.ny), + "pins": pins, + })) +} diff --git a/crates/engine/src/cmds_width.rs b/crates/engine/src/cmds_width.rs index 38fd6d28..3bc2088a 100644 --- a/crates/engine/src/cmds_width.rs +++ b/crates/engine/src/cmds_width.rs @@ -51,7 +51,7 @@ pub(crate) fn visible_shape(s: &Session, id: ElementId) -> Result Ok(el), ElementKind::Shape(_) => Err(EngineError::State("this shape has no stroke (give it one in Properties or with the Ink Bottle)".into())), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => Err(EngineError::State("only shapes have strokes (break it apart with Ctrl+B to edit its lines)".into())), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => Err(EngineError::State("only shapes have strokes (break it apart with Ctrl+B to edit its lines)".into())), } } @@ -62,7 +62,7 @@ pub(crate) fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; match &mut el.kind { ElementKind::Shape(sh) => Ok(sh), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => Err(EngineError::State("only shapes have strokes".into())), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => Err(EngineError::State("only shapes have strokes".into())), } } diff --git a/crates/engine/src/color_tests.rs b/crates/engine/src/color_tests.rs new file mode 100644 index 00000000..0031d910 --- /dev/null +++ b/crates/engine/src/color_tests.rs @@ -0,0 +1,259 @@ +//! Colour effects through the command registry (ADR 0056): every style, switching styles, +//! values on a mixed selection, classic and motion tweens, undo, the file round trip and the +//! renders they give. + +use super::*; +use anicraft_doc::{ColorEffect, ColorStyle, ColorTransform, Property, Rgba}; +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}"), + } +} + +/// A white 20 × 20 square at the origin, selected. +fn square() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#336699", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + s +} + +fn effect(s: &Session) -> ColorEffect { + s.visible_elements().first().map(|e| e.color).unwrap_or_default() +} + +/// The square's colour at the stage centre of its frame (CPU oracle, 1:1), 0–255. +fn pixel(s: &Session, frame: u32) -> [u8; 4] { + let pm = anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap(); + let px = pm.to_rgba8(); + let i = ((10 * pm.width + 10) * 4) as usize; + [px[i], px[i + 1], px[i + 2], px[i + 3]] +} + +fn near(a: [u8; 4], b: [u8; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 1) +} + +#[test] +fn every_style_is_set_and_reported() { + let mut s = square(); + let v = run(&mut s, "element.set_color_effect", json!({"brightness": -50})); + assert_eq!(v, json!({"style": "brightness", "brightness": -50.0})); + assert_eq!(effect(&s), ColorEffect::Brightness(-0.5)); + let v = run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 25})); + assert_eq!(v, json!({"style": "tint", "tint": "#ff0000", "tint_amount": 25.0})); + let v = run(&mut s, "element.set_color_effect", json!({"alpha": 40})); + assert_eq!(v, json!({"style": "alpha", "alpha": 40.0})); + run(&mut s, "element.set_color_effect", json!({"red_multiplier": -100, "red_offset": 255, "alpha_offset": -10.5})); + assert_eq!(effect(&s), ColorEffect::Advanced(ColorTransform { mul: [-1.0, 1.0, 1.0, 0.4], add: [1.0, 0.0, 0.0, -10.5 / 255.0] }), "Advanced starts from the alpha it had"); + let v = run(&mut s, "element.set_color_effect", json!({"style": "none"})); + assert_eq!(v, json!({"style": "none"})); + assert_eq!(effect(&s), ColorEffect::None); +} + +#[test] +fn a_new_style_keeps_the_look_it_can() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 60})); + let before = pixel(&s, 0); + run(&mut s, "element.set_color_effect", json!({"style": "advanced"})); + assert_eq!(effect(&s).style(), ColorStyle::Advanced); + assert!(near(pixel(&s, 0), before), "Advanced is exactly the tint"); + run(&mut s, "element.set_color_effect", json!({"style": "brightness"})); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + run(&mut s, "element.set_color_effect", json!({"style": "tint"})); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }); +} + +#[test] +fn bad_params_change_nothing() { + let mut s = square(); + let before = s.doc.clone(); + for p in [ + json!({}), + json!({"style": "sepia"}), + json!({"brightness": 101}), + json!({"tint_amount": -1}), + json!({"red_offset": 300}), + json!({"alpha": 50, "brightness": 10}), + json!({"style": "tint", "alpha": 50}), + json!({"tint": "red"}), + json!({"alpha": f64::NAN}), + ] { + assert!(s.execute("element.set_color_effect", &p).is_err(), "{p}"); + } + assert_eq!(s.doc, before); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.set_color_effect", &json!({"style": "alpha"})).is_err(), "nothing selected"); +} + +#[test] +fn renders_follow_the_arithmetic() { + // #336699 = (51, 102, 153). + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 50})); + assert!(near(pixel(&s, 0), [153, 179, 204, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + assert!(near(pixel(&s, 0), [153, 51, 77, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 50, "blue_offset": -100})); + // The tint carried over into Advanced (×50 %, +127.5 red), then these channels changed. + let fx = effect(&s).transform(); + assert_eq!((fx.mul[0], fx.add[0], fx.mul[1], fx.add[2]), (-1.0, 1.0, 0.5, -100.0 / 255.0)); + assert!(near(pixel(&s, 0), [204, 51, 0, 255]), "{:?}", pixel(&s, 0)); +} + +#[test] +fn a_change_on_a_mixed_selection_sets_only_that_value() { + let mut s = Session::default(); + let a = run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + let b = run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [a]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + run(&mut s, "element.select", json!({"ids": [b]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#0000ff", "tint_amount": 10})); + run(&mut s, "element.select", json!({"ids": [a, b]})); + run(&mut s, "element.set_color_effect", json!({"tint_amount": 80})); + let fx: Vec = s.visible_elements().iter().map(|e| e.color).collect(); + assert_eq!(fx, [ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.8 }, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.8 }], "each keeps its colour"); + // One undo step puts both back. + s.undo().unwrap(); + assert_eq!(s.visible_elements()[1].color, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.1 }); +} + +#[test] +fn set_alpha_keeps_the_rest_of_the_effect() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 20})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::brightness(0.2))); + run(&mut s, "element.set_color_effect", json!({"style": "none"})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); +} + +#[test] +fn a_classic_tween_between_styles_travels_in_the_advanced_space() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 100})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"alpha": 50})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + let mid = effect(&s); + assert_eq!(mid.style(), ColorStyle::Advanced); + let want = ColorTransform::tint(Rgba::hex(0xff0000), 1.0).lerp(&ColorTransform::alpha(0.5), 0.5); + let got = mid.transform(); + assert!(got.mul.iter().zip(want.mul).chain(got.add.iter().zip(want.add)).all(|(a, b)| (a - b).abs() < 1e-5), "{got:?} vs {want:?}"); + // Within one style the value itself travels: brightness −100 % to +100 % is 0 halfway. + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": -100})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"brightness": 100})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + assert!(near(pixel(&s, 5), [51, 102, 153, 255])); +} + +#[test] +fn motion_tweens_key_brightness_tint_and_advanced() { + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "brightness", "frame": 10, "value": 60})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.3)); + // A second style composes with the first into Advanced, exactly. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + run(&mut s, "motion.set_key", json!({"property": "tint_red", "frame": 0, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "tint_green", "frame": 0, "value": 0})); + run(&mut s, "motion.set_key", json!({"property": "tint_blue", "frame": 0, "value": 0})); + s.set_frame(10); + let want = ColorTransform::brightness(0.6).concat(&ColorTransform::tint(Rgba::hex(0xff0000), 0.5)); + assert_eq!(effect(&s).transform(), want); + // Advanced channels on their own curves. + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "red_offset", "frame": 10, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "alpha_multiplier", "frame": 10, "value": 0})); + s.set_frame(5); + let fx = effect(&s); + assert_eq!(fx.style(), ColorStyle::Advanced); + assert_eq!(fx.transform(), ColorTransform { mul: [1.0, 1.0, 1.0, 0.5], add: [0.5, 0.0, 0.0, 0.0] }); + assert!(s.execute("motion.set_key", &json!({"property": "red_offset", "frame": 3, "value": 256})).is_err()); + // Info lists the keys by their names. + let info = run(&mut s, "motion.info", json!({})); + assert!(info.to_string().contains("red_offset"), "{info}"); +} + +#[test] +fn a_motion_tween_has_one_colour_effect_style() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 40})); + run(&mut s, "timeline.create_motion_tween", json!({})); + // Untracked, the target's own tint shows all along. + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::hex(0x00ff00), amount: 0.4 }); + // Keying alpha makes it an alpha tween, as in Animate. + run(&mut s, "motion.set_key", json!({"property": "alpha", "frame": 10, "value": 0})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); + // Changing the alpha in Properties inside the span keys it there. + s.set_frame(4); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"alpha": 90})); + s.set_frame(4); + assert!((effect(&s).alpha() - 0.9).abs() < 1e-4, "{:?}", effect(&s)); + assert!(layer_motion_has(&s, Property::Alpha) && !layer_motion_has(&s, Property::Tint)); + // Keying tint as well composes the two (older files keyed both); the tint colour is the + // target's own. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + s.set_frame(10); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.0).concat(&ColorTransform::tint(Rgba::hex(0x00ff00), 0.5)), "the tint keys start from the target's own colour"); +} + +fn layer_motion_has(s: &Session, p: Property) -> bool { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).is_some_and(|m| m.track(p).is_some()) +} + +#[test] +fn files_keep_every_style() { + let mut s = Session::default(); + for (i, p) in [json!({"brightness": -30}), json!({"tint": "#123456", "tint_amount": 0}), json!({"style": "advanced", "blue_multiplier": -40, "green_offset": 12}), json!({"alpha": 100})].into_iter().enumerate() { + let id = run(&mut s, "draw.rect", json!({"x": i * 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [id]})); + run(&mut s, "element.set_color_effect", p); + } + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let styles: Vec = back.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color.style()).collect(); + assert_eq!(styles, [ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]); +} + +#[test] +fn plug_ins_may_set_colour_effects() { + assert!(crate::cmds_plugin::plugin_may_call("element.set_color_effect").is_ok()); +} + +#[test] +fn a_nine_slice_instance_takes_its_colour_effect() { + // ADR 0055 with ADR 0056: the slices are geometry; the colour effect applies to all of them. + let mut s = square(); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"})); + run(&mut s, "symbol.set_scale_grid", json!({"on": true, "left": 5, "right": 15, "top": 5, "bottom": 15})); + run(&mut s, "element.set_transform", json!({"sx": 3.0, "sy": 3.0})); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + let dl = anicraft_doc::evaluate(&s.doc, 0); + assert!(!dl.items.is_empty()); + let want = ColorTransform::tint(Rgba::hex(0xff0000), 0.5); + assert!(dl.items.iter().all(|i| i.color == want), "every slice is tinted"); +} diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 57de4cc9..5881bdda 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -38,6 +38,10 @@ fn plural(n: usize, word: &str) -> String { if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") } } +fn swatches(n: usize) -> String { + if n == 1 { "1 swatch".into() } else { format!("{n} swatches") } +} + fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); s.timeline().layer(id) @@ -98,7 +102,66 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } - "file.new" | "file.new_sample" | "file.open" | "file.recover" if s.is_dirty() => Some(Confirmation { + "file.save_as_template" => { + let path = crate::cmds_template::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the template")) + } + "file.delete_template" => { + let path = crate::cmds_template::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + Some(Confirmation { + title: "Delete template?".into(), + message: format!("The template “{name}” and its picture will be deleted from your templates. This cannot be undone."), + action: "Delete Template".into(), + irreversible: true, + }) + } + // Brushes of your own live in your preferences, outside undo (ADR 0068). + "brush.preset_delete" => { + let name = p.get("name").and_then(Value::as_str)?; + let i = s.brushes.position(name)?; + let name = s.brushes.user().get(i)?.name.clone(); + Some(Confirmation { + title: "Delete brush?".into(), + message: format!("The brush “{name}” will be deleted from your brushes. This cannot be undone."), + action: "Delete Brush".into(), + irreversible: true, + }) + } + // Swatches are document data and undoable (ADR 0078): replacing many asks by default. + "swatch.export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the swatches")) + } + "swatch.clear" => { + let n = s.doc.swatches.len(); + (n > 2).then(|| Confirmation { + title: "Clear swatches?".into(), + message: format!("{} will be removed, leaving black and white. You can undo this.", swatches(n)), + action: "Clear Swatches".into(), + irreversible: false, + }) + } + "swatch.reset" => { + let custom = !anicraft_doc::swatch::is_default_set(&s.doc.swatches) && !s.doc.swatches.is_empty(); + custom.then(|| Confirmation { + title: "Load the default swatches?".into(), + message: "The document's swatches will be replaced with a new document's set. You can undo this.".into(), + action: "Load Default Swatches".into(), + irreversible: false, + }) + } + "swatch.import" if p.get("replace").and_then(Value::as_bool) == Some(true) && !s.doc.swatches.is_empty() => Some(Confirmation { + title: "Replace swatches?".into(), + message: format!("The document's {} will be replaced with the file's. You can undo this.", swatches(s.doc.swatches.len())), + action: "Replace Swatches".into(), + irreversible: false, + }), + "brush.preset_export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the brushes")) + } + "file.new" | "file.new_sample" | "file.new_from_template" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation { title: "Discard unsaved changes?".into(), message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)), action: "Discard Changes".into(), @@ -109,10 +172,28 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let same = s.path.as_deref() == Some(path); (!same && crate::vfs::exists(path)).then(|| overwrite(path, "Saving")) } - "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { + "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting")) } + "file.publish" => { + // Publishing replaces what is already there; what this session published itself + // it replaces without asking again (ADR 0060). + let found = crate::publish::existing(s, &crate::publish::planned(s, p)?); + let names: Vec = found.iter().take(3).map(|f| f.display().to_string()).collect(); + let more = found.len().saturating_sub(names.len()); + (!found.is_empty()).then(|| Confirmation { + title: if found.len() == 1 { "Replace published file?".into() } else { "Replace published files?".into() }, + message: format!( + "Publishing replaces {} already there: {}{}. This cannot be undone.", + if found.len() == 1 { "a file".to_string() } else { plural(found.len(), "file") }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Publish".into(), + irreversible: true, + }) + } "file.export_sprite_sheet" => { // The sheet and its frame map: either one already there is replaced. let path = Path::new(p.get("path").and_then(Value::as_str)?); @@ -144,6 +225,16 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } + "find.replace" => { + // Replace All over many places asks first (ADR 0058); one undo step takes it back. + let n = crate::find::replace_count(s, p)?; + (n > crate::find::REPLACE_ASK).then(|| Confirmation { + title: "Replace all?".into(), + message: format!("This replaces what was found in {}. You can undo this in one step.", plural(n, "place")), + action: "Replace All".into(), + irreversible: false, + }) + } "library.delete" => { // Routine when nothing deleted is in use and no folder holds anything (undo is there); // asks when instances go with it or a folder takes its contents (ADR 0050). diff --git a/crates/engine/src/drop_tests.rs b/crates/engine/src/drop_tests.rs new file mode 100644 index 00000000..8f5b9d68 --- /dev/null +++ b/crates/engine/src/drop_tests.rs @@ -0,0 +1,224 @@ +//! Files dropped onto the window and recent files (ADR 0059): routing by type and target, what +//! `file.drop` brings in and where, one undo step, and the recent list that opening and saving +//! keep. + +use super::*; +use crate::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; +use serde_json::json; +use std::path::Path; + +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 temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-drop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a one-rectangle SVG and a short WAV in `dir`. +fn media(dir: &Path) -> (String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + (png.display().to_string(), svg.display().to_string(), wav.display().to_string()) +} + +#[test] +fn drops_route_by_file_type_and_target() { + use DropAction::*; + use DropTarget::*; + let k = |p: &str| kind_of(Path::new(p)); + assert_eq!(k("a.anicraft"), DropKind::Document); + assert_eq!(k("A.FLA"), DropKind::Document); + assert_eq!(k("b.xfl"), DropKind::Document); + assert_eq!(k("c.svg"), DropKind::Drawing); + assert_eq!(k("d.JPEG"), DropKind::Image); + assert_eq!(k("d.jpg"), DropKind::Image); + assert_eq!(k("e.png"), DropKind::Image); + assert_eq!(k("f.mp3"), DropKind::Sound); + assert_eq!(k("g.ogg"), DropKind::Sound); + assert_eq!(k("h.wav"), DropKind::Sound); + assert_eq!(k("i.psd"), DropKind::Unsupported); + assert_eq!(k("no extension"), DropKind::Unsupported); + // An XFL package is a folder with a DOMDocument.xml. + let dir = temp_dir("xfl").join("Movie"); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(kind_of(&dir), DropKind::Unsupported, "a plain folder"); + std::fs::write(dir.join("DOMDocument.xml"), "").unwrap(); + assert_eq!(kind_of(&dir), DropKind::Document); + // Documents open wherever they land; media go where they are dropped. + for t in [Stage, Library, Window] { + assert_eq!(route(DropKind::Document, t), Open); + assert!(matches!(route(DropKind::Unsupported, t), Refuse(_))); + } + for kind in [DropKind::Drawing, DropKind::Image, DropKind::Sound] { + assert_eq!(route(kind, Stage), ImportToStage); + assert!(matches!(route(kind, Window), Refuse(_)), "only the stage, the timeline and the Library take media"); + // The Library takes drawings too, as graphic symbols (ADR 0065); a layer's frame takes all. + assert_eq!(route(kind, Library), ImportToLibrary); + assert_eq!(route(kind, Timeline), ImportToTimeline); + } + assert!(matches!(route(DropKind::Unsupported, Timeline), Refuse(_))); + assert_eq!(route(DropKind::Document, Timeline), Open); +} + +#[test] +fn media_dropped_on_the_stage_land_on_the_active_layer_at_the_drop_point_in_one_step() { + let dir = temp_dir("stage"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + run(&mut s, "timeline.insert_frame", json!({"count": 20})); + s.set_frame(5); + let layers = s.timeline().layers.len(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg, wav], "to": "stage", "x": 100, "y": 60})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!(s.timeline().layers.len(), layers, "everything went onto the active layer"); + assert_eq!(v["elements"].as_array().map(Vec::len), Some(2), "{v}"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + // Centred on the drop point, in the keyframe that shows at the playhead. + let layer = s.active_layer().unwrap(); + let key = layer.keyframe_at(5).unwrap(); + assert!(s.selection.ids().all(|id| key.elements.iter().any(|e| e.id == id))); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 100.0).abs() < 0.01 && (b.center().y - 60.0).abs() < 0.01, "{b:?}"); + } + assert!(key.sound.is_some(), "the sound is on the keyframe at the playhead"); + assert_eq!((s.doc.bitmaps.len(), s.doc.sounds.len()), (1, 1), "the image and the sound are in the Library"); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.bitmaps.is_empty() && s.doc.sounds.is_empty() && s.active_layer().unwrap().keyframe_at(5).is_none_or(|k| k.elements.is_empty())); +} + +#[test] +fn media_dropped_on_the_library_go_into_the_folder_under_the_pointer() { + let dir = temp_dir("library"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + let folder = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png.clone(), wav], "to": "library", "folder": folder})); + assert_eq!(s.history_len(), history + 1); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2)); + let in_folder = s.doc.folder_contents(anicraft_doc::FolderId(folder)); + assert_eq!(in_folder.len(), 2, "{in_folder:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty() && k.sound.is_none())), "nothing placed on the stage"); + // The same image again: numbered, not refused. + run(&mut s, "file.drop", json!({"path": png.clone(), "to": "library", "folder": folder})); + let names: Vec = s.doc.folder_contents(anicraft_doc::FolderId(folder)).into_iter().filter_map(|e| s.doc.entry_name(e).map(str::to_string)).collect(); + assert!(names.contains(&"photo.png".to_string()) && names.contains(&"photo.png 2".to_string()), "{names:?}"); + // At the top level without a folder. + run(&mut s, "file.drop", json!({"path": png, "to": "library"})); + assert_eq!(s.doc.bitmaps.len(), 3); + // A drawing goes in as one graphic symbol named after the file (ADR 0065), into the folder. + let symbols = s.doc.library.len(); + let v = run(&mut s, "file.drop", json!({"paths": [svg], "to": "library", "folder": folder})); + assert_eq!(s.doc.library.len(), symbols + 1, "{v}"); + let sym = s.doc.library.last().unwrap(); + assert_eq!((sym.name.as_str(), sym.kind), ("badge", anicraft_doc::SymbolKind::Graphic)); + assert!(s.doc.folder_contents(anicraft_doc::FolderId(folder)).contains(&anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(sym.id)))); + // Nothing is imported when one file is refused. + let before = s.doc.clone(); + assert!(s.execute("file.drop", &json!({"paths": [png.clone(), dir.join("notes.txt").display().to_string()], "to": "library"})).is_err()); + assert!(s.doc == before); +} + +#[test] +fn drawings_with_layers_keep_them_and_bad_drops_change_nothing() { + let dir = temp_dir("bad"); + let (png, _, _) = media(&dir); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let mut s = Session::default(); + let layers = s.timeline().layers.len(); + run(&mut s, "file.drop", json!({"path": masked.display().to_string(), "to": "stage", "x": 10, "y": 10})); + assert!(s.timeline().layers.len() > layers + 1, "a masked drawing brings its folder and mask layer"); + let before = s.doc.clone(); + let doc = dir.join("x.anicraft"); + for p in [ + json!({"path": doc.display().to_string(), "to": "stage"}), + json!({"path": dir.join("y.psd").display().to_string(), "to": "stage"}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "stage"}), + json!({"path": png.clone(), "to": "timeline"}), + json!({"path": png.clone(), "to": "library", "folder": u64::MAX}), + json!({"path": png.clone(), "to": "stage", "folder": 1}), + json!({"path": png.clone(), "to": "stage", "x": f64::MAX, "y": 0}), + json!({"paths": [], "to": "stage"}), + json!({"paths": vec![png.clone(); 65], "to": "stage"}), + json!({"paths": "x", "to": "stage"}), + json!({"paths": [1, 2], "to": "library"}), + json!({"to": "stage"}), + json!({}), + Value::Null, + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + // A locked layer refuses the drop and says why. + let top = s.timeline().layers.len() - 1; + run(&mut s, "layer.select", json!({"index": top})); + run(&mut s, "layer.toggle_lock", json!({})); + let e = s.execute("file.drop", &json!({"path": png, "to": "stage"})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); +} + +#[test] +fn opening_and_saving_keep_the_recent_list_and_open_recent_reopens() { + let dir = temp_dir("recent"); + let a = dir.join("a.anicraft"); + let b = dir.join("b.anicraft"); + let mut s = Session::new(anicraft_doc::sample::demo()); + run(&mut s, "file.save_as", json!({"path": a.display().to_string()})); + run(&mut s, "file.new", json!({"width": 1280, "height": 720})); + run(&mut s, "file.save_as", json!({"path": b.display().to_string()})); + let list = run(&mut s, "file.recent_list", json!({})); + let names: Vec<&str> = list["files"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).collect(); + assert_eq!(names, ["b.anicraft", "a.anicraft"], "most recent first; New doesn't clear it"); + // Open Recent by index opens it, and moves it to the top. + run(&mut s, "file.open_recent", json!({"index": 1})); + assert_eq!(s.path.as_deref(), Some(a.as_path())); + assert_eq!(s.doc.stage.width, anicraft_doc::sample::demo().stage.width); + assert_eq!(s.recent.entries().first().map(|e| e.path.clone()), Some(a.clone())); + // Over unsaved work it asks first, like Open. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.open_recent", &json!({"index": 1})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.open_recent", &json!({"index": 1})).is_err()); + run(&mut s, "file.open_recent", json!({"index": 1, "confirm": true})); + assert_eq!(s.path.as_deref(), Some(b.as_path())); + // A file that is gone stays listed, marked missing, and says so when opened. + std::fs::remove_file(&a).unwrap(); + let list = run(&mut s, "file.recent_list", json!({})); + let gone = list["files"].as_array().unwrap().iter().find(|f| f["name"] == "a.anicraft").unwrap(); + assert_eq!(gone["missing"], true); + let e = s.execute("file.open_recent", &json!({"path": a.display().to_string()})).unwrap_err(); + assert!(e.to_string().contains("no longer there"), "{e}"); + // Pin, remove, clear. + run(&mut s, "prefs.recent_pin", json!({"path": a.display().to_string()})); + assert!(s.recent.entries().first().is_some_and(|e| e.pinned)); + run(&mut s, "prefs.recent_clear", json!({})); + assert_eq!(s.recent.len(), 1, "the pinned file stays"); + run(&mut s, "prefs.recent_remove", json!({"index": 0})); + assert!(s.recent.is_empty()); + // Hostile params never panic and never change the list. + run(&mut s, "file.open", json!({"path": b.display().to_string()})); + let before = s.recent.clone(); + for id in ["file.open_recent", "prefs.recent_pin", "prefs.recent_remove"] { + for p in [json!({"index": u64::MAX}), json!({"index": -1}), json!({"path": ""}), json!({"index": 0, "path": "x"}), json!({"pinned": "x"}), json!("x"), Value::Null] { + let _ = s.execute(id, &p); + assert_eq!(s.recent, before, "{id} {p}"); + } + } + // Restored autosaves and untitled opens aren't recent files. + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "unsaved": true})); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "untitled": true, "confirm": true})); + assert!(t.recent.is_empty()); +} diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 2928925e..5024ceb3 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -13,7 +13,7 @@ use crate::history::StateId; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::hash::{Hash, Hasher}; @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Edit Symbols", "Edit", Some("Ctrl+E"), - "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", + "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. A group (ADR 0073) or a drawing object (ADR 0080) opens in place the same way: inside, its raw shapes merge only with each other, and a drawing object closes as one object again (a group of its pieces when an edit left several). Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", false, edit as crate::RunFn, ), @@ -40,10 +40,31 @@ const MAX_LEVELS: usize = 32; /// How much the artwork around an open symbol shows (Animate dims it). const DIM: f32 = 0.35; -/// A symbol open for editing, and what to go back to. +/// What a level of the editing stack has open. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Opened { + /// A symbol's timeline (ADR 0045). + Symbol(SymbolId), + /// A group's members (ADR 0073): the group is [`EditLevel::instance`] on the timeline below, + /// on the keyframe at [`EditLevel::frame`]. + Group, + /// A drawing object opened in place (ADR 0080): while it is open it is a group of its raw + /// shapes, as [`Opened::Group`]; closing it makes it one drawing object again when it holds + /// one shape (a group of its pieces when it holds several, as Combine Objects' Union). + Drawing, +} + +impl Opened { + /// Whether this level opens a group's members (a group, or a drawing object being edited). + pub fn is_group(self) -> bool { + matches!(self, Opened::Group | Opened::Drawing) + } +} + +/// A symbol or group open for editing, and what to go back to. #[derive(Clone, Debug, PartialEq)] pub struct EditLevel { - pub symbol: SymbolId, + pub open: Opened, /// The instance it was opened from, on the timeline below (none: from the Library). pub instance: Option<(LayerId, ElementId)>, /// Stage space from the symbol's space: where the instance stands (through every level). @@ -52,24 +73,84 @@ pub struct EditLevel { pub layer: LayerId, pub frame: u32, pub selection: Selection, + /// A drawing object opened in place (ADR 0080): the document and state from before it was + /// opened, and the state right after, so closing it without an edit puts both back. + pub back: Option>, } -/// The timeline being edited: the open symbol's, else the scene's. -pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline { - match editing.last().and_then(|l| doc.symbol(l.symbol)) { - Some(sym) => &sym.timeline, - None => doc.timeline(scene), +impl EditLevel { + /// The symbol this level has open (`None` for a group). + pub fn symbol(&self) -> Option { + match self.open { + Opened::Symbol(id) => Some(id), + Opened::Group | Opened::Drawing => None, + } } } -/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using the session's others. -pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> &'a mut Timeline { - let open = editing.last().and_then(|l| doc.library.iter().position(|s| s.id == l.symbol)); +/// The members of the group level `l` opens, on timeline `below`. +fn group_in<'a>(below: &'a Timeline, l: &EditLevel) -> Option<&'a Timeline> { + let (layer, id) = l.instance?; + let k = below.layer(layer)?.keyframe_at(l.frame)?; + match &k.elements.iter().find(|e| e.id == id)?.kind { + ElementKind::Group { members } => Some(members), + _ => None, + } +} + +/// [`group_in`], copy-on-write. +fn group_in_mut<'a>(below: &'a mut Timeline, l: &EditLevel) -> Option<&'a mut Timeline> { + let (layer, id) = l.instance?; + let layer = below.layer_mut(layer)?; + let k = layer.keyframe_index_at(l.frame)?; + let el = layer.keyframe_mut(k)?.elements_mut_where(|e| e == id).into_iter().next()?; + match &mut el.kind { + ElementKind::Group { members } => Some(members), + _ => None, + } +} + +/// How many levels of `editing`, from the outermost, still open something, and the timeline the +/// last of them opens. +fn walk<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> (usize, &'a Timeline) { + let mut tl = doc.timeline(scene); + for (i, l) in editing.iter().enumerate() { + let next = match l.open { + Opened::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), + Opened::Group | Opened::Drawing => group_in(tl, l), + }; + match next { + Some(t) => tl = t, + None => return (i, tl), + } + } + (editing.len(), tl) +} + +/// The timeline being edited: the open symbol's or group's, else the scene's. +pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline { + walk(doc, scene, editing).1 +} + +/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using +/// the session's others. Fails only when an open group is gone, which [`Session::fix_editing`] +/// never leaves for long. +pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> Result<&'a mut Timeline> { + let (valid, _) = walk(doc, scene, editing); + let levels = editing.get(..valid).unwrap_or_default(); + // From the innermost open symbol (or the scene), through the groups opened inside it. + let base = levels.iter().rposition(|l| matches!(l.open, Opened::Symbol(_))); + let open = base.and_then(|b| levels.get(b)).and_then(EditLevel::symbol).and_then(|id| doc.library.iter().position(|s| s.id == id)); + let groups = levels.get(base.map_or(0, |b| b + 1)..).unwrap_or_default(); // (Borrowed only on the branch that returns it.) - match open { + let mut tl = match open { Some(i) if i < doc.library.len() => &mut Arc::make_mut(&mut doc.library[i]).timeline, _ => doc.timeline_mut(scene), + }; + for l in groups { + tl = group_in_mut(tl, l).ok_or_else(|| EngineError::State("the group open for editing is gone".into()))?; } + Ok(tl) } /// How the stage shows the open symbol: its space on the stage is `translate(origin) · @@ -103,6 +184,20 @@ pub struct Front { pub timeline: Timeline, pub frame: u32, pub at: Affine, + /// The timeline the symbol was opened from, when it shows around it (in place): with onion + /// skin on, its frames around its own playhead show dimmed too (ADR 0061). + pub parent: Option, +} + +/// A timeline drawn dimmed around an open symbol: the picture's layer `layer` shows `timeline` +/// (without the instance that was opened) at its `frame`, placed by `at`, at opacity `dim`. +#[derive(Clone, Debug)] +pub struct Around { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, + pub dim: f32, } impl Session { @@ -111,22 +206,32 @@ impl Session { edited(&self.doc, self.scene, &self.editing) } - /// The symbol open for editing, if any. + /// The symbol open for editing, if any (`None` on the stage and while a group is open). pub fn editing_symbol(&self) -> Option { - self.editing.last().map(|l| l.symbol) + self.editing.last().and_then(EditLevel::symbol) } - /// Closes levels whose symbol is gone (an undo, a Library deletion), from the first such. + /// Whether a group is open for editing (ADR 0073). + pub fn editing_group(&self) -> bool { + self.editing.last().is_some_and(|l| l.open.is_group()) + } + + /// Whether a drawing object is open for editing (ADR 0080). + pub fn editing_drawing(&self) -> bool { + self.editing.last().is_some_and(|l| l.open == Opened::Drawing) + } + + /// Closes levels whose symbol or group is gone (an undo, a Library deletion, an ungroup), + /// from the first such. pub(crate) fn fix_editing(&mut self) { - if let Some(i) = self.editing.iter().position(|l| self.doc.symbol(l.symbol).is_none()) { - while self.editing.len() > i { - self.exit_level(); - } + let (valid, _) = walk(&self.doc, self.scene, &self.editing); + while self.editing.len() > valid { + self.exit_level(); } } - fn enter_level(&mut self, symbol: SymbolId, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { - self.editing.push(EditLevel { symbol, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection) }); + fn enter_level(&mut self, open: Opened, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { + self.editing.push(EditLevel { open, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection), back: None }); // The top layer inside, at the frame the instance shows. self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); self.frame = frame.min(self.timeline().frame_count().saturating_sub(1)); @@ -138,9 +243,11 @@ impl Session { /// none is open. pub(crate) fn exit_level(&mut self) -> bool { let Some(l) = self.editing.pop() else { return false }; + let gone = l.open == Opened::Drawing && self.close_drawing(&l); self.layer = l.layer; self.frame = l.frame; self.selection = match l.instance { + Some(_) if gone => Selection::default(), Some((layer, id)) => Selection::only(layer, [id]), None => l.selection, }; @@ -175,8 +282,10 @@ impl Session { let mut h = std::collections::hash_map::DefaultHasher::new(); (self.state, self.scene, self.frame).hash(&mut h); for l in &self.editing { - (l.symbol, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); + (l.open, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); } + let hit = self.hit_overlay(); + hit.map(|(c, a)| [c.r, c.g, c.b, c.a, a].map(f32::to_bits)).hash(&mut h); let key = h.finish(); if let Some((k, pic)) = &*self.picture_cache.borrow() && *k == key @@ -188,21 +297,30 @@ impl Session { // The open symbol, in front. let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); let open = self.timeline().clone(); - let layer = placed(&mut doc, open.clone(), at, self.frame, 1.0); - let front = Arc::new(Front { layer: layer.id, timeline: open, frame: self.frame, at }); + // A button's hit area over the state being edited, translucent (ADR 0057). + if let Some((tint, alpha)) = hit { + let frame = anicraft_doc::player::hit_frame(open.frame_count()); + tl.layers.push(placed(&mut doc, hit_timeline(&open), at, frame, ColorEffect::Advanced(hit_tint(tint, alpha)))); + } + let layer = placed(&mut doc, open.clone(), at, self.frame, ColorEffect::default()); + let mut front = Front { layer: layer.id, timeline: open, frame: self.frame, at, parent: None }; tl.layers.push(layer); // Around it, dimmed: each timeline below, without the instance opened from it. if view.in_place { for (i, l) in self.editing.iter().enumerate().rev() { let parent = i.checked_sub(1).and_then(|j| self.editing.get(j)); - let below = match parent { - None => self.doc.timeline(self.scene).clone(), - Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(), - }; + let below = edited(&self.doc, self.scene, self.editing.get(..i).unwrap_or_default()).clone(); let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); - tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, DIM)); + let around = without(below, l.instance); + let layer = placed(&mut doc, around.clone(), xf, l.frame, ColorEffect::opacity(DIM)); + // The timeline right under the open symbol is the one onion skin shows around it. + if front.parent.is_none() { + front.parent = Some(Around { layer: layer.id, timeline: around, frame: l.frame, at: xf, dim: DIM }); + } + tl.layers.push(layer); } } + let front = Arc::new(front); *doc.timeline_mut(self.scene) = tl; // Apart from document states (counted up from 1), and the same for the same picture. let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) }); @@ -211,17 +329,55 @@ impl Session { } } +impl Session { + /// The tint and opacity the stage draws the open button's hit area in (ADR 0057): while a + /// button is open and its playhead is on another frame than the one that answers the + /// pointer (the Hit frame, or Up when it has none), and [`Session::hit_area`] is set. + pub fn hit_overlay(&self) -> Option<(anicraft_doc::Rgba, f32)> { + let (tint, alpha) = self.hit_area?; + let sym = self.editing_symbol().and_then(|id| self.doc.symbol(id))?; + let frame = anicraft_doc::player::hit_frame(sym.timeline.frame_count()); + (sym.kind == SymbolKind::Button && self.frame != frame && alpha.is_finite() && alpha > 0.0).then_some((tint, alpha.min(1.0))) + } +} + +/// What answers the pointer on a button with timeline `tl`, as a timeline to draw (the hit test's +/// rules, `doc::player::hit_area`): mask layers go and what they masked is whole again, guide +/// layers are hidden (they still steer what follows them). +fn hit_timeline(tl: &Timeline) -> Timeline { + let masks: Vec = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask).map(|l| l.id).collect(); + let layers = tl + .layers + .iter() + .filter(|l| l.kind != LayerKind::Mask) + .map(|l| { + if l.kind != LayerKind::Guide && !l.parent.is_some_and(|p| masks.contains(&p)) { + return l.clone(); + } + let mut l = (**l).clone(); + if l.kind == LayerKind::Guide { + l.visible = false; + } + if l.parent.is_some_and(|p| masks.contains(&p)) { + l.parent = None; + } + Arc::new(l) + }) + .collect(); + Timeline { layers } +} + /// A layer holding `timeline` as a graphic symbol's instance at `transform`, showing its `frame` -/// at opacity `alpha` (a symbol added to `doc`, which is only drawn). -fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc { +/// with colour effect `color` (a symbol added to `doc`, which is only drawn). +fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, color: ColorEffect) -> Arc { let symbol = SymbolId(doc.alloc_id()); - doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, timeline })); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(Element { id: ElementId(doc.alloc_id()), name: String::new(), transform, - color: ColorEffect { alpha, ..ColorEffect::default() }, + color, kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, })); let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); @@ -229,6 +385,82 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, Arc::new(layer) } +impl Session { + /// Opens the drawing object `id` on `layer` in place (ADR 0080): it becomes a group of one + /// raw shape (its own, unmoved), which the level opens. The picture doesn't change, so this + /// is no undo step; [`Session::close_drawing`] turns it back. + fn open_drawing(&mut self, layer: LayerId, id: ElementId) -> Result<()> { + let inner = ElementId(self.doc.alloc_id()); + let inner_layer = LayerId(self.doc.alloc_id()); + let frame = self.frame; + let tl = edited_mut(&mut self.doc, self.scene, &self.editing)?; + let l = tl.layer_mut(layer).ok_or_else(|| EngineError::State("that drawing object's layer is gone".into()))?; + let k = l.keyframe_index_at(frame).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let kf = l.keyframe_mut(k).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let at = kf.elements.iter().position(|e| e.id == id).ok_or_else(|| EngineError::State("that drawing object is not on this keyframe".into()))?; + let Some(el) = kf.elements.get(at).cloned() else { return Err(EngineError::State("that drawing object is not on this keyframe".into())) }; + let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("that is not a drawing object".into())) }; + let shape = Element { id: inner, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(anicraft_doc::Shape { merge: true, ..sh.clone() }) }; + let group = Element { id, name: el.name.clone(), transform: el.transform, color: el.color, kind: ElementKind::group(inner_layer, vec![Arc::new(shape)]) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(group); + } + Ok(()) + } + + /// Closes a drawing object opened in place (level `l`, just taken off the stack): one shape + /// left inside is one drawing object again, exactly as it shows (its id, name and place); + /// nothing left, and it is gone; several, and they stay a group of raw shapes (what Combine + /// Objects' Union makes of shapes of several colours). Opening and closing it without an + /// edit leaves the document as it was, state and all. True when it is gone. + fn close_drawing(&mut self, l: &EditLevel) -> bool { + // Nothing changed since it was opened: the document goes back exactly as it was. + if let Some(back) = &l.back + && back.2 == self.state + { + self.doc = back.0.clone(); + self.state = back.1; + self.dl_cache.replace(None); + return false; + } + let Some((layer, id)) = l.instance else { return false }; + let below = self.editing.clone(); + let Ok(tl) = edited_mut(&mut self.doc, self.scene, &below) else { return false }; + let Some(lay) = tl.layer_mut(layer) else { return false }; + let Some(k) = lay.keyframe_index_at(l.frame) else { return false }; + let Some(kf) = lay.keyframe_mut(k) else { return false }; + let Some(at) = kf.elements.iter().position(|e| e.id == id) else { return false }; + let Some(group) = kf.elements.get(at).cloned() else { return false }; + let ElementKind::Group { members } = &group.kind else { return false }; + let inside: Vec> = members.layers.iter().filter_map(|m| m.keyframe_at(0)).flat_map(|k| k.elements.iter().cloned()).collect(); + let one_layer = members.layers.len() == 1; + let mut gone = false; + match inside.as_slice() { + [] if one_layer => { + kf.elements.remove(at); + gone = true; + } + [only] if one_layer => { + // Two colour effects only nest as one when one of them is none. + let color = match (group.color, only.color) { + (c, ColorEffect::None) | (ColorEffect::None, c) => Some(c), + _ => None, + }; + if let (ElementKind::Shape(sh), Some(color)) = (&only.kind, color) { + let object = Element { id, name: group.name.clone(), transform: group.transform.mul(&only.transform), color, kind: ElementKind::Shape(anicraft_doc::Shape { merge: false, ..sh.clone() }) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(object); + } + } + } + _ => {} + } + self.state = crate::history::fresh_state(); + self.dl_cache.replace(None); + gone + } +} + /// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym` /// is open, or uses an open one, however deep. pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { @@ -238,7 +470,7 @@ pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { let mut seen: Vec = Vec::new(); let mut todo = vec![sym]; while let Some(id) = todo.pop() { - if s.editing.iter().any(|l| l.symbol == id) { + if s.editing.iter().any(|l| l.symbol() == Some(id)) { return true; } if seen.contains(&id) || seen.len() > 100_000 { @@ -247,7 +479,7 @@ pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { seen.push(id); let Some(sym) = s.doc.symbol(id) else { continue }; for k in sym.timeline.layers.iter().flat_map(|l| l.keyframes.iter()) { - todo.extend(k.elements.iter().filter_map(|e| match e.kind { + todo.extend(anicraft_doc::expand_groups(&k.elements).iter().filter_map(|e| match e.kind { ElementKind::Symbol { symbol, .. } => Some(symbol), _ => None, })); @@ -269,12 +501,23 @@ fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline { tl } +/// Whether `symbol.edit` opens `e`: a symbol instance, a group or a drawing object. +pub fn opens(e: &Element) -> bool { + match &e.kind { + ElementKind::Symbol { .. } | ElementKind::Group { .. } => true, + // A warped shape (ADR 0079) keeps its outline as drawn under its mesh: it is edited + // through its pins, not opened. + ElementKind::Shape(sh) => !sh.merge && sh.warp.is_none(), + _ => false, + } +} + /// The instance `id` on a layer at the playhead of the timeline being edited, and its layer. fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc)> { s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e))) } -fn edit(s: &mut Session, p: &Value) -> Result { +pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { if s.editing.len() >= MAX_LEVELS { return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other"))); } @@ -284,17 +527,17 @@ fn edit(s: &mut Session, p: &Value) -> Result { if s.doc.symbol(symbol).is_none() { return Err(EngineError::State(format!("no symbol {sym} in the Library"))); } - if s.editing.iter().any(|l| l.symbol == symbol) { + if s.editing.iter().any(|l| l.symbol() == Some(symbol)) { return Err(EngineError::State("that symbol is open already".into())); } let c = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); - s.enter_level(symbol, None, Affine::translate(c.x, c.y), 0); + s.enter_level(Opened::Symbol(symbol), None, Affine::translate(c.x, c.y), 0); return Ok(editing_json(s)); } let id = match opt_u64(p, "id")? { Some(i) => ElementId(i), None => { - let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| matches!(e.kind, ElementKind::Symbol { .. }))).collect(); + let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| opens(&e))).collect(); match picked.as_slice() { [one] => *one, // Nothing to open: Ctrl+E goes back to the document, as in Animate. @@ -302,8 +545,8 @@ fn edit(s: &mut Session, p: &Value) -> Result { s.exit_all(); return Ok(editing_json(s)); } - [] => return Err(EngineError::State("select a symbol instance to edit it (or double-click it)".into())), - _ => return Err(EngineError::State("select one symbol instance to edit".into())), + [] => return Err(EngineError::State("select a symbol instance, a group or a drawing object to edit it (or double-click it)".into())), + _ => return Err(EngineError::State("select one symbol instance, group or drawing object to edit".into())), } } }; @@ -311,23 +554,46 @@ fn edit(s: &mut Session, p: &Value) -> Result { if !s.selectable(layer) { return Err(EngineError::State("that instance's layer is locked or hidden".into())); } - let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance".into())) }; + let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform); + // A group opens where it stands (ADR 0073): its members at their only frame. The level finds + // the keyframe it is on through the playhead below. + if matches!(el.kind, ElementKind::Group { .. }) { + s.enter_level(Opened::Group, Some((layer, id)), below.mul(&el.transform), 0); + return Ok(editing_json(s)); + } + // A drawing object opens the same way (ADR 0080), as a group of its one raw shape. + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge && sh.warp.is_some()) { + return Err(EngineError::State("that drawing object is warped (Asset Warp): edit it with its pins, or remove its warp to edit its outline".into())); + } + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge) { + if crate::cmds_group::open_groups(s) + 1 > anicraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::State(format!("groups nest at most {} deep", anicraft_doc::MAX_GROUP_DEPTH))); + } + let (was, state) = (s.doc.clone(), s.state); + s.open_drawing(layer, id)?; + s.state = crate::history::fresh_state(); + s.enter_level(Opened::Drawing, Some((layer, id)), below.mul(&el.transform), 0); + if let Some(l) = s.editing.last_mut() { + l.back = Some(Arc::new((was, state, s.state))); + } + return Ok(editing_json(s)); + } + let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance, a group or a drawing object".into())) }; let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?; - if s.editing.iter().any(|l| l.symbol == symbol) { + if s.editing.iter().any(|l| l.symbol() == Some(symbol)) { return Err(EngineError::State("that symbol is open already".into())); } // A graphic opens at the frame the instance shows; movie clips and buttons at their first. let len = sym.timeline.frame_count(); let start = s.timeline().layer(layer).and_then(|l| l.keyframe_at(s.frame)).map_or(s.frame, |k| k.start); let frame = if sym.kind == SymbolKind::Graphic { loop_mode.local_frame(s.frame.saturating_sub(start), first_frame, len) } else { 0 }; - let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform); - s.enter_level(symbol, Some((layer, id)), below.mul(&el.transform), frame); + s.enter_level(Opened::Symbol(symbol), Some((layer, id)), below.mul(&el.transform), frame); Ok(editing_json(s)) } fn exit(s: &mut Session, p: &Value) -> Result { if s.editing.is_empty() { - return Err(EngineError::State("no symbol is open for editing".into())); + return Err(EngineError::State("no symbol or group is open for editing".into())); } if opt_bool(p, "all")?.unwrap_or(false) { s.exit_all(); @@ -339,6 +605,20 @@ fn exit(s: &mut Session, p: &Value) -> Result { /// The open symbols, outermost first. pub(crate) fn editing_json(s: &Session) -> Value { - let list: Vec = s.editing.iter().map(|l| json!({"symbol": l.symbol.0, "name": s.doc.symbol(l.symbol).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)})).collect(); + let list: Vec = s + .editing + .iter() + .map(|l| match l.symbol() { + Some(id) => json!({"symbol": id.0, "name": s.doc.symbol(id).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)}), + None if l.open == Opened::Drawing => json!({"drawing": l.instance.map(|(_, e)| e.0), "name": "Drawing Object", "instance": l.instance.map(|(_, e)| e.0)}), + None => json!({"group": l.instance.map(|(_, e)| e.0), "name": "Group", "instance": l.instance.map(|(_, e)| e.0)}), + }) + .collect(); json!({"editing": list, "layer": s.layer.0, "frame": s.frame, "selected": s.selection.id_list()}) } + +/// Every colour of the hit area replaced by `tint`, the whole faded to `alpha` (ADR 0057): what +/// Animate's Advanced effect calls multipliers 0 % and offsets of the tint, alpha at `alpha`. +fn hit_tint(tint: anicraft_doc::Rgba, alpha: f32) -> anicraft_doc::ColorTransform { + anicraft_doc::ColorTransform { mul: [0.0, 0.0, 0.0, alpha], add: [tint.r, tint.g, tint.b, 0.0] } +} diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs index 18b6a459..4b38fa91 100644 --- a/crates/engine/src/editing_tests.rs +++ b/crates/engine/src/editing_tests.rs @@ -106,6 +106,59 @@ fn opening_from_the_library_and_guards() { assert!(s.editing.is_empty()); } +/// The sample's Play button open from the Library (at the stage's centre, 640 × 360): its face is +/// 220 × 80, its Hit frame 240 × 100. +fn open_button(hit: Option<(anicraft_doc::Rgba, f32)>) -> Session { + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap_or_else(|| panic!("a button")); + run(&mut s, "symbol.edit", json!({"symbol": id.0})); + s.hit_area = hit; + s +} + +#[test] +fn an_open_button_shows_its_hit_area_over_its_other_states() { + let red = anicraft_doc::Rgba::new(1.0, 0.0, 0.0, 1.0); + let render = |s: &Session| { + let pic = s.stage_picture(); + anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")) + }; + let plain = render(&open_button(None)); + let mut s = open_button(Some((red, 0.5))); + assert_eq!(s.hit_overlay(), Some((red, 0.5)), "on the Up frame"); + let shown = render(&s); + let px = |p: &anicraft_render::Pixmap, x: u32, y: u32| p.pixel(x, y).unwrap_or_else(|| panic!("({x}, {y}) in the picture")); + // Inside the Hit frame but outside the face (x = 640 + 115): the background, half red now. + let (bg, over) = (px(&plain, 755, 360), px(&shown, 755, 360)); + for c in 0..3 { + let want = bg[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "channel {c}: {over:?} vs {want} (background {bg:?})"); + } + // Over the face (blue) and its arrow (white) alike: half red over what the state shows. + for (x, y) in [(600, 360), (640, 360)] { + let (art, over) = (px(&plain, x, y), px(&shown, x, y)); + for c in 0..3 { + let want = art[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "({x}, {y}) channel {c}: {over:?} vs {want}"); + } + } + // Outside the Hit frame: untouched. + assert_eq!(px(&shown, 775, 360), px(&plain, 775, 360)); + // On the Hit frame itself, nothing over it; it isn't in the document either. + s.set_frame(3); + assert_eq!(s.hit_overlay(), None); + let on_hit = render(&s); + s.hit_area = None; + assert_eq!(on_hit.to_rgba8(), render(&s).to_rgba8()); + assert_eq!(s.doc.library.len(), anicraft_doc::sample::interactive().library.len()); + // Only buttons: a movie clip open shows none. + let mut s = Session::new(anicraft_doc::sample::interactive()); + let clip = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::MovieClip).map(|x| x.id).unwrap_or_else(|| panic!("a clip")); + run(&mut s, "symbol.edit", json!({"symbol": clip.0})); + s.hit_area = Some((red, 0.5)); + assert_eq!(s.hit_overlay(), None); +} + #[test] fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { let (mut s, _, _) = boxed(); diff --git a/crates/engine/src/explorer.rs b/crates/engine/src/explorer.rs new file mode 100644 index 00000000..55c2431b --- /dev/null +++ b/crates/engine/src/explorer.rs @@ -0,0 +1,527 @@ +//! The Movie Explorer (ADR 0058), as Animate's: the movie as a tree of scenes › layers › +//! keyframes › what is on them (symbol instances, text, bitmaps, sounds, frame scripts and +//! instance actions), each instance opening into its symbol's own layers, and the Library's +//! symbol definitions. Show filters hide kinds of rows; a text filter keeps the rows whose names +//! hold it, with the rows above them. +//! +//! [`tree`] gives the rows that are showing, in order, each with its depth, so a list can draw +//! only the rows in view. Only open rows' children are made, so the work follows what is shown, +//! and it stops at [`MAX_ROWS`] and [`MAX_DEPTH`]. Every row says where it is as `find.goto` +//! params, which is how a double-click jumps there. + +use crate::find::{Scope, Step}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Document, ElementId, ElementKind, FrameScript, Keyframe, LayerId, LayerKind, Paint, Symbol, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![c( + "explorer.tree", + "Movie Explorer", + "", + None, + "{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}", + false, + tree_cmd as crate::RunFn, + )] +} + +/// Most rows one tree makes. +pub const MAX_ROWS: usize = 200_000; +/// Deepest row (instances inside instances). +pub const MAX_DEPTH: usize = 48; +const DEFAULT_LIMIT: usize = 1_000; +const MAX_LIMIT: usize = 10_000; + +/// What a row is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NodeKind { + Scene, + /// The Library's symbols, under one row. + Definitions, + /// A symbol in the Library. + Symbol(SymbolKind), + Layer(LayerKind), + /// A keyframe (its name is its label). + Frame, + /// A keyframe's script or actions. + Script, + /// A button or movie clip instance's actions for one event. + Handler, + Sound, + Instance(SymbolKind), + Text, + Bitmap, +} + +impl NodeKind { + pub fn key(self) -> &'static str { + match self { + NodeKind::Scene => "scene", + NodeKind::Definitions => "definitions", + NodeKind::Symbol(_) => "symbol", + NodeKind::Layer(_) => "layer", + NodeKind::Frame => "frame", + NodeKind::Script => "script", + NodeKind::Handler => "handler", + NodeKind::Sound => "sound", + NodeKind::Instance(_) => "instance", + NodeKind::Text => "text", + NodeKind::Bitmap => "bitmap", + } + } +} + +/// Which kinds of rows show (Animate's Show buttons). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Show { + /// Text fields. + pub text: bool, + /// Buttons, movie clips and graphics. + pub symbols: bool, + /// Frame scripts and instance actions. + pub scripts: bool, + /// Sounds and bitmaps. + pub media: bool, + /// Layers and keyframes; off, what is on them is listed straight under the scene or symbol. + pub frames: bool, +} + +impl Default for Show { + fn default() -> Self { + Show { text: true, symbols: true, scripts: true, media: true, frames: true } + } +} + +/// What the tree shows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Options { + pub scope: Scope, + pub show: Show, + pub definitions: bool, + /// Open rows, by key. `None`: only the top rows. + pub expanded: Option>, + /// Every row open. + pub all: bool, + pub filter: String, +} + +impl Default for Options { + fn default() -> Self { + Options { scope: Scope::Document, show: Show::default(), definitions: true, expanded: None, all: false, filter: String::new() } + } +} + +/// Where a row is, as `find.goto` params. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Go { + pub scene: Option, + /// The symbol opened alone (from the Library), or to open. + pub symbol: Option, + /// Instances opened in place from the scene or the symbol. + pub path: Vec, + pub layer: Option, + pub frame: Option, + pub element: Option, +} + +impl Go { + pub fn to_json(&self) -> Value { + let mut v = json!({}); + if let Some(s) = self.scene { + v["scene"] = json!(s); + } + if let Some(s) = self.symbol { + v["symbol"] = json!(s.0); + } + if !self.path.is_empty() { + v["path"] = Value::Array(self.path.iter().map(Step::to_json).collect()); + } + if let Some(l) = self.layer { + v["layer"] = json!(l.0); + } + if let Some(f) = self.frame { + v["frame"] = json!(f); + } + if let Some(e) = self.element { + v["element"] = json!(e.0); + } + v + } +} + +/// One row of the tree. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + /// Stable while the document keeps its ids: what `expanded` names. + pub key: String, + pub depth: usize, + pub kind: NodeKind, + /// Document text: a scene, layer, symbol or sound name, a frame label, a text field's first + /// line, an instance's symbol, a script's summary. + pub name: String, + /// More document text: an instance's name, a text field's font and size. + pub extra: String, + /// The keyframe's first frame (keyframes and what is on them). + pub frame: Option, + pub children: bool, + pub open: bool, + pub go: Go, +} + +impl Row { + pub fn to_json(&self) -> Value { + let mut v = json!({"key": self.key, "depth": self.depth, "kind": self.kind.key(), "name": self.name, "extra": self.extra, "frame": self.frame, "children": self.children, "open": self.open, "go": self.go.to_json()}); + match self.kind { + NodeKind::Symbol(k) | NodeKind::Instance(k) => v["type"] = json!(crate::cmds_library::kind_key(k)), + NodeKind::Layer(k) => v["type"] = json!(format!("{k:?}").to_lowercase()), + _ => {} + } + v + } +} + +/// The tree's rows and whether it stopped at [`MAX_ROWS`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Tree { + pub rows: Vec, + pub truncated: bool, +} + +struct Walk<'a> { + doc: &'a Document, + syms: HashMap, + o: &'a Options, + /// Everything is open (all, or a filter is looking through it all). + every: bool, + rows: Vec, + truncated: bool, +} + +/// The first line of `t`, at most 80 characters. +fn line(t: &str) -> String { + let first = t.lines().next().unwrap_or("").trim(); + let mut out: String = first.chars().take(80).collect(); + if out.len() < first.len() || t.trim().lines().nth(1).is_some() { + out.push('…'); + } + out +} + +impl<'a> Walk<'a> { + fn open(&self, key: &str, depth: usize) -> bool { + self.every || self.o.expanded.as_ref().map_or(depth == 0, |e| e.contains(key)) + } + + /// Adds a row; false once the tree is full. + fn push(&mut self, row: Row) -> bool { + if self.rows.len() >= MAX_ROWS { + self.truncated = true; + return false; + } + self.rows.push(row); + true + } + + fn full(&self) -> bool { + self.truncated + } + + /// Whether a keyframe shows anything (with the frames shown, a labelled keyframe does too). + fn frame_items(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) + || (s.media && k.sound.is_some()) + || anicraft_doc::expand_groups(&k.elements).iter().any(|e| match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera | ElementKind::Group { .. } => false, + }) + || (s.frames && !k.label.is_empty()) + } + + fn has_items(&self, tl: &Timeline) -> bool { + tl.layers.iter().any(|l| self.o.show.frames || l.keyframes.iter().any(|k| self.frame_items(k))) + } + + /// The rows of timeline `tl` under `key`, at `depth`. `go` is where the timeline is (scene or + /// symbol, and the instances opened to reach it); `stack` the symbols it is inside. + fn timeline(&mut self, tl: &Timeline, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + if depth > MAX_DEPTH { + return; + } + let mut skip_to = 0usize; + for (i, l) in tl.layers.iter().enumerate() { + if self.full() { + return; + } + if i < skip_to { + continue; + } + let lkey = format!("{key}/l{}", l.id.0); + let lgo = Go { layer: Some(l.id), ..go.clone() }; + if self.o.show.frames { + let d = depth + tl.depth(i).min(MAX_DEPTH); + let folder = l.kind == LayerKind::Folder; + let children = if folder { tl.group_range(i).len() > 1 } else { l.keyframes.iter().any(|k| self.frame_items(k)) }; + let open = children && self.open(&lkey, d); + if !self.push(Row { key: lkey.clone(), depth: d, kind: NodeKind::Layer(l.kind), name: l.name.clone(), extra: String::new(), frame: None, children, open, go: lgo.clone() }) { + return; + } + if folder { + if !open { + skip_to = tl.group_range(i).end; + } + continue; + } + if !open { + continue; + } + for k in &l.keyframes { + if !self.frame_items(k) { + continue; + } + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + let children = self.keyframe_has(k); + let open = children && self.open(&kkey, d + 1); + if !self.push(Row { key: kkey.clone(), depth: d + 1, kind: NodeKind::Frame, name: k.label.clone(), extra: String::new(), frame: Some(k.start), children, open, go: kgo.clone() }) { + return; + } + if open { + self.keyframe(k, &kkey, d + 2, &kgo, stack); + } + } + } else { + for k in &l.keyframes { + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + self.keyframe(k, &kkey, depth, &kgo, stack); + } + } + } + } + + /// Whether a keyframe row has children (its label alone makes the row, not children). + fn keyframe_has(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) || (s.media && k.sound.is_some()) || anicraft_doc::expand_groups(&k.elements).iter().any(|e| self.element_shows(e)) + } + + fn element_shows(&self, e: &anicraft_doc::Element) -> bool { + let s = self.o.show; + match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera | ElementKind::Group { .. } => false, + } + } + + /// What is on keyframe `k`: its script, its sound, then its elements. + fn keyframe(&mut self, k: &Keyframe, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + let s = self.o.show; + let leaf = |key: String, kind: NodeKind, name: String, extra: String, go: Go| Row { key, depth, kind, name, extra, frame: Some(k.start), children: false, open: false, go }; + if s.scripts + && let Some(script) = &k.script + { + let name = match script { + FrameScript::Source(src) => line(&src.text), + other => line(&other.describe()), + }; + if !self.push(leaf(format!("{key}/x"), NodeKind::Script, name, String::new(), go.clone())) { + return; + } + } + if s.media + && let Some(fs) = &k.sound + { + let name = self.doc.sound(fs.sound).map(|x| x.name.clone()).unwrap_or_default(); + if !self.push(leaf(format!("{key}/a"), NodeKind::Sound, name, fs.sync.key().to_string(), go.clone())) { + return; + } + } + // What is inside a group is listed as on its keyframe (ADR 0073). + for e in anicraft_doc::expand_groups(&k.elements).iter() { + if self.full() || !self.element_shows(e) { + continue; + } + let ekey = format!("{key}/e{}", e.id.0); + let ego = Go { element: Some(e.id), ..go.clone() }; + match &e.kind { + ElementKind::Symbol { symbol, events, .. } => { + let sym = self.syms.get(symbol).copied(); + let nested = sym.filter(|_| !stack.contains(symbol) && stack.len() < MAX_DEPTH); + let children = (s.scripts && !events.is_empty()) || nested.is_some_and(|sym| self.has_items(&sym.timeline)); + let open = children && self.open(&ekey, depth); + let row = Row { + key: ekey.clone(), + depth, + kind: NodeKind::Instance(sym.map_or(SymbolKind::Graphic, |x| x.kind)), + name: sym.map_or_else(String::new, |x| x.name.clone()), + extra: e.name.clone(), + frame: Some(k.start), + children, + open, + go: ego.clone(), + }; + if !self.push(row) || !open { + continue; + } + if s.scripts { + for (n, h) in events.iter().enumerate() { + let desc = h.actions.iter().map(anicraft_doc::Action::describe).collect::>().join("; "); + if !self.push(Row { key: format!("{ekey}/h{n}"), depth: depth + 1, kind: NodeKind::Handler, name: h.event.key().to_string(), extra: line(&desc), frame: Some(k.start), children: false, open: false, go: ego.clone() }) { + return; + } + } + } + if let Some(sym) = nested { + // Inside: the symbol's own timeline, reached by opening this instance. + let (Some(layer), Some(frame)) = (go.layer, go.frame) else { continue }; + let mut inner = Go { scene: go.scene, symbol: go.symbol, path: go.path.clone(), layer: None, frame: None, element: None }; + inner.path.push(Step { layer, frame, element: e.id }); + let mut st = stack.to_vec(); + st.push(*symbol); + self.timeline(&sym.timeline, &ekey, depth + 1, &inner, &st); + } + } + ElementKind::Text(t) => { + if !self.push(leaf(ekey, NodeKind::Text, line(&t.text), format!("{} {}", t.font, t.size), ego)) { + return; + } + } + ElementKind::Shape(sh) => { + let name = match &sh.fill { + Some(Paint::Bitmap { bitmap, .. }) => self.doc.bitmap(*bitmap).map(|b| b.name.clone()).unwrap_or_default(), + _ => String::new(), + }; + if !self.push(leaf(ekey, NodeKind::Bitmap, name, e.name.clone(), ego)) { + return; + } + } + ElementKind::Camera | ElementKind::Group { .. } => {} + } + } + } +} + +/// The rows showing for `o`, from scene `scene` (the scope's scene). +pub fn tree(doc: &Document, scene: usize, o: &Options) -> Tree { + let filter = o.filter.trim().to_lowercase(); + let mut w = Walk { doc, syms: doc.library.iter().map(|s| (s.id, &**s)).collect(), o, every: o.all || !filter.is_empty(), rows: Vec::new(), truncated: false }; + let scenes: Vec = match o.scope { + Scope::Document => (0..doc.scenes.len()).collect(), + Scope::Scene => vec![scene.min(doc.scenes.len().saturating_sub(1))], + }; + for i in scenes { + let Some(sc) = doc.scenes.get(i) else { continue }; + let key = format!("s{i}"); + let children = w.has_items(&sc.timeline); + let open = children && w.open(&key, 0); + let go = Go { scene: Some(i), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 0, kind: NodeKind::Scene, name: sc.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sc.timeline, &key, 1, &go, &[]); + } + } + if o.definitions && !doc.library.is_empty() && !w.full() { + let open = w.open("d", 0); + w.push(Row { key: "d".into(), depth: 0, kind: NodeKind::Definitions, name: String::new(), extra: String::new(), frame: None, children: true, open, go: Go::default() }); + if open { + for sym in &doc.library { + let key = format!("d/y{}", sym.id.0); + let children = w.has_items(&sym.timeline); + let open = children && w.open(&key, 1); + let go = Go { symbol: Some(sym.id), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 1, kind: NodeKind::Symbol(sym.kind), name: sym.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sym.timeline, &key, 2, &go, &[sym.id]); + } + } + } + } + let Walk { mut rows, truncated, .. } = w; + if !filter.is_empty() { + rows = filtered(rows, &filter); + } + Tree { rows, truncated } +} + +/// The rows whose name or extra text holds `needle` (lower case), with every row above them. +fn filtered(rows: Vec, needle: &str) -> Vec { + let hit = |r: &Row| r.name.to_lowercase().contains(needle) || r.extra.to_lowercase().contains(needle); + let mut keep = vec![false; rows.len()]; + // The nearest row above at each depth. + let mut above: Vec = Vec::new(); + for (i, r) in rows.iter().enumerate() { + above.truncate(r.depth); + if hit(r) { + if let Some(k) = keep.get_mut(i) { + *k = true; + } + for &a in &above { + if let Some(k) = keep.get_mut(a) { + *k = true; + } + } + } + // (Depths can skip, inside folders: keep the stack's indices in order.) + while above.len() < r.depth { + above.push(above.last().copied().unwrap_or(i)); + } + above.push(i); + } + rows.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect() +} + +fn opt_flag(v: &Value, key: &str) -> Result { + Ok(opt_bool(v, key)?.unwrap_or(true)) +} + +/// The options in `p` (`explorer.tree`'s params). +pub fn options_of(p: &Value) -> Result { + let scope = match opt_str(p, "scope")? { + None | Some("document") => Scope::Document, + Some("scene") => Scope::Scene, + Some(o) => return Err(EngineError::Param(format!("'scope' is document or scene, not '{o}'"))), + }; + let show = match p.get("show") { + None | Some(Value::Null) => Show::default(), + Some(v) if v.is_object() => Show { text: opt_flag(v, "text")?, symbols: opt_flag(v, "symbols")?, scripts: opt_flag(v, "scripts")?, media: opt_flag(v, "media")?, frames: opt_flag(v, "frames")? }, + Some(_) => return Err(EngineError::Param("'show' must be {text?, symbols?, scripts?, media?, frames?}".into())), + }; + let expanded = match p.get("expanded") { + None | Some(Value::Null) => None, + Some(Value::Array(list)) => { + if list.len() > MAX_ROWS { + return Err(EngineError::Param(format!("'expanded' names at most {MAX_ROWS} rows"))); + } + Some(list.iter().map(|v| v.as_str().map(str::to_string).ok_or_else(|| EngineError::Param("'expanded' must be a list of row keys".into()))).collect::>>()?) + } + Some(_) => return Err(EngineError::Param("'expanded' must be a list of row keys".into())), + }; + let filter: String = opt_str(p, "filter")?.unwrap_or("").chars().take(256).collect(); + Ok(Options { scope, show, definitions: opt_bool(p, "definitions")?.unwrap_or(true), expanded, all: opt_bool(p, "all")?.unwrap_or(false), filter }) +} + +fn tree_cmd(s: &mut Session, p: &Value) -> Result { + let o = options_of(p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let t = tree(&s.doc, s.scene, &o); + let rows: Vec = t.rows.iter().skip(offset).take(limit).map(Row::to_json).collect(); + Ok(json!({"rows": rows, "total": t.rows.len(), "offset": offset, "truncated": t.truncated})) +} + +#[cfg(test)] +#[path = "explorer_tests.rs"] +mod tests; diff --git a/crates/engine/src/explorer_tests.rs b/crates/engine/src/explorer_tests.rs new file mode 100644 index 00000000..49f08566 --- /dev/null +++ b/crates/engine/src/explorer_tests.rs @@ -0,0 +1,205 @@ +//! The Movie Explorer's tree (ADR 0058): its shape for scenes and nested symbols, open rows, +//! the show filters and the text filter, folders, symbols that hold themselves, paging, jumping +//! to a row, and a large document. + +use super::*; +use crate::find::tests::{Build, movie}; +use anicraft_doc::{LayerKind, Paint, Rgba, SymbolKind}; +use serde_json::json; + +fn keys_of(t: &Tree) -> Vec<(usize, NodeKind, String)> { + t.rows.iter().map(|r| (r.depth, r.kind, r.name.clone())).collect() +} + +fn all() -> Options { + Options { all: true, ..Options::default() } +} + +#[test] +fn the_top_rows_show_scenes_their_layers_and_the_library() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options::default()); + let names: Vec<(usize, &str)> = t.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "Actions"), (1, "Art"), (0, "Scene 2"), (1, "Back"), (0, ""), (1, "Outer"), (1, "Inner"), (1, "Unused")]); + assert!(t.rows[1].children && !t.rows[1].open); + // Scene 2's only layer holds a plain shape: nothing to list under it. + assert!(!t.rows[4].children); + assert_eq!(t.rows[5].kind, NodeKind::Definitions); + assert_eq!(t.rows[6].kind, NodeKind::Symbol(SymbolKind::MovieClip)); + // Scope: one scene. + let one = tree(&s.doc, 1, &Options { scope: Scope::Scene, definitions: false, ..Options::default() }); + assert_eq!(one.rows.iter().map(|r| r.name.as_str()).collect::>(), ["Scene 2", "Back"]); +} + +#[test] +fn instances_open_into_their_symbols_layers_however_deep() { + let (s, outer, inner, _) = movie(); + let t = tree(&s.doc, 0, &all()); + let scene1: Vec<(usize, NodeKind, String)> = keys_of(&t).into_iter().take_while(|r| r.2 != "Scene 2").collect(); + let want = [ + (0, NodeKind::Scene, "Scene 1"), + (1, NodeKind::Layer(LayerKind::Normal), "Actions"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Script, "stop(); // say hello"), + (1, NodeKind::Layer(LayerKind::Normal), "Art"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Text, "Hello world"), + (3, NodeKind::Instance(SymbolKind::MovieClip), "Outer"), + (4, NodeKind::Layer(LayerKind::Normal), "Outer art"), + (5, NodeKind::Frame, ""), + (6, NodeKind::Instance(SymbolKind::Graphic), "Inner"), + (7, NodeKind::Layer(LayerKind::Normal), "Inner art"), + (8, NodeKind::Frame, ""), + (9, NodeKind::Text, "Hello inside"), + (2, NodeKind::Frame, "intro hello"), + (3, NodeKind::Text, "hello hello again"), + ]; + let want: Vec<(usize, NodeKind, String)> = want.iter().map(|(d, k, n)| (*d, *k, n.to_string())).collect(); + assert_eq!(scene1, want); + // The instance row names the instance too, and its frame. + let hero = t.rows.iter().find(|r| r.extra == "hero").unwrap(); + assert_eq!((hero.frame, hero.children, hero.open), (Some(0), true, true)); + // The deepest text: reached by opening hero, then wheel, in place. + let deep = t.rows.iter().find(|r| r.depth == 9).unwrap(); + assert_eq!(deep.go.path.len(), 2); + assert_eq!(deep.go.scene, Some(0)); + let mut s = s; + let v = s.execute("find.goto", &deep.go.to_json()).unwrap(); + assert_eq!(s.editing.iter().map(|l| l.symbol().unwrap_or(SymbolId(0))).collect::>(), [outer, inner], "{v}"); + assert_eq!(s.selection.id_list(), [deep.go.element.unwrap().0]); + // Under the Library's Outer: its own layers, then Inner inside it. + let defs: Vec<(usize, String)> = t.rows.iter().skip_while(|r| r.kind != NodeKind::Definitions).map(|r| (r.depth, r.name.clone())).take(8).collect(); + assert_eq!(defs, [(0, String::new()), (1, "Outer".into()), (2, "Outer art".into()), (3, String::new()), (4, "Inner".into()), (5, "Inner art".into()), (6, String::new()), (7, "Hello inside".into())]); + // Keys are unique, so open rows can be remembered. + let mut keys: Vec<&str> = t.rows.iter().map(|r| r.key.as_str()).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), t.rows.len()); +} + +#[test] +fn only_open_rows_show_their_children() { + let (s, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + let t = tree(&s.doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{art}")].into()), definitions: false, ..Options::default() }); + let names: Vec<&str> = t.rows.iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, ["Scene 1", "Actions", "Art", "", "intro hello", "Scene 2"]); + assert!(t.rows[3].children && !t.rows[3].open); +} + +#[test] +fn show_filters_hide_kinds_and_frames_off_lists_items_straight_under_the_scene() { + let (s, ..) = movie(); + let no_symbols = tree(&s.doc, 0, &Options { show: Show { symbols: false, ..Show::default() }, definitions: false, ..all() }); + assert!(no_symbols.rows.iter().all(|r| !matches!(r.kind, NodeKind::Instance(_)))); + assert!(!no_symbols.rows.iter().any(|r| r.name == "Hello inside")); + let flat = tree(&s.doc, 0, &Options { show: Show { frames: false, ..Show::default() }, definitions: false, scope: Scope::Scene, ..all() }); + let names: Vec<(usize, &str)> = flat.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "stop(); // say hello"), (1, "Hello world"), (1, "Outer"), (2, "Inner"), (3, "Hello inside"), (1, "hello hello again")]); + let no_scripts = tree(&s.doc, 0, &Options { show: Show { scripts: false, ..Show::default() }, ..all() }); + assert!(no_scripts.rows.iter().all(|r| r.kind != NodeKind::Script && r.name != "Actions" || !r.children)); +} + +#[test] +fn the_text_filter_keeps_matches_and_the_rows_above_them() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options { filter: "INSIDE".into(), ..Options::default() }); + let texts = t.rows.iter().filter(|r| r.kind == NodeKind::Text).count(); + assert_eq!(texts, 3, "{:?}", keys_of(&t)); + // Each row is a match or above one: its next row is deeper, or it matches. + for (i, r) in t.rows.iter().enumerate() { + let matches = r.name.to_lowercase().contains("inside"); + let parent = t.rows.get(i + 1).is_some_and(|n| n.depth > r.depth); + assert!(matches || parent, "{r:?}"); + } + assert!(tree(&s.doc, 0, &Options { filter: "zebra".into(), ..Options::default() }).rows.is_empty()); + // The instance name counts too. + assert!(tree(&s.doc, 0, &Options { filter: "wheel".into(), ..Options::default() }).rows.iter().any(|r| r.extra == "wheel")); +} + +#[test] +fn closed_folders_hide_the_layers_in_them() { + let mut b = Build::new(); + let t1 = b.text("one", Rgba::BLACK); + let t2 = b.text("two", Rgba::BLACK); + let mut folder = b.layer("Folder", vec![(0, 1, "", vec![])]); + folder.kind = LayerKind::Folder; + let mut a = b.layer("A", vec![(0, 1, "", vec![t1])]); + a.parent = Some(folder.id); + let c = b.layer("C", vec![(0, 1, "", vec![t2])]); + let fid = folder.id.0; + b.scene("S", vec![folder, a, c]); + let doc = crate::Session::new(b.doc).doc; + let closed = tree(&doc, 0, &Options { expanded: Some(["s0".to_string()].into()), ..Options::default() }); + assert_eq!(closed.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (1, "C")]); + let open = tree(&doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{fid}")].into()), ..Options::default() }); + assert_eq!(open.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (2, "A"), (1, "C")]); +} + +#[test] +fn symbols_that_hold_themselves_stop() { + let mut b = Build::new(); + let a = b.symbol("A", SymbolKind::Graphic); + let c = b.symbol("B", SymbolKind::Graphic); + let (ia, ib, self_a) = (b.instance(c, ""), b.instance(a, ""), b.instance(a, "me")); + let l = b.layer("in A", vec![(0, 1, "", vec![ia, self_a])]); + b.fill(a, vec![l]); + let l = b.layer("in B", vec![(0, 1, "", vec![ib])]); + b.fill(c, vec![l]); + let top = b.instance(a, ""); + let l = b.layer("L", vec![(0, 1, "", vec![top])]); + b.scene("S", vec![l]); + let t = tree(&b.doc, 0, &all()); + assert!(t.rows.len() < 40 && !t.truncated, "{}", t.rows.len()); + assert!(t.rows.iter().all(|r| r.depth <= MAX_DEPTH)); +} + +#[test] +fn the_command_pages_rows_with_where_each_goes() { + let (mut s, ..) = movie(); + let v = s.execute("explorer.tree", &json!({"all": true, "offset": 2, "limit": 3})).unwrap(); + assert_eq!(v["rows"].as_array().map(Vec::len), Some(3)); + assert!(v["total"].as_u64().unwrap() > 20); + let r = &v["rows"][1]; + assert_eq!((r["kind"].as_str(), r["depth"].as_u64(), r["name"].as_str()), (Some("script"), Some(3), Some("stop(); // say hello"))); + assert_eq!(r["go"]["frame"], 0); + let v = s.execute("explorer.tree", &json!({"all": true, "show": {"text": false, "scripts": false, "media": false, "frames": false}, "definitions": false})).unwrap(); + let kinds: Vec<&str> = v["rows"].as_array().unwrap().iter().map(|r| r["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["scene", "instance", "instance", "scene"]); + assert_eq!(v["rows"][1]["type"], "movie_clip"); + assert!(s.execute("explorer.tree", &json!({"scope": "galaxy"})).is_err()); + assert!(s.execute("explorer.tree", &json!({"expanded": [1]})).is_err()); +} + +#[test] +fn a_large_movie_makes_its_tree_quickly() { + // 100 layers × 120 keyframes, each with a text and an instance of a symbol of 3 layers. + let mut b = Build::new(); + let sym = b.symbol("Prop", SymbolKind::MovieClip); + let inner: Vec<_> = (0..3).map(|i| { + let r = b.rect(Paint::Solid(Rgba::BLACK), None); + let t = b.text("label", Rgba::BLACK); + b.layer(&format!("p{i}"), vec![(0, 1, "", vec![r, t])]) + }).collect(); + b.fill(sym, inner); + let mut layers = Vec::new(); + for li in 0..100 { + let keys: Vec<_> = (0..120).map(|k| (k, 1, "", vec![b.text(&format!("t {li} {k}"), Rgba::BLACK), b.instance(sym, "")])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + let doc = b.doc; + let t0 = std::time::Instant::now(); + let open = tree(&doc, 0, &all()); + let every = t0.elapsed(); + let t0 = std::time::Instant::now(); + let top = tree(&doc, 0, &Options::default()); + let closed = t0.elapsed(); + let t0 = std::time::Instant::now(); + let found = tree(&doc, 0, &Options { filter: "t 99 119".into(), ..Options::default() }); + let filtered = t0.elapsed(); + println!("Movie Explorer on 24,000 elements: everything open {every:?} ({} rows), top rows {closed:?} ({} rows), filtered {filtered:?} ({} rows)", open.rows.len(), top.rows.len(), found.rows.len()); + assert!(open.rows.len() > 100_000 && !open.truncated); + assert_eq!(found.rows.iter().filter(|r| r.kind == NodeKind::Text).count(), 1); + assert!(every.as_secs_f64() < 3.0 && closed.as_secs_f64() < 0.5); +} diff --git a/crates/engine/src/eyedropper_tests.rs b/crates/engine/src/eyedropper_tests.rs index 18efa673..7b99125b 100644 --- a/crates/engine/src/eyedropper_tests.rs +++ b/crates/engine/src/eyedropper_tests.rs @@ -26,7 +26,7 @@ fn rect(s: &mut Session, x: f32, fill: &str) -> u64 { /// A linear gradient across the shape's own width (local space: the shape is centred on 0). fn gradient() -> Paint { - Paint::Linear { start: Vec2::new(-50.0, 0.0), end: Vec2::new(50.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }] } + Paint::linear(Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }]) } #[test] diff --git a/crates/engine/src/find.rs b/crates/engine/src/find.rs new file mode 100644 index 00000000..ce601a20 --- /dev/null +++ b/crates/engine/src/find.rs @@ -0,0 +1,1120 @@ +//! Find and Replace (ADR 0058), as Animate's Edit › Find and Replace: text (in text fields, +//! frame labels, layer names, instance names and frame scripts), fonts, colours, symbols, sounds +//! and bitmaps, in the current scene (and the symbols it uses) or the whole document. +//! +//! `find.search` lists located hits; `find.replace` replaces one hit or all of them as one undo +//! step (asking first above [`REPLACE_ASK`] places, ADR 0004); `find.goto` jumps to a place: the +//! scene or symbol (opened in place through the instances that lead to it, ADR 0045), the layer, +//! the keyframe and the element, selected. The Movie Explorer (`explorer.tree`) navigates through +//! `find.goto` too. +//! +//! Text is matched with the `regex` crate, whose engine runs in time linear in the text and +//! refuses patterns that would compile too large, so no pattern can hang the editor. Plain text, +//! whole words and case are the same engine with an escaped pattern. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; +use anicraft_doc::{BitmapId, Document, ElementId, ElementKind, FrameScript, LayerId, Paint, Rgba, SoundId, SourceScript, Symbol, SymbolId, Timeline}; +use regex::{Regex, RegexBuilder}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "find.search", + "Find and Replace", + "Edit", + Some("Ctrl+F"), + "{kind: text | font | color | symbol | sound | bitmap, text? (kind text: what to find), match_case?, whole_word?, regex? (a pattern; linear-time engine, size-limited), font? (family), color? (#rrggbb; alpha is ignored), symbol? | sound? | bitmap?: library id, in?: [text, labels, layers, instances, scripts] (kind text) | [fills, strokes, text] (kind color) (default: all), scope?: scene (the current scene and the symbols it uses; default) | document, offset?, limit? (default 500, at most 10000)} → {hits: [{kind, field, scene | symbol, layer, layer_name, frame (keyframe start; null on a layer name), element?, start, end (characters, text only), found, context}], total, truncated}", + false, + search_cmd as crate::RunFn, + ), + c( + "find.replace", + "Replace", + "", + None, + "{the find.search query, with: text (kind text; $1 and ${name} insert groups when regex) | family (font) | #rrggbb (color; each place keeps its alpha) | library id (symbol, sound, bitmap), at?: one hit as find.search returned it (Replace); without `at`, every hit (Replace All, one undo step; asks first above 100 places)} → {replaced, skipped, notes}", + true, + replace_cmd, + ), + c( + "find.goto", + "Go to Found Item", + "", + None, + "{layer?: id (its scene or symbol is found), scene?: index, symbol?: id, path?: [{layer, frame, element}] (instances to open in place from `scene`, or from `symbol` opened alone), frame?, element?} goes there: closes open symbols, switches scene or opens the symbol (in place through an instance that uses it when there is one), picks the layer and frame and selects the element", + false, + goto_cmd, + ), + ] +} + +/// Longest text to find (characters). +pub const MAX_QUERY_CHARS: usize = 1_000; +/// Most hits one search keeps. +pub const MAX_HITS: usize = 100_000; +/// Replace All asks first when it would change more places than this (ADR 0004). +pub const REPLACE_ASK: usize = 100; +/// Most a compiled pattern may take (bytes), and its lazy DFA. +const REGEX_LIMIT: usize = 1 << 20; +const DEFAULT_LIMIT: usize = 500; +const MAX_LIMIT: usize = 10_000; +/// Characters of context shown on each side of a text match. +const CONTEXT: usize = 32; +/// Most instances opened in place to reach a symbol (`editing`'s limit). +const MAX_ROUTE: usize = 32; + +/// What is searched for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Text, + Font, + Color, + Symbol, + Sound, + Bitmap, +} + +impl Kind { + pub const ALL: [Kind; 6] = [Kind::Text, Kind::Font, Kind::Color, Kind::Symbol, Kind::Sound, Kind::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Kind::Text => "text", + Kind::Font => "font", + Kind::Color => "color", + Kind::Symbol => "symbol", + Kind::Sound => "sound", + Kind::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.key() == s || (s == "colour" && *k == Kind::Color)) + } +} + +/// Where a search looks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Scope { + /// The current scene, and every symbol it uses (however deep). + #[default] + Scene, + /// Every scene and every symbol in the Library, used or not. + Document, +} + +/// A timeline of the document: a scene's, or a Library symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Where { + Scene(usize), + Symbol(SymbolId), +} + +/// The part of the document a hit is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Field { + /// A text field's text. + Text, + /// A keyframe's label. + Label, + LayerName, + /// An element's instance name. + InstanceName, + /// A keyframe's script source. + Script, + /// A text field's font. + Font, + /// A shape's fill (solid or a gradient stop), stroke, or a text field's colour. + Fill, + Stroke, + TextColor, + /// A symbol instance. + Instance, + /// A keyframe's sound. + Sound, + /// A shape filled with a bitmap (a placed bitmap is one). + Bitmap, +} + +impl Field { + pub const ALL: [Field; 12] = [Field::Text, Field::Label, Field::LayerName, Field::InstanceName, Field::Script, Field::Font, Field::Fill, Field::Stroke, Field::TextColor, Field::Instance, Field::Sound, Field::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Field::Text => "text", + Field::Label => "label", + Field::LayerName => "layer_name", + Field::InstanceName => "instance_name", + Field::Script => "script", + Field::Font => "font", + Field::Fill => "fill", + Field::Stroke => "stroke", + Field::TextColor => "text_color", + Field::Instance => "instance", + Field::Sound => "sound", + Field::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Field::ALL.into_iter().find(|f| f.key() == s) + } +} + +/// Which places a text or colour search looks in (the others ignore it). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Within { + pub text: bool, + pub labels: bool, + pub layers: bool, + pub instances: bool, + pub scripts: bool, + pub fills: bool, + pub strokes: bool, + pub text_color: bool, +} + +impl Default for Within { + fn default() -> Self { + Within { text: true, labels: true, layers: true, instances: true, scripts: true, fills: true, strokes: true, text_color: true } + } +} + +/// What a query matches. +#[derive(Clone, Debug)] +pub enum Needle { + Text { re: Regex, expand: bool }, + /// A family name, lower-cased and trimmed. + Font(String), + Color([u8; 3]), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +/// A checked search. +#[derive(Clone, Debug)] +pub struct Query { + pub needle: Needle, + pub within: Within, + pub scope: Scope, +} + +/// The text options of a text search, as the Find and Replace window holds them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TextOptions { + pub match_case: bool, + pub whole_word: bool, + pub regex: bool, +} + +/// Compiles `text` as a bounded pattern. +pub fn text_needle(text: &str, o: TextOptions) -> Result { + if text.is_empty() { + return Err(EngineError::Param("type something to find".into())); + } + if text.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to find is at most {MAX_QUERY_CHARS} characters"))); + } + let body = if o.regex { text.to_string() } else { regex::escape(text) }; + let pattern = if o.whole_word { format!(r"\b(?:{body})\b") } else { body }; + let re = RegexBuilder::new(&pattern) + .case_insensitive(!o.match_case) + .size_limit(REGEX_LIMIT) + .dfa_size_limit(REGEX_LIMIT) + .nest_limit(64) + .build() + .map_err(|e| EngineError::Param(match e { + regex::Error::CompiledTooBig(_) => "that pattern is too large; make it simpler".to_string(), + regex::Error::Syntax(s) => format!("that isn't a pattern: {}", s.lines().last().unwrap_or("").trim()), + _ => "that isn't a pattern".to_string(), + }))?; + Ok(Needle::Text { re, expand: o.regex }) +} + +fn rgb8(c: Rgba) -> [u8; 3] { + let c = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + [b(c.r), b(c.g), b(c.b)] +} + +fn font_key(f: &str) -> String { + f.trim().to_lowercase() +} + +fn opt_id(p: &Value, key: &str) -> Result { + opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required: a Library id"))) +} + +impl Query { + /// The query in `p` (`find.search`'s params), checked against the document. + pub fn from_params(s: &Session, p: &Value) -> Result { + let kind = str_req(p, "kind")?; + let kind = Kind::from_key(kind).ok_or_else(|| EngineError::Param(format!("unknown kind '{kind}' (text, font, color, symbol, sound or bitmap)")))?; + let needle = match kind { + Kind::Text => { + let o = TextOptions { match_case: opt_bool(p, "match_case")?.unwrap_or(false), whole_word: opt_bool(p, "whole_word")?.unwrap_or(false), regex: opt_bool(p, "regex")?.unwrap_or(false) }; + text_needle(str_req(p, "text")?, o)? + } + Kind::Font => { + let f = font_key(str_req(p, "font")?); + if f.is_empty() || f.chars().count() > 256 { + return Err(EngineError::Param("'font' must be a family name".into())); + } + Needle::Font(f) + } + Kind::Color => Needle::Color(rgb8(opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' is required: #rrggbb".into()))?)), + Kind::Symbol => { + let id = SymbolId(opt_id(p, "symbol")?); + s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Needle::Symbol(id) + } + Kind::Sound => { + let id = SoundId(opt_id(p, "sound")?); + s.doc.sound(id).ok_or_else(|| EngineError::State(format!("no sound with id {}", id.0)))?; + Needle::Sound(id) + } + Kind::Bitmap => { + let id = BitmapId(opt_id(p, "bitmap")?); + s.doc.bitmap(id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + Needle::Bitmap(id) + } + }; + let within = match p.get("in") { + None | Some(Value::Null) => Within::default(), + Some(Value::Array(list)) => { + let mut w = Within { text: false, labels: false, layers: false, instances: false, scripts: false, fills: false, strokes: false, text_color: false }; + for v in list.iter().take(16) { + match (kind, v.as_str()) { + (Kind::Text, Some("text")) => w.text = true, + (Kind::Text, Some("labels")) => w.labels = true, + (Kind::Text, Some("layers")) => w.layers = true, + (Kind::Text, Some("instances")) => w.instances = true, + (Kind::Text, Some("scripts")) => w.scripts = true, + (Kind::Color, Some("fills")) => w.fills = true, + (Kind::Color, Some("strokes")) => w.strokes = true, + (Kind::Color, Some("text")) => w.text_color = true, + (_, other) => return Err(EngineError::Param(format!("'in' can't hold {}", other.map_or_else(|| v.to_string(), |o| format!("'{o}'"))))), + } + } + w + } + Some(_) => return Err(EngineError::Param("'in' must be a list".into())), + }; + let scope = match opt_str(p, "scope")? { + None | Some("scene") => Scope::Scene, + Some("document") => Scope::Document, + Some(o) => return Err(EngineError::Param(format!("'scope' is scene or document, not '{o}'"))), + }; + Ok(Query { needle, within, scope }) + } + + pub fn kind(&self) -> Kind { + match self.needle { + Needle::Text { .. } => Kind::Text, + Needle::Font(_) => Kind::Font, + Needle::Color(_) => Kind::Color, + Needle::Symbol(_) => Kind::Symbol, + Needle::Sound(_) => Kind::Sound, + Needle::Bitmap(_) => Kind::Bitmap, + } + } +} + +/// One place a search found. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub at: Where, + pub layer: LayerId, + /// The keyframe's first frame; `None` for a layer's name. + pub frame: Option, + pub element: Option, + pub field: Field, + /// A text match's characters in the field (`start..end`); `0..0` otherwise. + pub start: usize, + pub end: usize, + /// What was found: the matched text, the font, the colour (#rrggbb), or the item's name. + pub found: String, + /// The text around a match, on one line, for lists (empty for other kinds). + pub context: String, +} + +impl Hit { + pub fn to_json(&self, doc: &Document, kind: Kind) -> Value { + let mut v = json!({ + "kind": kind.key(), "field": self.field.key(), "layer": self.layer.0, "frame": self.frame, + "element": self.element.map(|e| e.0), "start": self.start, "end": self.end, "found": self.found, "context": self.context, + }); + match self.at { + Where::Scene(i) => { + v["scene"] = json!(i); + v["scene_name"] = json!(doc.scenes.get(i).map(|s| s.name.as_str())); + } + Where::Symbol(id) => { + v["symbol"] = json!(id.0); + v["symbol_name"] = json!(doc.symbol(id).map(|s| s.name.as_str())); + } + } + v["layer_name"] = json!(timeline_of(doc, self.at).and_then(|t| t.layer(self.layer)).map(|l| l.name.as_str())); + v + } + + /// The hit `v` names (as [`Hit::to_json`] wrote it), without what was found. + fn target(v: &Value) -> Result { + let bad = || EngineError::Param("'at' must be a hit as find.search returns it".into()); + if !v.is_object() { + return Err(bad()); + } + let at = match (opt_u64(v, "scene")?, opt_u64(v, "symbol")?) { + (Some(i), None) => Where::Scene(usize::try_from(i).map_err(|_| bad())?), + (None, Some(id)) => Where::Symbol(SymbolId(id)), + _ => return Err(bad()), + }; + let field = opt_str(v, "field")?.and_then(Field::from_key).ok_or_else(bad)?; + let layer = LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?); + Ok(Target { at, layer, frame: opt_u32(v, "frame")?, element: opt_u64(v, "element")?.map(ElementId), field, start: opt_u64(v, "start")?.and_then(|n| usize::try_from(n).ok()).unwrap_or(0) }) + } +} + +/// A hit's place (what `find.replace`'s `at` names). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Target { + at: Where, + layer: LayerId, + frame: Option, + element: Option, + field: Field, + start: usize, +} + +impl Target { + fn is(&self, h: &Hit) -> bool { + self.at == h.at && self.layer == h.layer && self.frame == h.frame && self.element == h.element && self.field == h.field && (!matches!(h.field, Field::Text | Field::Label | Field::LayerName | Field::InstanceName | Field::Script) || self.start == h.start) + } +} + +/// The timeline `at` names. +pub fn timeline_of(doc: &Document, at: Where) -> Option<&Timeline> { + match at { + Where::Scene(i) => doc.scenes.get(i).map(|s| &s.timeline), + Where::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), + } +} + +fn timeline_of_mut(doc: &mut Document, at: Where) -> Option<&mut Timeline> { + match at { + Where::Scene(i) => doc.scenes.get_mut(i).map(|s| &mut Arc::make_mut(s).timeline), + Where::Symbol(id) => doc.library.iter_mut().find(|s| s.id == id).map(|s| &mut Arc::make_mut(s).timeline), + } +} + +/// The symbols an instance on `tl` shows (directly). +fn used_symbols(tl: &Timeline, mut f: impl FnMut(SymbolId)) { + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()) { + for e in &k.elements { + if let ElementKind::Symbol { symbol, .. } = e.kind { + f(symbol); + } + } + } +} + +/// Every symbol reachable from `roots` through instances (the roots included), however deep. +pub fn reachable(doc: &Document, roots: impl IntoIterator) -> HashSet { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen = HashSet::new(); + let mut todo: Vec = roots.into_iter().collect(); + while let Some(id) = todo.pop() { + if !seen.insert(id) { + continue; + } + if let Some(sym) = by_id.get(&id) { + used_symbols(&sym.timeline, |u| { + if !seen.contains(&u) { + todo.push(u); + } + }); + } + } + seen +} + +/// The timelines a scope covers, in order: scenes first, then symbols in Library order. +pub fn timelines(doc: &Document, scene: usize, scope: Scope) -> Vec { + match scope { + Scope::Document => (0..doc.scenes.len()).map(Where::Scene).chain(doc.library.iter().map(|s| Where::Symbol(s.id))).collect(), + Scope::Scene => { + let mut used = Vec::new(); + used_symbols(doc.timeline(scene), |s| used.push(s)); + let inside = reachable(doc, used); + std::iter::once(Where::Scene(scene.min(doc.scenes.len().saturating_sub(1)))).chain(doc.library.iter().filter(|s| inside.contains(&s.id)).map(|s| Where::Symbol(s.id))).collect() + } + } +} + +/// Non-empty matches of `re` in `text`: byte range and character start/end. +fn text_matches<'a>(re: &'a Regex, text: &'a str) -> impl Iterator + 'a { + let (mut byte, mut ch) = (0usize, 0usize); + re.find_iter(text).filter(|m| !m.is_empty()).map(move |m| { + ch += text.get(byte..m.start()).map_or(0, |t| t.chars().count()); + let len = m.as_str().chars().count(); + byte = m.end(); + let out = (m.start(), m.end(), ch, ch + len); + ch += len; + out + }) +} + +/// At most `n` characters of `t`, with "…" when there were more. +fn clip(t: &str, n: usize) -> String { + let mut out: String = t.chars().take(n).collect(); + if out.len() < t.len() { + out.push('…'); + } + out +} + +/// `text` around bytes `a..b`, on one line (the match itself clipped too). +fn context(text: &str, a: usize, b: usize) -> String { + let mut before: Vec = text.get(..a).unwrap_or("").chars().rev().take(CONTEXT + 1).collect(); + let cut = before.len() > CONTEXT; + before.truncate(CONTEXT); + let mut out: String = if cut { "…".into() } else { String::new() }; + out.extend(before.into_iter().rev()); + out.push_str(&clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT)); + out.push_str(&clip(text.get(b..).unwrap_or(""), CONTEXT)); + out.replace(['\n', '\r', '\t'], " ") +} + +/// Collects hits as they are found, up to [`MAX_HITS`]. +struct Found<'a> { + q: &'a Query, + doc: &'a Document, + hits: Vec, + truncated: bool, +} + +impl Found<'_> { + fn full(&mut self) -> bool { + if self.hits.len() >= MAX_HITS { + self.truncated = true; + } + self.truncated + } + + fn push(&mut self, h: Hit) { + if !self.full() { + self.hits.push(h); + } + } + + fn text(&mut self, place: (Where, LayerId, Option, Option), field: Field, text: &str) { + let q = self.q; + let Needle::Text { re, .. } = &q.needle else { return }; + for (a, b, ca, cb) in text_matches(re, text) { + if self.full() { + return; + } + self.hits.push(Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field, start: ca, end: cb, found: clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT), context: context(text, a, b) }); + } + } + + fn timeline(&mut self, at: Where, tl: &Timeline) { + let q = self.q; + let w = q.within; + for l in &tl.layers { + if self.full() { + return; + } + if w.layers && matches!(q.needle, Needle::Text { .. }) { + self.text((at, l.id, None, None), Field::LayerName, &l.name); + } + for k in &l.keyframes { + let f = Some(k.start); + let place = |e: Option| Hit { at, layer: l.id, frame: f, element: e, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() }; + match &q.needle { + Needle::Text { .. } => { + if w.labels { + self.text((at, l.id, f, None), Field::Label, &k.label); + } + if w.scripts + && let Some(FrameScript::Source(src)) = &k.script + { + self.text((at, l.id, f, None), Field::Script, &src.text); + } + } + Needle::Sound(id) if k.sound.as_ref().is_some_and(|fs| fs.sound == *id) => { + let found = self.doc.sound(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Sound, found, ..place(None) }); + } + _ => {} + } + for e in &k.elements { + if self.full() { + return; + } + let place = (at, l.id, f, Some(e.id)); + match (&q.needle, &e.kind) { + (Needle::Text { .. }, kind) => { + if w.instances { + self.text(place, Field::InstanceName, &e.name); + } + if w.text + && let ElementKind::Text(t) = kind + { + self.text(place, Field::Text, &t.text); + } + } + (Needle::Font(f), ElementKind::Text(t)) if font_key(&t.font) == *f => self.push(Hit { field: Field::Font, found: t.font.clone(), ..hit_at(place) }), + (Needle::Color(c), ElementKind::Shape(sh)) => { + if w.fills && sh.fill.as_ref().is_some_and(|p| paint_has(p, *c)) { + self.push(Hit { field: Field::Fill, found: hex(*c), ..hit_at(place) }); + } + if w.strokes && sh.stroke.as_ref().is_some_and(|s| rgb8(s.color) == *c) { + self.push(Hit { field: Field::Stroke, found: hex(*c), ..hit_at(place) }); + } + } + (Needle::Color(c), ElementKind::Text(t)) if w.text_color && rgb8(t.color) == *c => self.push(Hit { field: Field::TextColor, found: hex(*c), ..hit_at(place) }), + (Needle::Symbol(id), ElementKind::Symbol { symbol, .. }) if symbol == id => { + let found = self.doc.symbol(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Instance, found, ..hit_at(place) }); + } + (Needle::Bitmap(id), ElementKind::Shape(sh)) if matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == id) => { + let found = self.doc.bitmap(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Bitmap, found, ..hit_at(place) }); + } + _ => {} + } + } + } + } + } +} + +fn hit_at(place: (Where, LayerId, Option, Option)) -> Hit { + Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() } +} + +fn hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +fn paint_has(p: &Paint, c: [u8; 3]) -> bool { + match p { + Paint::Solid(x) => rgb8(*x) == c, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.iter().any(|s| rgb8(s.color) == c), + Paint::Bitmap { .. } => false, + } +} + +/// Every hit of `q` in its scope (from scene `scene`), in order, and whether the list stopped at +/// [`MAX_HITS`]. +pub fn search(doc: &Document, scene: usize, q: &Query) -> (Vec, bool) { + let mut f = Found { q, doc, hits: Vec::new(), truncated: false }; + for at in timelines(doc, scene, q.scope) { + if let Some(tl) = timeline_of(doc, at) { + f.timeline(at, tl); + } + if f.truncated { + break; + } + } + (f.hits, f.truncated) +} + +fn search_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let (hits, truncated) = search(&s.doc, s.scene, &q); + let kind = q.kind(); + let page: Vec = hits.iter().skip(offset).take(limit).map(|h| h.to_json(&s.doc, kind)).collect(); + Ok(json!({"hits": page, "total": hits.len(), "offset": offset, "truncated": truncated})) +} + +// ----- replace ----------------------------------------------------------------------------- + +/// What hits are replaced with. +#[derive(Clone, Debug)] +pub enum With { + Text(String), + Font(String), + Color(Rgba), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +impl With { + fn from_params(s: &Session, kind: Kind, p: &Value) -> Result { + let v = p.get("with").ok_or_else(|| EngineError::Param("param 'with' is required: what to replace with".into()))?; + let id = || v.as_u64().ok_or_else(|| EngineError::Param("'with' must be a Library id".into())); + Ok(match kind { + Kind::Text => { + let t = v.as_str().ok_or_else(|| EngineError::Param("'with' must be text".into()))?; + if t.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to replace with is at most {MAX_QUERY_CHARS} characters"))); + } + With::Text(t.to_string()) + } + Kind::Font => { + let f = v.as_str().map(str::trim).filter(|f| !f.is_empty() && f.chars().count() <= 256).ok_or_else(|| EngineError::Param("'with' must be a font family".into()))?; + With::Font(f.to_string()) + } + Kind::Color => With::Color(opt_color(p, "with")?.ok_or_else(|| EngineError::Param("'with' must be a colour: #rrggbb".into()))?), + Kind::Symbol => { + let to = SymbolId(id()?); + s.doc.symbol(to).ok_or_else(|| EngineError::State(format!("no symbol with id {}", to.0)))?; + With::Symbol(to) + } + Kind::Sound => { + let to = SoundId(id()?); + s.doc.sound(to).ok_or_else(|| EngineError::State(format!("no sound with id {}", to.0)))?; + With::Sound(to) + } + Kind::Bitmap => { + let to = BitmapId(id()?); + s.doc.bitmap(to).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", to.0)))?; + With::Bitmap(to) + } + }) + } +} + +/// `text` with the matches of `re` replaced by `with` (only the one starting at character `only` +/// when given); `None` when nothing matched. +fn replace_text(re: &Regex, expand: bool, text: &str, with: &str, only: Option) -> Option { + let mut out = String::with_capacity(text.len()); + // `last`: copied up to here; `seen`, `ch`: characters counted up to byte `seen`. + let (mut last, mut seen, mut ch, mut any) = (0usize, 0usize, 0usize, false); + for caps in re.captures_iter(text) { + let Some(m) = caps.get(0) else { continue }; + if m.is_empty() { + continue; + } + ch += text.get(seen..m.start()).map_or(0, |t| t.chars().count()); + let this = ch; + ch += m.as_str().chars().count(); + seen = m.end(); + if only.is_some_and(|o| o != this) { + continue; + } + out.push_str(text.get(last..m.start()).unwrap_or("")); + if expand { + caps.expand(with, &mut out); + } else { + out.push_str(with); + } + last = m.end(); + any = true; + if only.is_some() { + break; + } + } + if !any { + return None; + } + out.push_str(text.get(last..).unwrap_or("")); + Some(out) +} + +/// The places Replace All would change (each field once). +pub fn places(hits: &[Hit]) -> usize { + let mut seen = HashSet::new(); + hits.iter().filter(|h| seen.insert((h.at, h.layer, h.frame, h.element, h.field))).count() +} + +/// How many places `find.replace` with `p` would change (for its confirmation); `None` when +/// the params don't make a query or name one hit. +pub(crate) fn replace_count(s: &Session, p: &Value) -> Option { + if p.get("at").is_some_and(|v| !v.is_null()) { + return None; + } + let q = Query::from_params(s, p).ok()?; + Some(places(&search(&s.doc, s.scene, &q).0)) +} + +/// What a replacement did. +#[derive(Default)] +struct Tally { + replaced: usize, + skipped: usize, + notes: Vec, +} + +impl Tally { + fn note(&mut self, n: String) { + if !self.notes.contains(&n) && self.notes.len() < 16 { + self.notes.push(n); + } + } +} + +fn replace_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let with = With::from_params(s, q.kind(), p)?; + let only = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(Hit::target(v)?), + }; + let (mut hits, truncated) = search(&s.doc, s.scene, &q); + if let Some(t) = &only { + hits.retain(|h| t.is(h)); + if hits.is_empty() { + return Err(EngineError::State("that match isn't there any more; search again".into())); + } + } + if hits.is_empty() { + return Err(EngineError::State("nothing matches".into())); + } + // A symbol can't end up inside itself: no instance of `to` in `to`, or in a symbol it uses. + let blocked: HashSet = match with { + With::Symbol(to) => reachable(&s.doc, [to]), + _ => HashSet::new(), + }; + let sizes: HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); + let mut tally = Tally::default(); + let mut by_tl: Vec<(Where, Vec)> = Vec::new(); + for h in hits { + match by_tl.last_mut() { + Some((at, list)) if *at == h.at => list.push(h), + _ => by_tl.push((h.at, vec![h])), + } + } + for (at, list) in by_tl { + if let Where::Symbol(id) = at + && blocked.contains(&id) + { + tally.skipped += places(&list); + tally.note("an instance inside the symbol it would show (or one it uses) was left as it is: a symbol can't contain itself".into()); + continue; + } + let Some(tl) = timeline_of_mut(&mut s.doc, at) else { continue }; + apply(tl, &list, &q, &with, only.as_ref().map(|t| t.start), &sizes, &mut tally)?; + } + if tally.replaced == 0 { + return Err(EngineError::State(tally.notes.first().cloned().unwrap_or_else(|| "nothing could be replaced".into()))); + } + // The fill swatch and the text style keep what they were: replacing edits the document only. + Ok(json!({"replaced": tally.replaced, "skipped": tally.skipped, "notes": tally.notes, "truncated": truncated})) +} + +/// Replaces `hits` (all on `tl`) in place, un-sharing only the layers, keyframes and elements +/// they are on. `only`: the one text match to replace (Replace), by its first character. +fn apply(tl: &mut Timeline, hits: &[Hit], q: &Query, with: &With, only: Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + let layers: HashSet = hits.iter().map(|h| h.layer).collect(); + let (re, expand) = match &q.needle { + Needle::Text { re, expand } => (Some(re), *expand), + _ => (None, false), + }; + let new_text = |text: &str| -> Option { + match (re, with) { + (Some(re), With::Text(w)) => replace_text(re, expand, text, w, only), + _ => None, + } + }; + for l in tl.layers.iter_mut().filter(|l| layers.contains(&l.id)) { + let lh: Vec<&Hit> = hits.iter().filter(|h| h.layer == l.id).collect(); + let l = Arc::make_mut(l); + if lh.iter().any(|h| h.field == Field::LayerName) { + match new_text(&l.name).map(|n| n.chars().take(128).collect::()) { + Some(n) if !n.trim().is_empty() => { + l.name = n; + t.replaced += 1; + } + _ => { + t.skipped += 1; + t.note("a layer name can't be empty".into()); + } + } + } + let frames: HashSet = lh.iter().filter_map(|h| h.frame).collect(); + for k in l.keyframes.iter_mut().filter(|k| frames.contains(&k.start)) { + let kh: Vec<&&Hit> = lh.iter().filter(|h| h.frame == Some(k.start)).collect(); + let k = Arc::make_mut(k); + let has = |f: Field| kh.iter().any(|h| h.field == f && h.element.is_none()); + if has(Field::Label) + && let Some(n) = new_text(&k.label) + { + k.label = n.chars().take(256).collect(); + t.replaced += 1; + } + if has(Field::Script) + && let Some(FrameScript::Source(src)) = &k.script + && let Some(n) = new_text(&src.text) + { + if n.len() > anicraft_doc::actions::MAX_SOURCE_BYTES { + t.skipped += 1; + t.note("a script would be too long".into()); + } else { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(src.language, n)))); + t.replaced += 1; + } + } + if has(Field::Sound) + && let (Some(fs), With::Sound(to)) = (k.sound.as_mut(), with) + { + fs.sound = *to; + t.replaced += 1; + } + let ids: HashSet = kh.iter().filter_map(|h| h.element).collect(); + for e in k.elements.iter_mut().filter(|e| ids.contains(&e.id)) { + let fields: Vec = kh.iter().filter(|h| h.element == Some(e.id)).map(|h| h.field).collect(); + let e = Arc::make_mut(e); + for f in Field::ALL.into_iter().filter(|f| fields.contains(f)) { + apply_element(e, f, q, with, &new_text, sizes, t)?; + } + } + } + } + Ok(()) +} + +/// Replaces field `f` of element `e`. +fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With, new_text: &dyn Fn(&str) -> Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + match (f, &mut e.kind, with) { + (Field::InstanceName, _, _) => { + if let Some(n) = new_text(&e.name) { + e.name = n.chars().take(128).collect(); + t.replaced += 1; + } + } + (Field::Text, ElementKind::Text(tb), _) => { + if let Some(n) = new_text(&tb.text) { + if n.trim().is_empty() { + t.skipped += 1; + t.note("a text field can't be left empty (delete it instead)".into()); + } else { + // Laid out again as it is: text on a path stays on it (ADR 0070). + let (block, note, shift) = crate::cmds_text::relay_static(tb, &n, &crate::cmds_text::style_of(tb))?; + t.note_opt(note); + *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); + t.replaced += 1; + } + } + } + (Field::Font, ElementKind::Text(tb), With::Font(family)) => { + let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) }; + let (block, note, shift) = crate::cmds_text::relay_static(tb, &tb.text, &style)?; + t.note_opt(note); + *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); + t.replaced += 1; + } + (Field::TextColor, ElementKind::Text(tb), With::Color(c)) => { + let tb = Arc::make_mut(tb); + tb.color = Rgba { a: tb.color.a, ..*c }; + t.replaced += 1; + } + (Field::Fill | Field::Stroke, ElementKind::Shape(sh), With::Color(c)) => { + let Needle::Color(from) = q.needle else { return Ok(()) }; + let recolour = |x: &mut Rgba| { + if rgb8(*x) == from { + *x = Rgba { a: x.a, ..*c }; + } + }; + if f == Field::Fill { + match &mut sh.fill { + Some(Paint::Solid(x)) => recolour(x), + Some(Paint::Linear { stops, .. } | Paint::Radial { stops, .. }) => stops.iter_mut().for_each(|s| recolour(&mut s.color)), + _ => {} + } + } else if let Some(st) = &mut sh.stroke { + recolour(&mut st.color); + } + t.replaced += 1; + } + (Field::Instance, ElementKind::Symbol { symbol, .. }, With::Symbol(to)) => { + *symbol = *to; + t.replaced += 1; + } + (Field::Bitmap, ElementKind::Shape(_), With::Bitmap(to)) => { + t.replaced += usize::from(crate::cmds_library::swap_bitmap_of(e, *to, sizes)); + } + _ => {} + } + Ok(()) +} + +impl Tally { + fn note_opt(&mut self, n: Option) { + if let Some(n) = n { + self.note(n); + } + } +} + +// ----- go to ------------------------------------------------------------------------------- + +/// One instance opened in place on the way to a symbol: on `layer`, at the keyframe starting at +/// `frame`, the instance `element`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Step { + pub layer: LayerId, + pub frame: u32, + pub element: ElementId, +} + +impl Step { + pub fn to_json(&self) -> Value { + json!({"layer": self.layer.0, "frame": self.frame, "element": self.element.0}) + } +} + +/// Where a scene or symbol timeline holding layer `id` is. +pub fn locate_layer(doc: &Document, id: LayerId) -> Option { + doc.scenes.iter().position(|s| s.timeline.layer(id).is_some()).map(Where::Scene).or_else(|| doc.library.iter().find(|s| s.timeline.layer(id).is_some()).map(|s| Where::Symbol(s.id))) +} + +/// The shortest chain of instances from scene `scene`'s timeline to symbol `target` (each opened +/// in place in turn), when an instance in that scene leads to it. +pub fn route(doc: &Document, scene: usize, target: SymbolId) -> Option> { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen: HashSet = HashSet::new(); + let mut todo: VecDeque<(&Timeline, Vec)> = VecDeque::from([(doc.timeline(scene), Vec::new())]); + while let Some((tl, path)) = todo.pop_front() { + if path.len() >= MAX_ROUTE { + continue; + } + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + let ElementKind::Symbol { symbol, .. } = e.kind else { continue }; + let mut next = path.clone(); + next.push(Step { layer: l.id, frame: k.start, element: e.id }); + if symbol == target { + return Some(next); + } + if seen.insert(symbol) + && let Some(sym) = by_id.get(&symbol) + { + todo.push_back((&sym.timeline, next)); + } + } + } + } + } + None +} + +fn steps_of(p: &Value) -> Result>> { + let Some(list) = p.get("path").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = list.as_array().ok_or_else(|| EngineError::Param("'path' must be a list of {layer, frame, element}".into()))?; + if list.len() > MAX_ROUTE { + return Err(EngineError::Param(format!("'path' opens at most {MAX_ROUTE} instances"))); + } + let bad = || EngineError::Param("each step of 'path' is {layer, frame, element}".into()); + list.iter() + .map(|v| Ok(Step { layer: LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?), frame: opt_u32(v, "frame")?.ok_or_else(bad)?, element: ElementId(opt_u64(v, "element")?.ok_or_else(bad)?) })) + .collect::>>() + .map(Some) +} + +/// Opens each instance of `steps` in place, from the timeline being edited. False when one +/// can't be opened (a hidden or locked layer, an instance that isn't there). +fn walk(s: &mut Session, steps: &[Step]) -> bool { + for st in steps { + if s.timeline().layer(st.layer).is_none() { + return false; + } + s.layer = st.layer; + s.frame = st.frame.min(crate::MAX_FRAME); + s.selection.clear(); + if crate::editing::edit(s, &json!({"id": st.element.0})).is_err() { + return false; + } + } + true +} + +fn goto_cmd(s: &mut Session, p: &Value) -> Result { + let layer = opt_u64(p, "layer")?.map(LayerId); + let frame = opt_u32(p, "frame")?; + let element = opt_u64(p, "element")?.map(ElementId); + let scene = match opt_u64(p, "scene")? { + Some(i) => Some(usize::try_from(i).ok().filter(|i| *i < s.doc.scenes.len()).ok_or_else(|| EngineError::State(format!("there is no scene {i}")))?), + None => None, + }; + let symbol = opt_u64(p, "symbol")?.map(SymbolId); + if let Some(id) = symbol + && s.doc.symbol(id).is_none() + { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + } + let steps = steps_of(p)?; + if steps.is_some() && layer.is_none() { + return Err(EngineError::Param("a 'path' goes to a 'layer': name it".into())); + } + // Where to end up: the layer's timeline, else what the params name. + let target = match layer { + Some(l) => locate_layer(&s.doc, l).ok_or_else(|| EngineError::State(format!("no layer with id {}", l.0)))?, + None => match (symbol, scene) { + (Some(id), _) => Where::Symbol(id), + (None, Some(i)) => Where::Scene(i), + (None, None) => return Err(EngineError::Param("name where to go: {layer}, {scene} or {symbol}".into())), + }, + }; + let here = s.scene; + // Open symbols close first (ADR 0045). + s.exit_all(); + match target { + Where::Scene(i) => crate::cmds_scene::open_scene(s, i), + Where::Symbol(t) => { + let opened = match &steps { + // Through the instances named, from the scene (or from `symbol`, opened alone). + Some(steps) => { + match symbol { + Some(b) => { + crate::editing::edit(s, &json!({"symbol": b.0}))?; + } + None => crate::cmds_scene::open_scene(s, scene.unwrap_or(here)), + } + walk(s, steps) && s.editing_symbol() == Some(t) + } + // In place through the first instance that leads there: in this scene, else another. + None => { + let order = std::iter::once(scene.unwrap_or(here)).chain(0..s.doc.scenes.len()); + let found = order.into_iter().find_map(|i| route(&s.doc, i, t).map(|r| (i, r))); + match found { + Some((i, r)) => { + crate::cmds_scene::open_scene(s, i); + walk(s, &r) && s.editing_symbol() == Some(t) + } + None => false, + } + } + }; + if !opened { + // Alone, from the Library (no instance leads there, or one can't be opened). + s.exit_all(); + crate::editing::edit(s, &json!({"symbol": t.0}))?; + } + } + } + if let Some(l) = layer.filter(|l| s.timeline().layer(*l).is_some()) { + s.layer = l; + } + if let Some(f) = frame { + s.frame = f.min(crate::MAX_FRAME); + } + s.selection = match element { + Some(e) => Selection::only(s.layer, [e]), + None => Selection::default(), + }; + s.revision += 1; + s.dl_cache.replace(None); + s.fix_selection(); + let mut v = crate::editing::editing_json(s); + v["scene"] = json!(s.scene); + Ok(v) +} + +#[cfg(test)] +#[path = "find_tests.rs"] +pub(crate) mod tests; diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs new file mode 100644 index 00000000..609a93d1 --- /dev/null +++ b/crates/engine/src/find_tests.rs @@ -0,0 +1,456 @@ +//! Find and Replace end to end (ADR 0058): each kind, scopes, text options and bounded patterns, +//! Replace and Replace All as one undo step, the confirmation, and going to what was found +//! (symbols opened in place through the instances that lead to them). + +use super::*; +use anicraft_doc::{ColorEffect, Document, Element, ElementKind, FrameSound, GradientStop, Keyframe, Layer, LayerId, LoopMode, Paint, Rgba, Scene, Shape, SourceScript, Symbol, SymbolKind, TextAlign, TextBlock}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +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 err(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(), + } +} + +/// Builds documents by hand, ids from the document. +pub(crate) struct Build { + pub doc: Document, +} + +impl Build { + pub fn new() -> Build { + let mut doc = Document::default(); + doc.scenes.clear(); + doc.next_id = 1; + Build { doc } + } + pub fn id(&mut self) -> u64 { + self.doc.alloc_id() + } + pub fn text(&mut self, t: &str, color: Rgba) -> Element { + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None }; + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } + } + pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { + let mut sh = Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), fill); + if let Some(c) = stroke { + sh = sh.with_stroke(c, 2.0); + } + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(sh) } + } + pub fn instance(&mut self, symbol: SymbolId, name: &str) -> Element { + Element { + id: ElementId(self.id()), + name: name.into(), + transform: Affine::translate(100.0, 50.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + } + } + /// A layer with keyframes `(start, duration, label, elements)`. + pub fn layer(&mut self, name: &str, keys: Vec<(u32, u32, &str, Vec)>) -> Layer { + let mut l = Layer::new(LayerId(self.id()), name); + l.keyframes = keys + .into_iter() + .map(|(start, dur, label, els)| { + let mut k = Keyframe::new(start, dur); + k.label = label.into(); + k.elements = els.into_iter().map(Arc::new).collect(); + Arc::new(k) + }) + .collect(); + l + } + pub fn scene(&mut self, name: &str, layers: Vec) { + let mut sc = Scene::new(name); + sc.timeline.layers = layers.into_iter().map(Arc::new).collect(); + self.doc.scenes.push(Arc::new(sc)); + } + pub fn symbol(&mut self, name: &str, kind: SymbolKind) -> SymbolId { + let id = SymbolId(self.id()); + self.doc.library.push(Arc::new(Symbol { id, name: name.into(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })); + id + } + pub fn fill(&mut self, id: SymbolId, layers: Vec) { + if let Some(s) = self.doc.library.iter_mut().find(|s| s.id == id) { + Arc::make_mut(s).timeline.layers = layers.into_iter().map(Arc::new).collect(); + } + } +} + +const RED: u32 = 0xff0000; + +/// Scene 1: an Art layer (a text field, a red rect with a blue stroke, an instance of Outer +/// named "hero"; a second keyframe labelled "intro hello" with more text), an Actions layer with a +/// script. Outer holds an instance of Inner and a red rect; Inner holds text. Unused holds text +/// and is in no scene. Scene 2 has a red rect. +pub(crate) fn movie() -> (Session, SymbolId, SymbolId, SymbolId) { + let mut b = Build::new(); + let outer = b.symbol("Outer", SymbolKind::MovieClip); + let inner = b.symbol("Inner", SymbolKind::Graphic); + let unused = b.symbol("Unused", SymbolKind::Graphic); + let t = b.text("Hello inside", Rgba::hex(RED)); + let l = b.layer("Inner art", vec![(0, 5, "", vec![t])]); + b.fill(inner, vec![l]); + let i = b.instance(inner, "wheel"); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("Outer art", vec![(0, 1, "", vec![r]), (3, 2, "", vec![i])]); + b.fill(outer, vec![l]); + let t = b.text("hello unused", Rgba::BLACK); + let l = b.layer("U", vec![(0, 1, "", vec![t])]); + b.fill(unused, vec![l]); + let t1 = b.text("Hello world", Rgba::BLACK); + let r = b.rect(Paint::Solid(Rgba::hex(RED).with_alpha(0.5)), Some(Rgba::hex(0x0000ff))); + let hero = b.instance(outer, "hero"); + let t2 = b.text("hello hello again", Rgba::hex(RED)); + let art = b.layer("Art", vec![(0, 10, "", vec![t1, r, hero]), (10, 5, "intro hello", vec![t2])]); + let mut actions = b.layer("Actions", vec![(0, 15, "", vec![])]); + if let Some(k) = actions.keyframe_mut(0) { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(Default::default(), "stop(); // say hello")))); + } + b.scene("Scene 1", vec![actions, art]); + let r = b.rect(Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(RED) }, GradientStop { offset: 1.0, color: Rgba::WHITE }]), None); + let l = b.layer("Back", vec![(0, 1, "", vec![r])]); + b.scene("Scene 2", vec![l]); + (Session::new(b.doc), outer, inner, unused) +} + +fn hits(s: &mut Session, p: Value) -> Vec { + run(s, "find.search", p)["hits"].as_array().cloned().unwrap_or_default() +} + +fn fields(h: &[Value]) -> Vec { + h.iter().map(|h| h["field"].as_str().unwrap_or("").to_string()).collect() +} + +#[test] +fn text_is_found_in_every_place_and_scope() { + let (mut s, ..) = movie(); + // The scene and the symbols it uses: the script, text fields (Inner's too), the label. + let h = hits(&mut s, json!({"kind": "text", "text": "hello"})); + let found: Vec<&str> = h.iter().map(|h| h["found"].as_str().unwrap()).collect(); + assert_eq!(fields(&h), ["script", "text", "label", "text", "text", "text"], "{h:?}"); + assert_eq!(found, ["hello", "Hello", "hello", "hello", "hello", "Hello"]); + assert_eq!(h[1]["scene"], 0); + assert_eq!(h[1]["layer_name"], "Art"); + assert_eq!(h[3]["start"], 0); + assert_eq!(h[4]["start"], 6); + assert_eq!(h[4]["context"], "hello hello again"); + assert_eq!(h[5]["symbol_name"], "Inner"); + // The whole document adds the unused symbol (and Scene 2 has none). + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hello", "scope": "document"})).len(), 7); + // Case, whole words and where to look. + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "Hello", "match_case": true})).len(), 2); + assert!(hits(&mut s, json!({"kind": "text", "text": "hell", "whole_word": true})).is_empty()); + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hell"})).len(), 6); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["labels"]}))), ["label"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "her", "in": ["instances"]}))), ["instance_name"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "art", "in": ["layers"]}))), ["layer_name", "layer_name", "layer_name"]); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "x", "in": ["fills"]})).contains("'in'")); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": ""})).contains("find")); + // Paging. + let v = run(&mut s, "find.search", json!({"kind": "text", "text": "hello", "offset": 4, "limit": 1})); + assert_eq!((v["total"].as_u64(), v["hits"].as_array().map(Vec::len)), (Some(6), Some(1))); +} + +#[test] +fn patterns_are_bounded() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": r"h\w+o", "regex": true, "in": ["text"]})); + assert_eq!(h.len(), 4); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "(", "regex": true})).contains("pattern")); + // Too large to compile is refused, not run. + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "a{1000}{1000}", "regex": true})).contains("too large")); + // What backtracking engines take exponential time over runs in linear time. + let mut b = Build::new(); + let t = b.text(&format!("{}b", "a".repeat(50_000)), Rgba::BLACK); + let l = b.layer("L", vec![(0, 1, "", vec![t])]); + b.scene("S", vec![l]); + let mut big = Session::new(b.doc); + let t0 = std::time::Instant::now(); + assert_eq!(hits(&mut big, json!({"kind": "text", "text": "(a+)+$", "regex": true})).len(), 0); + assert!(t0.elapsed().as_secs_f64() < 2.0, "{:?}", t0.elapsed()); + // An empty match finds nothing, rather than every gap. + assert!(hits(&mut s, json!({"kind": "text", "text": "x*", "regex": true})).is_empty()); +} + +#[test] +fn colours_fonts_and_library_items_are_found() { + let (mut s, outer, inner, _) = movie(); + // Red: a text colour (Scene 1's second text), a fill with alpha, Outer's fill, Inner's text. + let h = hits(&mut s, json!({"kind": "color", "color": "#FF0000"})); + assert_eq!(fields(&h), ["fill", "text_color", "fill", "text_color"], "{h:?}"); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#0000ff"}))), ["stroke"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["strokes"]}))).len(), 0); + // Gradient stops count (Scene 2). + assert_eq!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"], "scope": "document"})).len(), 3); + assert_eq!(hits(&mut s, json!({"kind": "font", "font": " test sans "})).len(), 3); + let h = hits(&mut s, json!({"kind": "symbol", "symbol": inner.0})); + assert_eq!((h.len(), h[0]["symbol"].as_u64(), h[0]["found"].as_str()), (1, Some(outer.0), Some("Inner"))); + assert!(err(&mut s, "find.search", json!({"kind": "symbol", "symbol": 999_999})).contains("no symbol")); + assert!(err(&mut s, "find.search", json!({"kind": "sparkle"})).contains("unknown kind")); +} + +#[test] +fn sounds_and_bitmaps_are_found_and_replaced() { + let (mut s, ..) = movie(); + let wav = crate::cmds_sound::test_wav(8000, &[0.25; 800]); + let (a, b) = (anicraft_doc::SoundId(s.doc.alloc_id()), anicraft_doc::SoundId(s.doc.alloc_id())); + for (id, n) in [(a, "a.wav"), (b, "b.wav")] { + s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, n, wav.clone()).unwrap())); + } + let k = Arc::make_mut(&mut s.doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap(); + k.sound = Some(FrameSound::new(a)); + let h = hits(&mut s, json!({"kind": "sound", "sound": a.0})); + assert_eq!((fields(&h), h[0]["found"].as_str()), (vec!["sound".to_string()], Some("a.wav"))); + run(&mut s, "find.replace", json!({"kind": "sound", "sound": a.0, "with": b.0})); + assert_eq!(s.doc.timeline(0).layers[0].keyframes[0].sound.as_ref().map(|f| f.sound), Some(b)); + // A placed bitmap takes the new one's size. + let png = |w, h| anicraft_render::encode_png(w, h, &[0, 0, 255, 255].repeat((w * h) as usize)).unwrap(); + let (p, q) = (anicraft_doc::BitmapId(s.doc.alloc_id()), anicraft_doc::BitmapId(s.doc.alloc_id())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(p, "p.png", png(3, 2)).unwrap())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(q, "q.png", png(5, 4)).unwrap())); + run(&mut s, "library.place", json!({"bitmap": p.0})); + assert_eq!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).len(), 1); + run(&mut s, "find.replace", json!({"kind": "bitmap", "bitmap": p.0, "with": q.0})); + assert!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).is_empty()); + let placed = s.doc.timeline(0).layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find_map(|e| match &e.kind { + ElementKind::Shape(sh) if matches!(sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == q) => Some(sh.path.bounds()), + _ => None, + }); + assert_eq!(placed.map(|r| (r.width(), r.height())), Some((5.0, 4.0))); +} + +#[test] +fn replace_all_is_one_undo_step_and_undo_brings_everything_back() { + let (mut s, ..) = movie(); + let before = s.doc.clone(); + let steps = s.history_len(); + let v = run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "with": "bye", "in": ["text", "labels", "scripts"]})); + assert_eq!(v["replaced"], 5, "{v}"); + assert_eq!(s.history_len(), steps + 1); + let texts: Vec = s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }).collect(); + // Case-insensitive, every match; the unused symbol is outside the scene's scope. + assert_eq!(texts, ["bye world", "bye bye again", "bye inside", "hello unused"]); + assert_eq!(s.doc.timeline(0).layers[1].keyframes[1].label, "intro bye"); + match &s.doc.timeline(0).layers[0].keyframes[0].script { + Some(FrameScript::Source(src)) => assert_eq!(src.text, "stop(); // say bye"), + other => panic!("{other:?}"), + } + // A replaced text is laid out again (its outline was empty). + assert!(s.doc.timeline(0).layers[1].keyframes[1].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "bye bye again" && t.box_width != 10.0))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + // Nothing to replace is an error, and records nothing. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "zebra", "with": "x"})).contains("nothing")); + assert_eq!(s.history_len(), steps); +} + +#[test] +fn replace_one_changes_only_that_match() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["text"]})); + let second = h.iter().find(|h| h["start"] == 6).cloned().unwrap(); + run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})); + let t = s.doc.timeline(0).layers[1].keyframes[1].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(t.as_deref(), Some("hello HI again")); + // The same hit again is gone. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})).contains("isn't there")); + // Groups expand with a pattern, not with plain text. + run(&mut s, "find.replace", json!({"kind": "text", "text": r"(\w+) world", "regex": true, "with": "$1, $1 world"})); + let first = s.doc.timeline(0).layers[1].keyframes[0].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(first.as_deref(), Some("Hello, Hello world")); + run(&mut s, "find.replace", json!({"kind": "text", "text": "world", "with": "$0$1"})); + assert!(s.doc.timeline(0).layers[1].keyframes[0].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "Hello, Hello $0$1"))); + // A layer name can't become empty: skipped, and said why. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "Actions", "in": ["layers"], "with": ""})).contains("can't be empty")); +} + +#[test] +fn colours_keep_alpha_and_fonts_lay_out_again() { + let (mut s, ..) = movie(); + let v = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"})); + assert_eq!(v["replaced"], 5, "{v}"); + assert!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})).is_empty()); + let r = &s.doc.timeline(0).layers[1].keyframes[0].elements[1]; + match &r.kind { + ElementKind::Shape(sh) => assert_eq!(sh.fill, Some(Paint::Solid(Rgba::hex(0x00ff00).with_alpha(0.5)))), + other => panic!("{other:?}"), + } + match &s.doc.timeline(1).layers[0].keyframes[0].elements[0].kind { + ElementKind::Shape(sh) => assert!(matches!(&sh.fill, Some(Paint::Linear { stops, .. }) if stops[0].color == Rgba::hex(0x00ff00) && stops[1].color == Rgba::WHITE)), + other => panic!("{other:?}"), + } + let v = run(&mut s, "find.replace", json!({"kind": "font", "font": "Test Sans", "with": "Inter"})); + assert_eq!(v["replaced"], 3); + assert!(hits(&mut s, json!({"kind": "font", "font": "test sans"})).is_empty()); +} + +#[test] +fn a_symbol_that_would_contain_itself_is_skipped() { + let (mut s, outer, inner, unused) = movie(); + // Inner's instance is inside Outer: swapping it for Outer would nest Outer in itself. + assert!(err(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": outer.0})).contains("contain itself")); + // Into a symbol that doesn't hold the place: fine (and the scene's Outer becomes Unused). + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": outer.0, "with": unused.0})); + assert_eq!(v["replaced"], 1); + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": unused.0, "scope": "document"})); + assert_eq!(v["replaced"], 1); +} + +#[test] +fn replace_all_over_many_places_asks_first() { + let mut b = Build::new(); + let els: Vec = (0..(REPLACE_ASK + 1)).map(|_| b.rect(Paint::Solid(Rgba::hex(RED)), None)).collect(); + let l = b.layer("L", vec![(0, 1, "", els)]); + b.scene("S", vec![l]); + let mut s = Session::new(b.doc); + let p = json!({"kind": "color", "color": "#ff0000", "with": "#000000"}); + let c = s.confirmation("find.replace", &p).expect("asks above the limit"); + assert!(!c.irreversible && c.message.contains("101 places"), "{c:?}"); + // One place (Replace) never asks. + let one = hits(&mut s, p.clone()).remove(0); + let mut p1 = p.clone(); + p1["at"] = one; + assert!(s.confirmation("find.replace", &p1).is_none()); + // Undoable, so a script runs it without "confirm". + assert_eq!(run(&mut s, "find.replace", p)["replaced"], 101); +} + +#[test] +fn going_to_a_hit_opens_the_symbols_in_place_and_selects_it() { + let (mut s, outer, inner, unused) = movie(); + // Inner's text: through hero (Outer) and wheel (Inner), in place. + let h = hits(&mut s, json!({"kind": "text", "text": "inside"})).remove(0); + let v = run(&mut s, "find.goto", h.clone()); + let open: Vec = s.editing.iter().map(|l| l.symbol().unwrap_or(SymbolId(0))).collect(); + assert_eq!(open, [outer, inner], "{v}"); + assert!(s.editing.iter().all(|l| l.instance.is_some())); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + assert_eq!(s.edit_view().map(|v| v.in_place), Some(true)); + // A symbol no scene uses opens alone, from the Library. + let h = hits(&mut s, json!({"kind": "text", "text": "unused", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h.clone()); + assert_eq!((s.editing.len(), s.editing_symbol(), s.editing[0].instance), (1, Some(unused), None)); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + // Another scene: the scene switches, the frame is the keyframe's. + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})); + let back = h.iter().find(|h| h["scene"] == 1).cloned().unwrap(); + run(&mut s, "find.goto", back); + assert_eq!((s.scene, s.editing.len(), s.selection.len()), (1, 0, 1)); + // A label: the keyframe, nothing selected. + let h = hits(&mut s, json!({"kind": "text", "text": "intro", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h); + assert_eq!((s.scene, s.frame, s.selection.len()), (0, 10, 0)); + assert_eq!(s.active_layer().map(|l| l.name.as_str()), Some("Art")); + // Going somewhere records nothing to undo. + assert!(!s.can_undo()); + assert!(err(&mut s, "find.goto", json!({})).contains("where")); + assert!(err(&mut s, "find.goto", json!({"layer": 999_999})).contains("no layer")); +} + +#[test] +fn going_to_a_symbol_behind_a_locked_layer_opens_it_alone() { + let (mut s, outer, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": art})); + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"]})); + let inside = h.iter().find(|h| h["symbol"] == outer.0).cloned().unwrap(); + run(&mut s, "find.goto", inside); + assert_eq!((s.editing_symbol(), s.editing[0].instance), (Some(outer), None)); +} + +#[test] +fn search_and_replace_are_fast_on_a_large_document() { + // 40 layers × 300 keyframes (12,000 text fields and 12,000 shapes), 500 symbols. + let mut b = Build::new(); + let mut layers = Vec::new(); + for li in 0..40 { + let keys: Vec<(u32, u32, &str, Vec)> = (0..300).map(|k| (k, 1, "", vec![b.text(&format!("caption {li} {k} needle"), Rgba::BLACK), b.rect(Paint::Solid(Rgba::hex(RED)), None)])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + for i in 0..500 { + let id = b.symbol(&format!("S{i}"), SymbolKind::Graphic); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("x", vec![(0, 1, "", vec![r])]); + b.fill(id, vec![l]); + } + let mut s = Session::new(b.doc); + let t0 = std::time::Instant::now(); + let n = run(&mut s, "find.search", json!({"kind": "text", "text": "needle", "whole_word": true, "limit": 1}))["total"].as_u64(); + let text = t0.elapsed(); + let t0 = std::time::Instant::now(); + let c = run(&mut s, "find.search", json!({"kind": "color", "color": "#ff0000", "scope": "document", "limit": 1}))["total"].as_u64(); + let colour = t0.elapsed(); + let t0 = std::time::Instant::now(); + let r = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"}))["replaced"].as_u64(); + let replace = t0.elapsed(); + let t0 = std::time::Instant::now(); + run(&mut s, "edit.undo", json!({})); + let undo = t0.elapsed(); + println!("find on 24,000 elements: text {text:?}, colour {colour:?}; Replace All of 12,500 colours {replace:?}, its undo {undo:?}"); + assert_eq!((n, c, r), (Some(12_000), Some(12_500), Some(12_500))); + assert!(text.as_secs_f64() < 2.0 && colour.as_secs_f64() < 2.0 && replace.as_secs_f64() < 5.0); +} + +#[test] +fn random_queries_never_panic() { + let (s0, outer, inner, _) = movie(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let atoms = ["a", "(", ")", "*", "+", "?", "|", "\\b", "\\w", "[", "]", "{2,}", ".", "^", "$", "hello", "é", "\\", "$1", "${x}", "\n"]; + let kinds = ["text", "font", "color", "symbol", "sound", "bitmap", "x"]; + let mut s = s0; + for _ in 0..400 { + let pat: String = (0..(next() % 6)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let with: String = (0..(next() % 4)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let kind = kinds[(next() % kinds.len() as u64) as usize]; + let id = [outer.0, inner.0, next()][(next() % 3) as usize]; + let p = json!({"kind": kind, "text": pat, "regex": next() % 2 == 0, "whole_word": next() % 3 == 0, "match_case": next() % 2 == 0, "font": pat, "color": format!("#{:06x}", next() % 0xffffff), "symbol": id, "sound": id, "bitmap": id, "with": if next() % 2 == 0 { json!(with) } else { json!(id) }, "scope": if next() % 2 == 0 { "scene" } else { "document" }}); + if let Ok(v) = s.execute("find.search", &p) + && let Some(h) = v["hits"].as_array().and_then(|h| h.first()) + { + let _ = s.execute("find.goto", h); + let mut one = p.clone(); + one["at"] = h.clone(); + let _ = s.execute("find.replace", &one); + } + let _ = s.execute("find.replace", &p); + if next() % 7 == 0 { + let _ = s.execute("edit.undo", &json!({})); + } + } + let _ = anicraft_render::render_frame(&s.doc, 0, 0.1); +} + +#[test] +fn the_new_namespaces_are_open_to_plug_ins() { + for id in ["find.search", "find.replace", "find.goto", "explorer.tree"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/gradient_tests.rs b/crates/engine/src/gradient_tests.rs new file mode 100644 index 00000000..9c204125 --- /dev/null +++ b/crates/engine/src/gradient_tests.rs @@ -0,0 +1,244 @@ +//! The fill swatch's gradients, Lock Fill and the Gradient Transform tool's command (ADR 0074). + +use crate::Session; +use anicraft_doc::{ElementId, ElementKind, Paint, Rgba, Shape, Spread}; +use anicraft_geom::{Affine, Vec2}; +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}: {e}")) +} + +fn shape(s: &Session, id: u64) -> (Shape, Affine) { + s.visible_elements() + .iter() + .find(|e| e.id == ElementId(id)) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some((sh.clone(), e.transform)), + _ => None, + }) + .expect("a shape") +} + +/// A 100 × 100 square at (x, 100), selected (drawing commands select what they draw). +fn square(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}))["element"].as_u64().unwrap() +} + +/// A 100 × 100 square at (x, 100) in the fill swatch. +fn poured(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "stroke": null}))["element"].as_u64().unwrap() +} + +/// Where a shape's fill lies on the stage. +fn stage_frame(s: &Session, id: u64) -> Affine { + let (sh, m) = shape(s, id); + m.mul(&sh.fill.and_then(|f| f.frame(None)).expect("a gradient")) +} + +fn near(a: &Affine, b: &Affine) -> bool { + a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-3 * x.abs().max(y.abs()).max(1.0)) +} + +const RAMP: &str = r##"[{"offset": 0, "color": "#ff8800"}, {"offset": 0.5, "color": "#ffffff80"}, {"offset": 1, "color": "#0044ff"}]"##; + +#[test] +fn set_fill_makes_gradients_for_the_swatch_and_the_selection_in_one_step() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + let steps = s.history_len(); + let stops: Value = serde_json::from_str(RAMP).unwrap(); + let r = run(&mut s, "paint.set_fill", json!({"type": "linear", "stops": stops, "spread": "reflect", "linear_rgb": true})); + assert_eq!(r["changed"], 1); + assert_eq!(r["fill"]["type"], "linear"); + assert_eq!(r["fill"]["stops"][1]["color"], "#ffffff80", "alpha survives as #rrggbbaa"); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // The selected square's fill is fitted to it: across its width, through its middle. + match shape(&s, a).0.fill { + Some(Paint::Linear { start, end, stops, spread, linear_rgb }) => { + assert_eq!((start, end), (Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0))); + assert_eq!((stops.len(), spread, linear_rgb), (3, Spread::Reflect, true)); + assert!((stops[1].color.a - 128.0 / 255.0).abs() < 1e-6); + } + other => panic!("{other:?}"), + } + // The swatch holds it too (across the stage), so the next shape gets it, fitted. + assert!(matches!(s.style.fill_paint, Some(Paint::Linear { .. }))); + assert_eq!(s.style.fill, Rgba::hex(0xff8800), "the swatch shows the first colour"); + let b = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 200, "h": 40, "stroke": null}))["element"].as_u64().unwrap(); + assert!(near(&stage_frame(&s, b), &Affine { m: [100.0, 0.0, 0.0, 100.0, 400.0, 320.0] }), "{:?}", stage_frame(&s, b)); + // Undo puts the solid colour back. + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0xff0000)))); +} + +#[test] +fn editing_stops_keeps_where_a_gradient_lies() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + // A white-to-black ring round the square's centre, touching its sides. + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + run(&mut s, "paint.transform_fill", json!({"move": [10, 0], "scale_x": 2})); + let moved = stage_frame(&s, a); + // New stops, overflow and focal point: the ring stays put. + let stops: Value = serde_json::from_str(RAMP).unwrap(); + run(&mut s, "paint.set_fill", json!({"stops": stops, "spread": "repeat", "focal": 0.5})); + assert!(near(&stage_frame(&s, a), &moved)); + match shape(&s, a).0.fill { + Some(Paint::Radial { stops, spread, focal, .. }) => assert_eq!((stops.len(), spread, focal), (3, Spread::Repeat, 0.5)), + other => panic!("{other:?}"), + } + // Changing kind fits it again; back to solid, and the swatch is solid too. + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + assert!(matches!(shape(&s, a).0.fill, Some(Paint::Linear { spread: Spread::Repeat, .. })), "the gradient keeps its colours and overflow"); + run(&mut s, "paint.set_fill", json!({"type": "solid", "color": "#00ff00"})); + assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0x00ff00)))); + assert!(s.style.fill_paint.is_none()); +} + +#[test] +fn set_fill_checks_its_params() { + let mut s = Session::default(); + square(&mut s, 100.0); + for bad in [ + json!({"type": "conic"}), + json!({"stops": [{"offset": 0, "color": "#ff0000"}]}), + json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1.5, "color": "#ff0000"}]}), + json!({"stops": [{"offset": 0, "color": "red"}, {"offset": 1, "color": "#ff0000"}]}), + json!({"stops": (0..16).map(|i| json!({"offset": i as f32 / 15.0, "color": "#000000"})).collect::>()}), + json!({"spread": "mirror"}), + json!({"focal": 1.0}), + json!({"type": "bitmap"}), + json!({"type": "bitmap", "bitmap": 999}), + ] { + let before = s.doc.clone(); + assert!(s.execute("paint.set_fill", &bad).is_err(), "{bad}"); + assert!(s.doc == before, "{bad} changed nothing"); + } + // Unselected: only the swatch. + s.selection.clear(); + let r = run(&mut s, "paint.set_fill", json!({"type": "radial"})); + assert_eq!(r["changed"], 0); + assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. }))); +} + +#[test] +fn transform_fill_moves_turns_scales_and_skews_analytically() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + let f0 = stage_frame(&s, a); + // Scale along the gradient (its own x), then turn 90° about its centre, then move. + run(&mut s, "paint.transform_fill", json!({"scale_x": 0.5, "rotate": 90, "move": [5, -5]})); + let want = Affine::translate(5.0, -5.0).mul(&Affine::translate(150.0, 150.0)).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::translate(-150.0, -150.0)).mul(&f0).mul(&Affine::scale(0.5, 1.0)); + let got = stage_frame(&s, a); + // A linear gradient keeps only its axis: compare the ends. + for x in [-1.0, 1.0] { + assert!(got.apply(Vec2::new(x, 0.0)).distance(want.apply(Vec2::new(x, 0.0))) < 1e-3, "{got:?} vs {want:?}"); + } + match shape(&s, a).0.fill { + Some(Paint::Linear { start, end, .. }) => { + assert!(start.distance(Vec2::new(5.0, -30.0)) < 1e-3 && end.distance(Vec2::new(5.0, 20.0)) < 1e-3, "{start:?} {end:?}"); + } + other => panic!("{other:?}"), + } + // A radial gradient takes any frame: skew and an absolute frame are kept exactly. + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + let f1 = stage_frame(&s, a); + run(&mut s, "paint.transform_fill", json!({"skew_x": 30, "focal": -0.25})); + let want = f1.mul(&Affine { m: [1.0, 0.0, 30f32.to_radians().tan(), 1.0, 0.0, 0.0] }); + assert!(near(&stage_frame(&s, a), &want), "{:?}", stage_frame(&s, a)); + assert!(matches!(shape(&s, a).0.fill, Some(Paint::Radial { focal, .. }) if focal == -0.25)); + let frame = [40.0, 10.0, -5.0, 20.0, 160.0, 140.0]; + let r = run(&mut s, "paint.transform_fill", json!({"element": a, "frame": frame})); + assert_eq!(r["changed"], 1); + assert!(near(&stage_frame(&s, a), &Affine { m: frame })); + // The result reports the frames, so a script can carry on from them. + assert_eq!(r["frames"][0].as_array().map(Vec::len), Some(6)); +} + +#[test] +fn transform_fill_turns_bitmap_fills_and_refuses_what_it_cannot_do() { + let mut s = Session::default(); + // A 4 × 2 bitmap from the library, poured into a square. + let png = anicraft_render::encode_png(4, 2, &[255; 32]).unwrap(); + let id = s.doc.alloc_id(); + s.doc.bitmaps.push(std::sync::Arc::new(anicraft_doc::Bitmap::from_png(anicraft_doc::BitmapId(id), "tile.png", png).unwrap())); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "bitmap", "bitmap": id})); + let (sh, m) = shape(&s, a); + let fill = sh.fill.clone().unwrap(); + let frame = |s: &Session| { + let (sh, m) = shape(s, a); + let f = sh.fill.unwrap(); + m.mul(&f.frame(Some((4.0, 2.0))).unwrap()) + }; + // Tiled from the square's top-left at its own size. + assert!(near(&m.mul(&fill.frame(Some((4.0, 2.0))).unwrap()), &Affine { m: [2.0, 0.0, 0.0, 1.0, 102.0, 101.0] })); + let f0 = frame(&s); + let steps = s.history_len(); + run(&mut s, "paint.transform_fill", json!({"scale": 3, "skew_y": 20, "rotate": -45})); + assert_eq!(s.history_len(), steps + 1, "one step"); + let c = f0.apply(Vec2::ZERO); + let want = Affine::translate(c.x, c.y).mul(&Affine::rotate(-std::f32::consts::FRAC_PI_4)).mul(&Affine::translate(-c.x, -c.y)).mul(&f0).mul(&Affine::scale(3.0, 3.0)).mul(&Affine { m: [1.0, 20f32.to_radians().tan(), 0.0, 1.0, 0.0, 0.0] }); + assert!(near(&frame(&s), &want), "{:?} vs {want:?}", frame(&s)); + // Nothing to flatten a fill to, nor a solid fill to transform. + let before = s.doc.clone(); + assert!(s.execute("paint.transform_fill", &json!({"frame": [1, 0, 2, 0, 0, 0]})).is_err()); + assert!(s.execute("paint.transform_fill", &json!({"scale_x": 0})).is_err()); + assert!(s.execute("paint.transform_fill", &json!({"skew_x": 90})).is_err()); + assert!(s.doc == before); + let b = square(&mut s, 300.0); + assert!(s.execute("paint.transform_fill", &json!({"element": b, "move": [1, 1]})).is_err(), "a solid fill has no gradient to move"); + s.selection.clear(); + assert!(s.execute("paint.transform_fill", &json!({"move": [1, 1]})).is_err(), "nothing selected"); +} + +#[test] +fn lock_fill_runs_one_gradient_across_shapes() { + let mut s = Session::default(); + s.selection.clear(); + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + // The swatch spans the stage, left to right. + let w = s.doc.stage.width as f32; + match &s.style.fill_paint { + Some(Paint::Linear { start, end, .. }) => assert_eq!((start.x, end.x), (0.0, w)), + other => panic!("{other:?}"), + } + // Unlocked (the default), each shape gets its own ramp. + let a = poured(&mut s, 100.0); + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + // Locked, the swatch's ramp across the stage, in each shape's own space. + let r = run(&mut s, "paint.lock_fill", json!({})); + assert_eq!(r["on"], true); + let b = poured(&mut s, 300.0); + let f = stage_frame(&s, b); + assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3 && (f.apply(Vec2::new(1.0, 0.0)).x - w).abs() < 1e-3, "{f:?}"); + // The Paint Bucket follows it too: a click on the unlocked square locks its ramp to the stage. + run(&mut s, "paint.bucket", json!({"x": 150, "y": 150})); + let f = stage_frame(&s, a); + assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3, "{f:?}"); + assert_eq!(run(&mut s, "paint.lock_fill", json!({"on": false}))["on"], false); + run(&mut s, "paint.bucket", json!({"x": 350, "y": 150})); + assert!(near(&stage_frame(&s, b), &Affine { m: [50.0, 0.0, 0.0, 50.0, 350.0, 150.0] })); + assert!(s.execute("paint.lock_fill", &json!({"on": "yes"})).is_err()); +} + +#[test] +fn a_raw_fill_keeps_its_id_through_a_drag_of_its_gradient() { + // The editor draws raw (merge) shapes; the Gradient Transform tool addresses one by id + // through every step of a drag, so moving where its fill lies never re-merges it. + let mut s = Session::default(); + s.style.object_drawing = false; + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + let id = s.selection.id_list().first().copied().unwrap_or(a); + for k in 1..=3 { + let r = run(&mut s, "paint.transform_fill", json!({"element": id, "frame": [50.0 + 10.0 * k as f32, 0, 0, 50, 150, 150]})); + assert_eq!(r["changed"], 1, "step {k}"); + } + assert!(near(&stage_frame(&s, id), &Affine { m: [80.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); +} diff --git a/crates/engine/src/group_tests.rs b/crates/engine/src/group_tests.rs new file mode 100644 index 00000000..bf1221fb --- /dev/null +++ b/crates/engine/src/group_tests.rs @@ -0,0 +1,365 @@ +//! Groups and Combine Objects (ADR 0073). + +use crate::Session; +use crate::cmds_group::even_odd_area; +use anicraft_doc::{Element, ElementId, 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}")) +} + +fn id_of(v: &Value, key: &str) -> ElementId { + ElementId(v[key].as_u64().unwrap_or_else(|| panic!("no {key} in {v}"))) +} + +fn top(s: &Session) -> Vec> { + s.visible_elements() +} + +/// Every drawn item's transform, path and fill, in order: what the movie shows, exactly. +fn picture(s: &Session) -> Vec<([u32; 6], usize, String)> { + let dl = anicraft_doc::evaluate_scene(&s.doc, s.scene, s.frame); + dl.items.iter().map(|i| (i.transform.m.map(f32::to_bits), i.path.cmds.len(), format!("{:?}{:?}{:?}", i.fill, i.stroke, i.color))).collect() +} + +/// Three objects: a rotated, scaled red square, a blue oval and a green star; Object Drawing on. +fn three() -> (Session, [ElementId; 3]) { + let mut s = Session::new(anicraft_doc::Document::default()); + let a = run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 60, "fill": "#ff0000", "stroke": "#000000"})); + let a = id_of(&a, "element"); + run(&mut s, "element.set_transform", json!({"rotation": 33.0, "sx": 1.3, "sy": 0.7})); + let b = id_of(&run(&mut s, "draw.ellipse", json!({"x": 140, "y": 50, "w": 80, "h": 50, "fill": "#0000ff"})), "element"); + let c = id_of(&run(&mut s, "draw.star", json!({"cx": 300, "cy": 200, "outer": 40, "fill": "#00ff00"})), "element"); + (s, [a, b, c]) +} + +#[test] +fn group_and_ungroup_keep_every_members_place_exactly() { + let (mut s, ids) = three(); + let before = picture(&s); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + let v = run(&mut s, "modify.group", json!({})); + let g = id_of(&v, "group"); + assert_eq!(v["members"], json!(3)); + assert_eq!(top(&s).len(), 1, "one group on the layer"); + assert_eq!(s.selection.id_list(), vec![g.0]); + assert_eq!(picture(&s), before, "grouping changes nothing drawn"); + // Picking anything in it picks the group. + assert_eq!(s.hit_test(Vec2::new(300.0, 200.0), 1.0).map(|x| x.1), Some(g)); + // One undo step. + run(&mut s, "edit.undo", json!({})); + assert_eq!(top(&s).len(), 3); + run(&mut s, "edit.redo", json!({})); + // Moved and scaled as one, then ungrouped: each member is where the group showed it, bit for bit. + run(&mut s, "modify.transform", json!({"a": 1.5, "b": 0.2, "c": -0.1, "d": 0.8, "e": 12.5, "f": -7.25})); + let moved = picture(&s); + let v = run(&mut s, "modify.ungroup", json!({})); + assert_eq!(v["members"], json!(3)); + assert_eq!(picture(&s), moved, "ungrouping changes nothing drawn"); + let back: Vec = top(&s).iter().map(|e| e.id).collect(); + assert_eq!(back, ids.to_vec(), "members keep their ids and order"); + assert_eq!(s.selection.id_list().len(), 3); +} + +#[test] +fn groups_nest_and_take_the_topmost_members_place() { + let (mut s, [a, b, c]) = three(); + let before = picture(&s); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + let g1 = id_of(&run(&mut s, "modify.group", json!({})), "group"); + // The group stands where its topmost member stood: under the star. + assert_eq!(top(&s).iter().map(|e| e.id).collect::>(), vec![g1, c]); + run(&mut s, "element.select", json!({"ids": [g1.0, c.0]})); + let g2 = id_of(&run(&mut s, "modify.group", json!({})), "group"); + assert_eq!(picture(&s), before); + assert_eq!(crate::cmds_group::group_depth(&top(&s)[0]), 2); + // Break Apart on a group ungroups it, one level. + run(&mut s, "element.select", json!({"ids": [g2.0]})); + run(&mut s, "modify.break_apart", json!({})); + assert_eq!(top(&s).len(), 2); + assert_eq!(picture(&s), before); + // Ungroup a group that holds nothing selected says so. + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("modify.ungroup", &json!({})).is_err()); +} + +#[test] +fn a_group_opens_in_place_and_edits_there_with_every_tool() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + let g = id_of(&run(&mut s, "modify.group", json!({})), "group"); + run(&mut s, "modify.transform", json!({"a": 1, "b": 0, "c": 0, "d": 1, "e": 100, "f": 50})); + let steps = s.history_len(); + let v = run(&mut s, "symbol.edit", json!({"id": g.0})); + assert_eq!(v["editing"][0]["group"], json!(g.0), "{v}"); + assert!(s.editing_group() && s.editing_symbol().is_none()); + assert_eq!(s.history_len(), steps, "opening is not an edit"); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(view.in_place && view.origin.distance(Vec2::new(100.0, 50.0)) < 1e-4, "{view:?}"); + // Inside: the members, in the group's space. + assert_eq!(top(&s).len(), 3); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#123456"})); + assert_eq!(top(&s).len(), 4); + // A group is one layer and one frame. + assert!(s.execute("layer.new", &json!({})).is_err()); + assert!(s.execute("timeline.insert_keyframe", &json!({})).is_err()); + let _ = s.execute("timeline.goto", &json!({"frame": 5})); + assert_eq!(s.frame, 0, "the playhead stays on the group's frame"); + // The stage shows the edit where the group stands, the rest dimmed. + let pic = s.stage_picture(); + assert!(pic.front.is_some()); + run(&mut s, "symbol.exit", json!({})); + assert_eq!(s.selection.id_list(), vec![g.0], "the group is selected again"); + let members = top(&s)[0].kind.group_members(); + assert_eq!(members.len(), 4); + let new = members.last().cloned().unwrap_or_else(|| panic!("member")); + // The new rectangle sits at (100, 50) + its place inside, on the stage. + let b = s.element_bounds(g); + assert!(b.min.x <= 100.5 && b.min.y <= 50.5, "{b:?}"); + assert!(matches!(new.kind, ElementKind::Shape(_))); + // Undo goes back inside, where the change was made. + run(&mut s, "edit.undo", json!({})); + assert!(s.editing_group()); + assert_eq!(top(&s).len(), 3); + // An ungroup undone from inside closes the group when it goes. + run(&mut s, "symbol.exit", json!({})); + run(&mut s, "modify.ungroup", json!({})); + assert!(s.editing.is_empty()); +} + +#[test] +fn raw_shapes_in_a_group_merge_only_with_each_other() { + 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": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + let g = id_of(&run(&mut s, "modify.group", json!({})), "group"); + // A raw square drawn over it leaves the grouped square whole. + run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + let group = top(&s).into_iter().find(|e| e.id == g).unwrap_or_else(|| panic!("group")); + let m = group.kind.group_members(); + assert_eq!(m.len(), 1); + let ElementKind::Shape(sh) = &m[0].kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &m[0].transform) - 10_000.0).abs() < 1.0); + // The group sits above the raw drawing, as objects do... and inside, a raw square merges. + run(&mut s, "symbol.edit", json!({"id": g.0})); + run(&mut s, "draw.rect", json!({"x": 50, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + let fills = top(&s); + assert_eq!(fills.len(), 1, "one red fill: the two squares joined"); + run(&mut s, "symbol.exit", json!({})); + // Ungrouped, the red fill merges with the blue square it now stands in. + run(&mut s, "modify.ungroup", json!({})); + let raw = top(&s); + assert!(raw.iter().all(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)), "all raw"); + let red: f64 = raw.iter().filter_map(|e| match &e.kind { + ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0xff0000))) => Some(even_odd_area(&sh.path, &e.transform)), + _ => None, + }).sum(); + // Red (150 × 100) on top of blue: all of it shows. + assert!((red - 15_000.0).abs() < 2.0, "{red}"); +} + +#[test] +fn copies_of_a_group_ungroup_with_their_own_ids() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "edit.duplicate", json!({"dx": 10, "dy": 10})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.ungroup", json!({})); + let all: Vec = top(&s).iter().map(|e| e.id.0).collect(); + let mut unique = all.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!((all.len(), unique.len()), (6, 6), "{all:?}"); +} + +#[test] +fn groups_save_and_open_and_older_files_have_none() { + let (mut s, ids) = three(); + let plain = crate::format::to_json(&s.doc).unwrap_or_default(); + assert!(!plain.contains("Group"), "nothing new in files without groups"); + run(&mut s, "element.select", json!({"ids": [ids[0].0, ids[1].0]})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "element.select", json!({"ids": [ids[2].0]})); + let text = crate::format::to_json(&s.doc).unwrap_or_default(); + let back = crate::format::from_json(&text).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back, s.doc); + // Ids inside groups count: what a loaded document makes next is new. + let mut d = back.clone(); + let next = d.alloc_id(); + assert!(next > ids.iter().map(|i| i.0).max().unwrap_or(0)); +} + +#[test] +fn symbols_inside_groups_count_as_used_and_go_with_their_symbol() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + let sym = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"}))["symbol"].as_u64().unwrap_or(0); + run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 50, "h": 50, "fill": "#00ff00"})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.group", json!({})); + assert!(s.doc.unused_items().is_empty(), "the instance inside the group uses it"); + assert_eq!(s.doc.library_uses().len(), 1); + // Deleting the symbol takes its instance out of the group, and keeps the rest. + run(&mut s, "library.delete", json!({"items": [{"symbol": sym}], "confirm": true})); + let g = top(&s); + assert_eq!(g.len(), 1); + assert_eq!(g[0].kind.group_members().len(), 1); +} + +/// Two 100 × 100 squares, overlapping by 50 × 50, as drawing objects; the second on top. +fn squares(s: &mut Session) { + run(s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + run(s, "edit.select_all", json!({})); +} + +fn areas(s: &Session) -> Vec { + top(s) + .iter() + .map(|e| match &e.kind { + ElementKind::Shape(sh) => even_odd_area(&sh.path, &e.transform), + ElementKind::Group { .. } => e.kind.group_members().iter().filter_map(|m| match &m.kind { + ElementKind::Shape(sh) if sh.fill.is_some() => Some(even_odd_area(&sh.path, &e.transform.mul(&m.transform))), + _ => None, + }).sum(), + _ => 0.0, + }) + .collect() +} + +#[test] +fn combine_objects_areas_are_exact() { + let near = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5); + // Union of two colours: a group of the merged pieces, whose area is the union's. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + let v = run(&mut s, "modify.combine", json!({"op": "union"})); + assert_eq!(v["created"].as_array().map(Vec::len), Some(1)); + assert!(matches!(top(&s)[0].kind, ElementKind::Group { .. })); + assert!(near(&areas(&s), &[17_500.0]), "{:?}", areas(&s)); + // Intersect: the overlap, in the top's colour. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.intersect", json!({})); + assert!(near(&areas(&s), &[2_500.0]), "{:?}", areas(&s)); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0x0000ff))) && !sh.merge)); + // Punch: the bottom square less the top one, which goes. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.punch", json!({})); + assert!(near(&areas(&s), &[7_500.0]), "{:?}", areas(&s)); + // Crop: the bottom square inside the top one. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.crop", json!({})); + assert!(near(&areas(&s), &[2_500.0]), "{:?}", areas(&s)); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0xff0000))))); + // Union of one colour: one drawing object. + let mut s = Session::new(anicraft_doc::Document::default()); + 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": 50, "y": 50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.union", json!({})); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if !sh.merge), "one object"); + assert!(near(&areas(&s), &[17_500.0]), "{:?}", areas(&s)); + // A hole punched in the middle: a ring, 100² − 40². + let mut s = Session::new(anicraft_doc::Document::default()); + 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": 30, "y": 30, "w": 40, "h": 40, "fill": "#0000ff", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.punch", json!({})); + assert!(near(&areas(&s), &[8_400.0]), "{:?}", areas(&s)); + // A circle cropped by a square through its centre: a quarter of π r² (cubic arcs: 0.03 %). + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.ellipse", json!({"x": -100, "y": -100, "w": 200, "h": 200, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200, "fill": "#0000ff", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.crop", json!({})); + let a = areas(&s); + let quarter = std::f64::consts::PI * 100.0 * 100.0 / 4.0; + assert!(a.len() == 1 && (a[0] - quarter).abs() < quarter * 0.001, "{a:?} vs {quarter}"); +} + +#[test] +fn combine_refuses_what_it_cannot_combine() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.union", &json!({})).is_err(), "one shape"); + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.intersect", &json!({})).is_err(), "apart: nothing in common"); + assert!(s.execute("modify.combine", &json!({"op": "xor"})).is_err()); + // The document is as it was after a refusal. + assert_eq!(top(&s).len(), 2); + // A line can't punch (it has no area). + run(&mut s, "draw.line", json!({"x0": 0, "y0": 50, "x1": 400, "y1": 50, "stroke": "#000000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.punch", &json!({})).is_err()); +} + +#[test] +fn ctrl_drag_pulls_a_sharp_corner_out_of_a_line() { + // What the Selection tool's Ctrl-drag runs (issue #200): a point where the edge was grabbed, + // then that point moved, in one gesture. + 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": 100, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + s.begin_gesture("Pull Corner"); + let v = run(&mut s, "raw.add_point", json!({"x": 50, "y": 0.4, "slop": 3})); + let (x, y) = (v["x"].as_f64().unwrap_or(-1.0), v["y"].as_f64().unwrap_or(-1.0)); + assert!((x - 50.0).abs() < 0.5 && y.abs() < 1e-3, "{v}"); + run(&mut s, "raw.move_point", json!({"x": x, "y": y, "to_x": 50, "to_y": -40, "merge": false})); + let ids: Vec = top(&s).iter().map(|e| e.id.0).collect(); + run(&mut s, "raw.merge", json!({"ids": ids})); + s.end_gesture(); + // The fill gained a triangle 100 wide and 40 high: straight sides meeting at a sharp point. + let fill = top(&s).into_iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).unwrap_or_else(|| panic!("fill")); + let ElementKind::Shape(sh) = &fill.kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &fill.transform) - 12_000.0).abs() < 0.5); + assert!(sh.path.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::CubicTo(..) | anicraft_geom::PathCmd::QuadTo(..))), "straight lines, no curve: {:?}", sh.path.cmds); + assert!(s.history_len() >= 2); + run(&mut s, "edit.undo", json!({})); + let fill = top(&s).into_iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).unwrap_or_else(|| panic!("fill")); + let ElementKind::Shape(sh) = &fill.kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &fill.transform) - 10_000.0).abs() < 0.5, "one undo step"); +} + +#[test] +fn alt_drag_copies_leave_the_original_whole() { + // What the Selection tool's Alt-drag runs: a copy in place, moved, dropped into the drawing. + 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": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "element.pick", json!({"x": 50, "y": 50})); + s.begin_gesture("Copy"); + run(&mut s, "edit.duplicate", json!({"dx": 0, "dy": 0})); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 0})); + run(&mut s, "draw.drop", json!({})); + s.end_gesture(); + let a: Vec = areas(&s); + assert!(a.len() == 2 && a.iter().all(|x| (x - 10_000.0).abs() < 0.5), "{a:?}"); +} + +#[test] +fn groups_draw_their_colour_effect_and_fade_as_one() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + let dl = s.display_list(); + assert_eq!(dl.groups.len(), 1, "a translucent group composites as one"); + assert!(dl.items.iter().all(|i| i.group == Some(0))); + assert!((dl.effective_alpha(&dl.items[0]) - 0.5).abs() < 1e-6); + // Placement composes: a member's item is the group's transform times its own. + let g = top(&s)[0].clone(); + let m = g.kind.group_members()[0].clone(); + let want = Affine::IDENTITY.mul(&g.transform).mul(&m.transform); + assert_eq!(dl.items[0].transform.m, want.m); +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 3ada0b02..e162610c 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -144,7 +144,7 @@ fn path_bytes(e: &Element) -> usize { match &e.kind { ElementKind::Shape(s) => size_of::() + s.path.cmds.len() * size_of::(), ElementKind::Text(t) => size_of::() + t.outline.cmds.len() * size_of::(), - ElementKind::Symbol { .. } | ElementKind::Camera => 0, + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => 0, } } @@ -158,6 +158,10 @@ fn element_bytes(e: &Element, shared_paths: &HashSet) -> usize { b += stops.len() * size_of::(); } } + // A group's members, as if each stood alone (ADR 0073; nesting is bounded by MAX_GROUP_DEPTH). + if let ElementKind::Group { .. } = &e.kind { + b += size_of::() + e.kind.group_members().iter().map(|m| element_bytes(m, shared_paths)).sum::(); + } if let ElementKind::Text(t) = &e.kind { b += size_of::() + t.text.len() + t.font.len(); if !shared_paths.contains(&ptr(&t.outline)) { @@ -176,7 +180,7 @@ fn keyframe_bytes(k: &Keyframe, other: Option<&Keyframe>) -> usize { .filter_map(|e| match &e.kind { ElementKind::Shape(s) => Some(ptr(&s.path)), ElementKind::Text(t) => Some(ptr(&t.outline)), - ElementKind::Symbol { .. } | ElementKind::Camera => None, + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => None, }) .collect() }) @@ -245,6 +249,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize { /// Estimated total bytes of a document (as if nothing were shared). Used for reporting. pub fn document_bytes(doc: &Document) -> usize { - let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: doc.next_id }; + let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), next_id: doc.next_id }; unique_bytes(doc, &empty) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a6972fe4..c8cb9b6d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,23 +5,32 @@ //! JSON params, so headless and interactive behaviour cannot drift apart. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod anim; mod cmds_actions; mod cmds_bone; +mod cmds_warp; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; +pub mod cmds_envelope; +pub mod cmds_drop; pub mod cmds_erase; mod cmds_file; mod cmds_frames; +mod cmds_group; mod cmds_modify; mod cmds_motion; mod cmds_hints; +mod cmds_layer; pub mod cmds_library; -mod cmds_paint; +pub mod cmds_paint; mod cmds_path; pub mod cmds_raw; pub mod cmds_rawsub; mod cmds_rawpoints; +pub mod brush_library; +pub mod cmds_recent; +pub mod cmds_template; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -29,10 +38,14 @@ mod cmds_scene; pub mod cmds_sound; pub mod cmds_text; mod cmds_timeline; +mod cmds_view; mod cmds_width; mod cmds_stroke; +pub mod cmds_swatch; pub mod confirm; pub mod editing; +pub mod explorer; +pub mod find; pub mod format; pub mod history; mod merge; @@ -41,8 +54,10 @@ pub mod onion; pub mod recovery; pub mod render_service; pub mod selection; +pub mod snap; pub mod params; pub mod player; +pub mod publish; pub mod vfs; use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, evaluate_layer_elements, evaluate_scene}; @@ -58,6 +73,9 @@ pub use anicraft_plugins as plugins; pub use anicraft_text as text; pub use anicraft_geom as geom; pub use anicraft_render as render; +/// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open` +/// imports. +pub use cmds_file::is_animate; #[derive(Debug, thiserror::Error)] pub enum EngineError { @@ -75,6 +93,9 @@ pub enum EngineError { Render(#[from] anicraft_render::RenderError), #[error("{0}")] NeedsConfirmation(String), + /// A running publish was cancelled (ADR 0060). + #[error("cancelled")] + Cancelled, } pub type Result = std::result::Result; @@ -108,10 +129,16 @@ impl CommandSpec { pub fn commands() -> Vec { let mut v = Vec::new(); v.extend(cmds_file::specs()); + v.extend(cmds_envelope::specs()); + v.extend(publish::specs()); + v.extend(cmds_recent::specs()); + v.extend(cmds_drop::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); + v.extend(cmds_layer::specs()); v.extend(cmds_camera::specs()); v.extend(cmds_bone::specs()); + v.extend(cmds_warp::specs()); v.extend(cmds_motion::specs()); v.extend(cmds_hints::specs()); v.extend(cmds_scene::specs()); @@ -119,6 +146,8 @@ pub fn commands() -> Vec { v.extend(onion::specs()); v.extend(multi::specs()); v.extend(cmds_draw::specs()); + v.extend(cmds_view::specs()); + v.extend(cmds_group::specs()); v.extend(cmds_library::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); @@ -127,9 +156,12 @@ pub fn commands() -> Vec { v.extend(cmds_rawsub::specs()); v.extend(cmds_rawpoints::specs()); v.extend(editing::specs()); + v.extend(find::specs()); + v.extend(explorer::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); + v.extend(cmds_swatch::specs()); v.extend(cmds_text::specs()); v.extend(cmds_width::specs()); v.extend(cmds_stroke::specs()); @@ -157,6 +189,13 @@ pub fn find_command(id: &str) -> Option { pub use history::{Snapshot, StateId}; pub use selection::Selection; +pub use snap::{Accuracy, SnapTo, ViewAids}; +pub use cmds_layer::LAYER_COLORS; + +/// The command namespaces that change a timeline's layers and frames, refused while a group is +/// open for editing (ADR 0073): a group is one layer and one frame. A name ending in `.` is a +/// namespace, any other one command. +const GROUP_REFUSES: &[&str] = &["timeline.", "layer.", "camera.", "bone.", "motion.", "tween.", "frames.", "sound.place", "script.set", "script.clear"]; /// Last addressable frame (0-based); about 70 minutes at 24 fps. pub const MAX_FRAME: u32 = 100_000; @@ -186,9 +225,13 @@ pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize #[derive(Clone, Debug)] pub struct ToolStyle { pub fill: anicraft_doc::Rgba, - /// The fill swatch holds a gradient or a bitmap (picked with the Eyedropper, ADR 0034), in - /// stage space; `fill` is then its representative colour. `None`: the solid `fill`. + /// The fill swatch holds a gradient or a bitmap (set in the Colour panel or picked with the + /// Eyedropper, ADR 0034 and 0074), in stage space; `fill` is then its representative colour. + /// `None`: the solid `fill`. pub fill_paint: Option, + /// Lock Fill (ADR 0074): a gradient or bitmap from the swatch is poured where it lies on the + /// stage, so it runs on across shapes. Off, each shape gets it fitted to its own bounds. + pub lock_fill: bool, pub stroke: anicraft_doc::Rgba, pub stroke_width: f32, pub use_fill: bool, @@ -210,7 +253,7 @@ pub struct ToolStyle { 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, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true } + ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, lock_fill: false, 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 } } } @@ -219,6 +262,13 @@ impl ToolStyle { pub fn fill_paint(&self) -> anicraft_doc::Paint { self.fill_paint.clone().unwrap_or(anicraft_doc::Paint::Solid(self.fill)) } + /// The fill swatch's paint for a shape whose space is `to_local` from the stage and whose + /// outline has the local `bounds`: with Lock Fill, the stage-space paint carried into the + /// shape; without, a gradient or bitmap fitted to the bounds (as Animate pours them). + pub fn fill_paint_for(&self, to_local: &anicraft_geom::Affine, bounds: &anicraft_geom::Rect) -> anicraft_doc::Paint { + let paint = self.fill_paint(); + if self.lock_fill || matches!(paint, anicraft_doc::Paint::Solid(_)) { paint.transformed(to_local) } else { paint.fitted(bounds) } + } /// Sets the fill swatch to a solid colour (dropping a picked gradient or bitmap). pub fn set_fill_color(&mut self, c: anicraft_doc::Rgba) { self.fill = c; @@ -232,10 +282,6 @@ impl ToolStyle { 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; @@ -245,7 +291,7 @@ impl ToolStyle { /// An open document plus everything the editor tracks about it. /// A display list and the `(state, scene, frame, open symbol)` it was evaluated for. -type CachedList = (StateId, usize, u32, Option, Arc); +type CachedList = (StateId, usize, u32, Option<(editing::Opened, Option<(LayerId, ElementId)>, usize)>, Arc); pub struct Session { /// The document: a persistent tree, so cloning it (undo, render thread) is cheap. @@ -268,6 +314,9 @@ pub struct Session { saved_state: Option, pub path: Option, pub style: ToolStyle, + /// Whether the rulers, grid and guides show and snap (ADR 0076): the editor's, not the + /// document's. + pub aids: ViewAids, /// The style new text gets (the last one used). pub text_style: cmds_text::TextStyle, history: History, @@ -294,8 +343,25 @@ pub struct Session { pub(crate) pending_cut: Option<(CutOrigin, Vec)>, /// The open gesture began on a provisional cut: the document with the cut. gesture_cut: Option, + /// How a button open for editing shows its hit area over its other states (ADR 0057): the + /// tint and opacity, or `None` for no overlay (the default; the app sets it from its theme). + /// View state, like the playhead: never in the document or its undo history. + pub hit_area: Option<(anicraft_doc::Rgba, f32)>, /// The last picture of an open symbol in place, by its key (ADR 0045). picture_cache: RefCell)>>, + /// A publish this session runs: its Cancel and frame count, which exports check (ADR 0060). + pub job: Option>, + /// Files this session's publishes wrote: publishing again replaces them without asking. + pub published: std::collections::BTreeSet, + /// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the + /// session, not the document: they survive New and Open. The desktop app keeps them in its + /// preferences. + pub recent: cmds_recent::RecentFiles, + /// The user's own brush presets (ADR 0068). Like recent files they belong to the session + /// and survive New and Open; the desktop app keeps them in its preferences. + pub brushes: brush_library::BrushLibrary, + /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. + pub(crate) envelope: Option, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -348,6 +414,7 @@ impl Session { saved_state: Some(state), path: None, style: ToolStyle::default(), + aids: ViewAids::default(), text_style: cmds_text::TextStyle::default(), history: History::default(), gesture: None, @@ -360,7 +427,13 @@ impl Session { provisional: None, pending_cut: None, gesture_cut: None, + hit_area: None, picture_cache: RefCell::new(None), + job: None, + published: std::collections::BTreeSet::new(), + recent: cmds_recent::RecentFiles::default(), + brushes: brush_library::BrushLibrary::default(), + envelope: None, } } @@ -442,7 +515,11 @@ impl Session { let budget = self.history.budget_bytes; let clipboard = std::mem::take(&mut self.clipboard); let plugins = std::mem::take(&mut self.plugins); + let recent = std::mem::take(&mut self.recent); + let brushes = std::mem::take(&mut self.brushes); *self = Session::new(doc); + self.recent = recent; + self.brushes = brushes; // The clipboard survives New/Open, so artwork can move between documents. self.clipboard = clipboard; self.plugins = plugins; @@ -462,10 +539,15 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } + // A group open for editing is one layer and one frame (ADR 0073). + if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { + return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); + } self.settle_cut(id, params); if !spec.mutates { let r = (spec.run)(self, params); self.settle_cut(id, params); + self.hold_group_frame(); return r; } // An edit on a marquee's cut records its step from before the cut (ADR 0041). @@ -516,6 +598,7 @@ impl Session { } } self.fix_selection(); + self.hold_group_frame(); Ok(v) } Err(e) => { @@ -526,6 +609,14 @@ impl Session { } } + /// Inside a group (ADR 0073) the playhead stays on its only frame. + fn hold_group_frame(&mut self) { + if self.frame != 0 && self.editing_group() { + self.frame = 0; + self.fix_selection(); + } + } + /// 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()) @@ -724,7 +815,7 @@ impl Session { /// The current scene evaluated at the playhead, cached per `(state, scene, frame)`. pub fn display_list(&self) -> Arc { - let open = self.editing_symbol(); + let open = self.editing.last().map(|l| (l.open, l.instance, self.editing.len())); if let Some((s, sc, f, o, dl)) = &*self.dl_cache.borrow() && *s == self.state && *sc == self.scene @@ -733,11 +824,8 @@ impl Session { { return dl.clone(); } - // An open symbol is edited in its own space (ADR 0045). - let dl = Arc::new(match open.and_then(|id| self.doc.symbol(id)) { - Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, self.frame), - None => evaluate_scene(&self.doc, self.scene, self.frame), - }); + // An open symbol (ADR 0045) or group (ADR 0073) is edited in its own space. + let dl = Arc::new(if open.is_some() { anicraft_doc::evaluate_timeline(&self.doc, self.timeline(), self.frame) } else { evaluate_scene(&self.doc, self.scene, self.frame) }); self.dl_cache.replace(Some((self.state, self.scene, self.frame, open, dl.clone()))); dl } @@ -777,7 +865,7 @@ impl Session { pub(crate) fn layer_mut(&mut self, id: Option) -> Result<&mut Layer> { let id = id.unwrap_or(self.layer); - crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) + crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing)?.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) } /// The keyframe on the active layer that edits at the playhead should change. Creates a @@ -808,7 +896,7 @@ impl Session { } // Through the fields, not `layer_mut`, so `motion_edit` can be set below. let (scene, active) = (self.scene, self.layer); - let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; + let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing)?.layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; if layer.locked { return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); } @@ -894,6 +982,30 @@ pub(crate) enum KeyEdit { Pose, } +/// A colour effect as commands report it (ADR 0056): its style and that style's values, in the +/// units `element.set_color_effect` takes (percent; Advanced offsets −255..255). +pub fn color_effect_json(fx: &anicraft_doc::ColorEffect) -> serde_json::Value { + use anicraft_doc::ColorEffect; + let r = |v: f32, k: f32| f64::from((v * k * 100.0).round() / 100.0); + let mut v = serde_json::json!({"style": fx.style().key()}); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => v["alpha"] = r(a, 100.0).into(), + ColorEffect::Brightness(b) => v["brightness"] = r(b, 100.0).into(), + ColorEffect::Tint { color, amount } => { + v["tint"] = color.to_hex().into(); + v["tint_amount"] = r(amount, 100.0).into(); + } + ColorEffect::Advanced(t) => { + for (i, ch) in ["red", "green", "blue", "alpha"].iter().enumerate() { + v[format!("{ch}_multiplier")] = r(t.mul.get(i).copied().unwrap_or(1.0), 100.0).into(); + v[format!("{ch}_offset")] = r(t.add.get(i).copied().unwrap_or(0.0), 255.0).into(); + } + } + } + v +} + /// Short human label for an element (properties panel, library, CLI). pub fn element_label(doc: &Document, e: &Element) -> String { let kind = match &e.kind { @@ -907,6 +1019,14 @@ pub fn element_label(doc: &Document, e: &Element) -> String { None => "Graphic: missing".to_string(), }, ElementKind::Camera => "Camera".to_string(), + ElementKind::Group { .. } => "Group".to_string(), + // An empty field (an input field waiting for the viewer) is named by its type. + ElementKind::Text(t) if t.text.trim().is_empty() => match t.kind() { + anicraft_doc::TextKind::Static => "Static text", + anicraft_doc::TextKind::Dynamic => "Dynamic text", + anicraft_doc::TextKind::Input => "Input text", + } + .to_string(), ElementKind::Text(t) => { let first: String = t.text.lines().next().unwrap_or("").chars().take(24).collect(); format!("Text: {first}{}", if t.text.chars().count() > first.chars().count() { "…" } else { "" }) @@ -921,6 +1041,8 @@ mod tests; #[cfg(test)] mod motion_tests; #[cfg(test)] +mod color_tests; +#[cfg(test)] mod motion_path_tests; #[cfg(test)] mod motion_pin_tests; @@ -939,6 +1061,10 @@ mod tests_camera; #[cfg(test)] mod tests_bone; #[cfg(test)] +mod tests_shape_bone; +#[cfg(test)] +mod tests_warp; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; @@ -951,10 +1077,36 @@ mod editing_tests; #[cfg(test)] mod brush_tests; #[cfg(test)] +mod brush_library_tests; +#[cfg(test)] mod web_tests; #[cfg(test)] mod erase_tests; #[cfg(test)] mod eyedropper_tests; #[cfg(test)] +mod gradient_tests; +#[cfg(test)] mod selection_tests; +#[cfg(test)] +mod scale_grid_tests; +#[cfg(test)] +mod drop_tests; +#[cfg(test)] +mod template_tests; +#[cfg(test)] +mod timeline_drop_tests; +#[cfg(test)] +mod timeline_key_tests; +#[cfg(test)] +mod tests_bone_chain; +#[cfg(test)] +mod view_tests; +#[cfg(test)] +mod path_text_tests; +#[cfg(test)] +mod group_tests; +#[cfg(test)] +mod swatch_tests; +#[cfg(test)] +mod parity_tests; diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 3e41aca4..114ca901 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -197,7 +197,7 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt 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: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), 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, warp: None }), })); } Some(Remerged { out, picked, inside, from }) @@ -245,13 +245,20 @@ fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) -> } /// Whether two paints look the same (positions within a thousandth of a unit). -pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool { +pub(crate) fn same_paint(x: &Paint, y: &Paint) -> bool { const EPS: f32 = 1e-3; let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS; - match (a, b) { + match (x, y) { (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::Linear { start: s0, end: e0, stops: a, spread: p0, linear_rgb: l0 }, Paint::Linear { start: s1, end: e1, stops: b, spread: p1, linear_rgb: l1 }) => near(*s0, *s1) && near(*e0, *e1) && a == b && p0 == p1 && l0 == l1, + (Paint::Radial { stops: a, spread: p0, linear_rgb: l0, focal: f0, .. }, Paint::Radial { stops: b, spread: p1, linear_rgb: l1, focal: f1, .. }) => { + // The same ring: the frames agree (centre, axes and size). + let same_frame = match (x.frame(None), y.frame(None)) { + (Some(m0), Some(m1)) => m0.m.iter().zip(m1.m).all(|(u, v)| (u - v).abs() <= EPS * u.abs().max(v.abs()).max(1.0)), + _ => false, + }; + same_frame && a == b && p0 == p1 && l0 == l1 && (f0 - f1).abs() <= EPS + } (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)) } @@ -272,6 +279,11 @@ fn index_of(table: &mut Vec, 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 { + drop_selected(s) +} + +/// [`drop`] on the active layer (also when an envelope closes, ADR 0080). +pub(crate) fn drop_selected(s: &mut Session) -> Result { let sel = s.selection.on(s.layer); let kf = s.editable_keyframe()?; let mut moving = Vec::new(); @@ -380,8 +392,28 @@ pub(crate) fn merge_document(doc: &mut Document) -> usize { } fn merge_timeline(doc: &mut Document, tl: &mut Timeline) -> usize { + merge_timeline_at(doc, tl, 0) +} + +/// [`merge_timeline`], inside groups too (ADR 0073): a group's raw shapes merge with each other. +fn merge_timeline_at(doc: &mut Document, tl: &mut Timeline, depth: usize) -> usize { let mut n = 0; + let is_group = |e: &Element| matches!(e.kind, ElementKind::Group { .. }); for layer in tl.layers.iter_mut() { + if depth < anicraft_doc::MAX_GROUP_DEPTH && layer.keyframes.iter().any(|k| k.elements.iter().any(|e| is_group(e))) { + let layer = Arc::make_mut(layer); + for kf in layer.keyframes.iter_mut().filter(|k| k.elements.iter().any(|e| is_group(e))) { + for e in Arc::make_mut(kf).elements.iter_mut().filter(|e| is_group(e)) { + let ElementKind::Group { members } = &e.kind else { continue }; + let mut members = members.clone(); + let k = merge_timeline_at(doc, &mut members, depth + 1); + if k > 0 { + Arc::make_mut(e).kind = ElementKind::Group { members }; + n += k; + } + } + } + } if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| mergeable(e).is_some())) { continue; } diff --git a/crates/engine/src/motion_tests.rs b/crates/engine/src/motion_tests.rs index dc7206cd..7f707024 100644 --- a/crates/engine/src/motion_tests.rs +++ b/crates/engine/src/motion_tests.rs @@ -95,7 +95,7 @@ fn transforms_and_colour_edits_key_their_own_properties() { assert!(m.track(Property::ScaleY).is_none() && m.track(Property::X).is_none()); s.set_frame(4); let e = s.visible_elements()[0].clone(); - assert!((e.color.alpha - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); + assert!((e.color.alpha() - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); // Non-tweenable edits change the object itself, whatever the frame. run(&mut s, "edit.select_all", json!({})); run(&mut s, "element.set_fill", json!({"color": "#ff0000"})); diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs index dc2bac63..bd6ed5af 100644 --- a/crates/engine/src/multi_tests.rs +++ b/crates/engine/src/multi_tests.rs @@ -285,7 +285,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { let n = dl.items.len(); let (ghost, now) = (&dl.items[n - 2], &dl.items[n - 1]); assert_eq!((left(ghost), left(now)), (100.0, 140.0)); - assert!(ghost.color.alpha < 1.0 && ghost.color.tint_amount > 0.0 && now.color.alpha == 1.0); + assert!(ghost.color.mul[3] < 1.0 && ghost.color.changes_colour() && now.color.is_identity()); // The job does the same, keyed apart from the plain picture. let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None }; let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts)); @@ -295,7 +295,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { // Edit Multiple Frames shows both keyframes at full strength. let multi = OnionSkin { edit_multiple: true, markers: crate::onion::Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() }; let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi); - assert!(dl.items.iter().rev().take(2).all(|i| i.color.alpha == 1.0 && i.color.tint_amount == 0.0)); + assert!(dl.items.iter().rev().take(2).all(|i| i.color.is_identity())); // With nothing to add, the job draws the picture as it is. let off = make_off(&pic); assert_eq!(off.display_list().items.len(), plain.items.len()); diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index fd5a51a5..cc51e5e8 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -19,7 +19,7 @@ //! program; nothing was copied. use crate::{CommandSpec, MAX_FRAME, Result, Session}; -use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; +use anicraft_doc::{ColorTransform, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; use anicraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; use std::collections::{BTreeMap, HashSet}; @@ -168,12 +168,12 @@ impl OnionSkin { } /// 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) { + pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorTransform, Option) { 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) + (ColorTransform::alpha(alpha).concat(&ColorTransform::tint(tint, tint_amount)), outline) } /// A hash of everything that changes the picture, for render-cache keys. @@ -199,15 +199,22 @@ pub struct Extra { pub distance: u32, } -/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers). -fn ghosted(tl: &Timeline, i: usize) -> bool { +/// Whether `layer` is shown and unlocked artwork (not a folder), itself and through its folders. +fn open_artwork(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 onion skin draws `layer`: shown and unlocked (Animate doesn't onion-skin locked +/// layers), with its own onion toggle on (ADR 0061). +pub fn ghosted(tl: &Timeline, i: usize) -> bool { + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| l.onion) +} + /// 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). +/// A layer's onion toggle doesn't apply: it is about the faded frames, not editing. 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)) + open_artwork(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), @@ -301,6 +308,9 @@ fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec| c.map(|c| c + base); let gshift = move |g: Option| g.map(|g| g + gbase); dl.clip_parents.extend(part.clip_parents.into_iter().map(shift)); + for (i, m) in part.clip_modes.into_iter().enumerate() { + dl.set_clip_mode(base + i as u32, m); + } 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 @@ -400,10 +410,7 @@ impl Session { let mut parts = Vec::new(); let mut starts: Vec> = Vec::new(); for e in multi_frames(tl, self.frame, first, last) { - let mut dl = match self.editing_symbol().and_then(|id| self.doc.symbol(id)) { - Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, e.frame), - None => anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame), - }; + let mut dl = if self.editing.is_empty() { anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame) } else { anicraft_doc::evaluate_timeline(&self.doc, tl, e.frame) }; keep_layers(&mut dl, &e.layers); parts.push(dl); starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect()); diff --git a/crates/engine/src/onion_tests.rs b/crates/engine/src/onion_tests.rs index db289dd2..4da367cb 100644 --- a/crates/engine/src/onion_tests.rs +++ b/crates/engine/src/onion_tests.rs @@ -106,11 +106,12 @@ fn onion_frames_fade_by_distance_in_their_colours() { 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 look = |c, a| anicraft_doc::ColorTransform::alpha(a).concat(&anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT)); + assert_eq!((past, line), (look(o.past, NEAR_ALPHA), None)); let (future, _) = o.look(false, 2, 2); - assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA)); + assert_eq!(future, look(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"); + assert!(!own.changes_colour(), "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))); } @@ -182,10 +183,11 @@ fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() { 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(); + let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).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)); + let tint = |c| anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT).add; + assert_eq!(dl.items.first().map(|i| i.color.add), Some(tint(skin.past))); + assert_eq!(dl.items.get(1).map(|i| i.color.add), Some(tint(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); @@ -230,7 +232,7 @@ fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() { // 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![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![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); + assert_eq!(dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect::>(), 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![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top"); @@ -420,7 +422,7 @@ fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() { 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"); + assert_eq!(on_ball.last().map(|i| i.color.is_identity()), Some(true), "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. diff --git a/crates/engine/src/parity_tests.rs b/crates/engine/src/parity_tests.rs new file mode 100644 index 00000000..8d869360 --- /dev/null +++ b/crates/engine/src/parity_tests.rs @@ -0,0 +1,549 @@ +//! Drawing parity leftovers (ADR 0080): PolyStar options, Paint Selection and Paint Inside, +//! drawing objects edited in place, Envelope. + +use crate::Session; +use crate::cmds_erase::measure_els; +use anicraft_doc::{ElementKind, Paint, Rgba, Shape}; +use anicraft_geom::{Affine, Vec2}; +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}: {e}")) +} + +fn blank(object: bool) -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": object})); + s +} + +/// The keyframe's shapes, bottom to top, with their transforms. +fn shapes(s: &Session) -> Vec<(Shape, Affine)> { + s.visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((sh.clone(), e.transform)), + _ => None, + }) + .collect() +} + +/// Total fill area on the active layer, raw shapes and drawing objects (even-odd loops summed +/// by sign; exact for polygons, within the flattening for curves). +fn fill_area(s: &Session) -> f64 { + let raw = measure_els(&s.visible_elements()).0; + let objects: f64 = shapes(s).iter().filter(|(sh, _)| sh.fill.is_some() && !sh.merge).map(|(sh, m)| area_of(&sh.path, m)).sum(); + raw + objects +} + +fn area_of(path: &anicraft_geom::Path, m: &Affine) -> f64 { + path.flatten(m, 0.005) + .iter() + .map(|pl| { + let n = pl.points.len(); + (0..n).map(|i| { + let (a, b) = (pl.points[i], pl.points[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + }) + .sum::() + .abs() +} + +/// What colour covers stage point `p` (the topmost shape containing it). +fn top_at(s: &Session, p: Vec2) -> Option { + shapes(s).iter().rev().find(|(sh, m)| sh.fill.is_some() && sh.path.contains(p, m, sh.fill_rule)).and_then(|(sh, _)| match sh.fill { + Some(Paint::Solid(c)) => Some(c), + _ => None, + }) +} + +// ----- PolyStar ---------------------------------------------------------------------------------- + +/// A polygon of n sides has area n/2 · r² · sin(2π/n); a star at point size 1 covers the same. +#[test] +fn polystar_polygon_and_star_areas() { + for object in [false, true] { + for n in [3u32, 6, 32] { + let mut s = blank(object); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": n, "stroke": null, "fill": "#336699"})); + let want = f64::from(n) / 2.0 * 2500.0 * (std::f64::consts::TAU / f64::from(n)).sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4, "polygon {n} object {object}: {} vs {want}", fill_area(&s)); + let mut t = blank(object); + let v = run(&mut t, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "sides": n, "point_size": 1.0, "stroke": null, "fill": "#336699"})); + assert_eq!(v["kind"], "star"); + assert!((fill_area(&t) - want).abs() < want * 1e-4, "star {n} at size 1"); + } + } +} + +/// A star's area is n · r · r_in · sin(π/n), r_in = r · size · cos(π/n); the old `inner` and +/// `points` params still work. +#[test] +fn polystar_star_follows_point_size() { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "sides": 5, "point_size": 0.3, "stroke": null, "fill": "#ff0000"})); + let half = std::f64::consts::PI / 5.0; + let inner = 40.0 * 0.3 * half.cos(); + let want = 5.0 * 40.0 * inner * half.sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4); + let mut t = blank(true); + run(&mut t, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "inner": 10, "points": 6, "stroke": null, "fill": "#ff0000"})); + let want = 6.0 * 40.0 * 10.0 * (std::f64::consts::PI / 6.0).sin(); + assert!((fill_area(&t) - want).abs() < want * 1e-4); +} + +#[test] +fn polystar_refuses_bad_options() { + let mut s = blank(false); + for p in [ + json!({"cx": 0, "cy": 0, "outer": 40, "shape": "hexagon"}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 2}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 65}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": 1.5}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": -0.1}), + ] { + assert!(s.execute("draw.star", &p).is_err(), "{p}"); + } + assert!(s.visible_elements().is_empty()); +} + +/// Merge drawing: a polygon drawn over a raw fill of another colour cuts into it, as the other +/// shape tools do (ADR 0031). +#[test] +fn polystar_merges_like_the_other_shape_tools() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": 4, "stroke": null, "fill": "#ff0000"})); + // The square's area stays: the polygon replaced what it covers. + assert!((fill_area(&s) - 40_000.0).abs() < 1.0, "{}", fill_area(&s)); + assert_eq!(top_at(&s, Vec2::new(100.0, 100.0)), Some(Rgba::hex(0xff0000))); + assert_eq!(top_at(&s, Vec2::new(5.0, 5.0)), Some(Rgba::hex(0x0000ff))); + assert!(shapes(&s).iter().all(|(sh, _)| sh.merge)); +} + +// ----- Paint Selection and Paint Inside ---------------------------------------------------------- + +/// Fill area of one colour on the active layer. +fn area_in(s: &Session, color: u32) -> f64 { + shapes(s).iter().filter(|(sh, _)| matches!(sh.fill, Some(Paint::Solid(c)) if c == Rgba::hex(color))).map(|(sh, m)| area_of(&sh.path, m)).sum() +} + +/// A blue square at 0..100 and a green one at 200..300 (raw fills, no lines). +fn two_squares() -> Session { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#00ff00"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +fn brush(s: &mut Session, mode: &str, from: [f32; 2], to: [f32; 2]) -> Value { + let pts: Vec<[f32; 2]> = (0..=40).map(|i| { + let t = i as f32 / 40.0; + [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t] + }).collect(); + run(s, "draw.brush", json!({"points": pts, "size": 20, "smoothing": 0, "mode": mode, "color": "#ff0000"})) +} + +fn blue_id(s: &Session) -> u64 { + s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill == Some(Paint::Solid(Rgba::hex(0x0000ff))))).map(|e| e.id.0).expect("the blue square") +} + +/// Paint Selection: a stroke across both squares paints only the selected one, exactly over +/// the 100 × 20 band inside it. +#[test] +fn paint_selection_clips_to_the_selected_fills() { + let mut s = two_squares(); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["merged"], true, "{v}"); + let red = area_in(&s, 0xff0000); + assert!((red - 2000.0).abs() < 2.0, "the band inside the blue square: {red}"); + assert!((area_in(&s, 0x0000ff) - 8000.0).abs() < 2.0, "the rest of the blue square: {}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5, "the green square is not selected"); + assert_eq!(top_at(&s, Vec2::new(250.0, 50.0)), Some(Rgba::hex(0x00ff00))); + assert_eq!(top_at(&s, Vec2::new(150.0, 50.0)), None, "nothing between them"); + assert_eq!(top_at(&s, Vec2::new(50.0, 50.0)), Some(Rgba::hex(0xff0000))); + // The selection stays on the blue square's pieces and the paint, for the next stroke. + let sel = s.selection.on(s.layer); + let els = s.visible_elements(); + assert!(sel.len() >= 2, "{sel:?}"); + for id in &sel { + let e = els.iter().find(|e| e.id == *id).expect("selected element"); + let ElementKind::Shape(sh) = &e.kind else { panic!("a shape") }; + let b = sh.path.bounds().transformed(&e.transform); + assert!(b.min.x > -0.5 && b.max.x < 100.5, "inside the blue square: {b:?}"); + } + let v = brush(&mut s, "selection", [-60.0, 20.0], [360.0, 20.0]); + assert!(v["elements"].as_array().is_some_and(|a| !a.is_empty()), "a second stroke paints too"); + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// With nothing selected (or a stroke that misses the selection), nothing changes and there is +/// no undo step. +#[test] +fn paint_selection_without_a_selection_changes_nothing() { + let mut s = two_squares(); + let steps = s.history_len(); + let doc = s.doc.clone(); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["painted"], false); + assert_eq!(s.history_len(), steps); + assert!(s.doc == doc); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [150.0, 300.0], [160.0, 400.0]); + assert_eq!(v["painted"], false, "{v}"); + assert_eq!(s.history_len(), steps); +} + +/// Paint Inside: started in the blue square, the stroke stays inside it (a half-round start +/// cap and a 50 × 20 band) and never reaches the green one. +#[test] +fn paint_inside_clips_to_the_fill_it_starts_on() { + let mut s = two_squares(); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5); + assert!((area_in(&s, 0x0000ff) + red - 10_000.0).abs() < 2.0, "the paint replaced its part of the blue square"); +} + +/// Paint Inside started on empty stage inside a closed outline paints only that empty area, +/// under the line; started on open stage, only empty areas (as Paint Behind). +#[test] +fn paint_inside_empty_areas() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert_eq!(top_at(&s, Vec2::new(200.0, 50.0)), None, "nothing outside the outline"); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the outline is whole"); + + let mut t = two_squares(); + brush(&mut t, "inside", [-100.0, 50.0], [50.0, 50.0]); + assert!((area_in(&t, 0x0000ff) - 10_000.0).abs() < 0.5, "the blue square is untouched"); + assert!(area_in(&t, 0xff0000) > 1000.0, "the empty stage took the paint"); +} + +/// A line across the selected fill stays: clipped paint goes under lines. +#[test] +fn paint_selection_leaves_lines() { + let mut s = two_squares(); + run(&mut s, "draw.line", json!({"x0": 50, "y0": -20, "x1": 50, "y1": 120, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + run(&mut s, "edit.select_all", json!({})); + brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the line is whole"); + // Both squares were selected: the band in each. + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// As drawing objects, the clipped paint is an object of exactly the clipped outline. +#[test] +fn paint_inside_as_a_drawing_object() { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + assert!((area_in(&s, 0xff0000) - want).abs() < want * 0.01); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "objects don't cut each other"); +} + +// ----- drawing objects edited in place ----------------------------------------------------------- + +/// A drawing object (an orange rectangle at 100..300 × 100..200) beside a raw blue square on the +/// same layer; returns the object's id. +fn object_and_raw() -> (Session, u64) { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 400, "y": 100, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + let v = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null, "fill": "#ff8800", "object": true})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "edit.deselect", json!({})); + (s, id) +} + +/// Double-clicking a drawing object opens it in place; opening and closing it without an edit +/// changes nothing: the same document and state, no undo step, the object selected. +#[test] +fn drawing_object_opens_and_closes_unchanged() { + let (mut s, id) = object_and_raw(); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let v = run(&mut s, "symbol.edit", json!({"id": id})); + assert_eq!(v["editing"][0]["drawing"], id, "{v}"); + assert!(s.editing_drawing() && s.editing_group()); + // Inside, its one raw shape, where it showed. + let inside = s.visible_elements(); + assert_eq!(inside.len(), 1); + assert!(matches!(&inside[0].kind, ElementKind::Shape(sh) if sh.merge)); + run(&mut s, "symbol.exit", json!({})); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!(s.state, state, "no unsaved change"); + assert_eq!(s.history_len(), steps); + assert_eq!(s.selection.id_list(), vec![id]); + assert!(s.visible_elements().iter().any(|e| e.id.0 == id && matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge))); +} + +/// Inside, a line drawn across merges only with the object's own shape: it splits the fill, the +/// raw square outside is untouched, and closing it leaves a group of the pieces (several +/// shapes stay one object, as Combine Objects' Union makes them). +#[test] +fn drawing_object_merges_only_inside() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + // Positions inside are in the object's own space (its centre at the origin). + run(&mut s, "draw.line", json!({"x0": 0, "y0": -100, "x1": 0, "y1": 100, "stroke": "#000000", "stroke_width": 2, "object": false})); + let inside = s.visible_elements(); + let fills = inside.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2, "the line cut the fill in two"); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object stays, with its id"); + assert!(matches!(obj.kind, ElementKind::Group { .. }), "several pieces: a group"); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "the raw square outside is whole"); + assert_eq!(els.len(), 2); +} + +/// An edit that leaves one shape makes it one drawing object again, moved as edited; undo goes +/// back inside, and closing then gives the object as it was. +#[test] +fn drawing_object_edit_keeps_one_object() { + let (mut s, id) = object_and_raw(); + let before = s.element_bounds(anicraft_doc::ElementId(id)); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 30, "dy": 10})); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object"); + assert!(matches!(&obj.kind, ElementKind::Shape(sh) if !sh.merge), "one drawing object again"); + let after = s.element_bounds(anicraft_doc::ElementId(id)); + assert!((after.min.x - before.min.x - 30.0).abs() < 1e-3 && (after.min.y - before.min.y - 10.0).abs() < 1e-3, "{before:?} → {after:?}"); + // Undo: inside again, before the move. + run(&mut s, "edit.undo", json!({})); + assert!(s.editing_drawing()); + run(&mut s, "symbol.exit", json!({})); + assert!((s.element_bounds(anicraft_doc::ElementId(id)).min.x - before.min.x).abs() < 1e-3); +} + +/// Everything inside deleted: closing it removes the object. +#[test] +fn an_emptied_drawing_object_is_gone() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "edit.delete", json!({})); + run(&mut s, "symbol.exit", json!({})); + assert!(s.visible_elements().iter().all(|e| e.id.0 != id)); + assert!(s.selection.is_empty()); + assert_eq!(s.visible_elements().len(), 1, "the raw square stays"); +} + +/// Raw shapes don't open (they are the drawing itself); the timeline stays one frame inside. +#[test] +fn only_drawing_objects_open() { + let (mut s, _) = object_and_raw(); + let raw = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).map(|e| e.id.0).expect("raw"); + assert!(s.execute("symbol.edit", &json!({"id": raw})).is_err()); + let id = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge)).map(|e| e.id.0).expect("object"); + run(&mut s, "symbol.edit", json!({"id": id})); + assert!(s.execute("timeline.insert_keyframe", &json!({})).is_err(), "one frame inside"); +} + +// ----- Envelope ---------------------------------------------------------------------------------- + +fn points_of(v: &Value) -> Vec<[f32; 2]> { + v["points"].as_array().expect("points").iter().map(|p| [p[0].as_f64().unwrap_or(0.0) as f32, p[1].as_f64().unwrap_or(0.0) as f32]).collect() +} + +/// A 100 × 50 orange drawing object at (10, 20), selected, with an envelope open on it. +fn enveloped() -> (Session, Value) { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let v = run(&mut s, "modify.envelope", json!({})); + (s, v) +} + +/// At rest the envelope is the identity: its mesh is evenly over the bounds, and moving it to +/// the rest mesh changes nothing. +#[test] +fn envelope_identity_at_rest() { + let (mut s, v) = enveloped(); + assert_eq!(v["bounds"], json!([10.0, 20.0, 100.0, 50.0])); + let pts = points_of(&v); + assert_eq!(pts.len(), 16); + assert_eq!(pts[0], [10.0, 20.0]); + assert_eq!(pts[15], [110.0, 70.0]); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"points": v["points"]})); + let after = shapes(&s); + assert_eq!(before.len(), after.len()); + let flat = |sh: &Shape, m: &Affine| sh.path.flatten(m, 0.01).into_iter().flat_map(|p| p.points).collect::>(); + for ((a, ma), (b, mb)) in before.iter().zip(&after) { + let (pa, pb) = (flat(a, ma), flat(b, mb)); + assert_eq!(pa.len(), pb.len()); + assert!(pa.iter().zip(&pb).all(|(x, y)| x.distance(*y) < 1e-3)); + } + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Lifting the top side's two handles by 30 bends the top edge up: the area grows by +/// lift · width / 2 (∫ B₁ + B₂ = ½), and each move is one undo step. +#[test] +fn envelope_bends_by_the_mesh() { + let (mut s, v) = enveloped(); + let steps = s.history_len(); + let pts = points_of(&v); + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 30.0})); + let v = run(&mut s, "modify.envelope_move", json!({"index": 2, "x": pts[2][0], "y": pts[2][1] - 30.0})); + assert_eq!(s.history_len(), steps + 2, "one step per move"); + let want = 5000.0 + 30.0 * 100.0 / 2.0; + assert!((fill_area(&s) - want).abs() < want * 1e-3, "{} vs {want}", fill_area(&s)); + // The inner points followed the side (Coons). + let now = points_of(&v); + assert!(now[5][1] < pts[5][1] - 1.0 && now[6][1] < pts[6][1] - 1.0); + // Undo: the mesh that made the shapes on the stage. + run(&mut s, "edit.undo", json!({})); + let (_, _, mesh) = s.envelope().expect("still open"); + assert!((mesh[2].y - pts[2][1]).abs() < 1e-4 && (mesh[1].y - (pts[1][1] - 30.0)).abs() < 1e-4); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("still open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Moves bend the shapes as they were when the envelope opened, so a move and its reverse +/// leave them exactly as they were. +#[test] +fn envelope_moves_do_not_compound() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": 160, "y": 120})); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0], "y": pts[15][1]})); + let after = shapes(&s); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); + assert_eq!(before[0].0.path.cmds.len(), after[0].0.path.cmds.len()); +} + +/// Symbols, text and groups can't be bent; nothing open is an error for a move. +#[test] +fn envelope_refuses_what_it_cannot_bend() { + let mut s = blank(true); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "nothing selected"); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "a symbol instance"); + assert!(s.execute("modify.envelope_move", &json!({"index": 0, "x": 1, "y": 1})).is_err()); + let (mut t, _) = enveloped(); + for p in [json!({"index": 16, "x": 0, "y": 0}), json!({"points": [[0, 0]]}), json!({"index": 0, "x": 1e9, "y": 0}), json!({})] { + assert!(t.execute("modify.envelope_move", &p).is_err(), "{p}"); + } + // A new selection ends it. + run(&mut t, "edit.deselect", json!({})); + assert!(t.envelope().is_none()); +} + +/// Raw shapes bent by an envelope merge with the drawing they land on when it closes. +#[test] +fn envelope_close_merges_raw_shapes() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#ff0000"})); + // The red square is selected (the last drawn): bend its left side over the blue one. + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let mut m = pts.clone(); + for i in [0usize, 4, 8, 12] { + m[i][0] -= 150.0; + } + run(&mut s, "modify.envelope_move", json!({"points": m})); + run(&mut s, "modify.envelope_close", json!({})); + assert!(s.envelope().is_none()); + // The red covers 50 of the blue square's width now. + assert!((area_in(&s, 0x0000ff) - 5000.0).abs() < 5.0, "{}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0xff0000) - 25_000.0).abs() < 25.0, "{}", area_in(&s, 0xff0000)); +} + +/// A drag's moves are one undo step and remember only the last mesh; undo goes back to before +/// the drag with the envelope still open. +#[test] +fn envelope_drag_is_one_step() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let steps = s.history_len(); + s.begin_gesture("Envelope"); + for k in 1..=300 { + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0] + k as f32 * 0.1, "y": pts[15][1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + assert!(s.envelope.as_ref().is_some_and(|e| e.states_len() == 2)); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + run(&mut s, "edit.redo", json!({})); + let (_, _, mesh) = s.envelope().expect("open"); + assert!((mesh[15].x - (pts[15][0] + 30.0)).abs() < 1e-3); +} + +/// Timings for ADR 0080 (`cargo test --release -p anicraft-engine parity_timings -- --ignored --nocapture`). +#[test] +#[ignore = "a measurement"] +fn parity_timings() { + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let wave: Vec<[f32; 2]> = (0..=400).map(|i| [20.0 + i as f32 * 2.5, 300.0 + (i as f32 * 0.05).sin() * 120.0]).collect(); + for mode in ["normal", "inside", "selection"] { + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(false); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 800, "h": 400, "fill": "#3d8bfd", "stroke": "#000000", "stroke_width": 2})); + run(&mut s, "edit.deselect", json!({})); + if mode == "selection" { + run(&mut s, "edit.select_all", json!({})); + } + let t = std::time::Instant::now(); + run(&mut s, "draw.brush", json!({"points": wave, "size": 30, "mode": mode, "color": "#ff0000"})); + times.push(t.elapsed().as_secs_f64() * 1e3); + } + eprintln!("brush 1000 px wave, size 30, {mode}: {:.2} ms", median(times)); + } + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 400, "cy": 300, "outer": 250, "sides": 32, "point_size": 0.5, "fill": "#ff0000"})); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 600, "h": 400, "fill": "#00ff00"})); + run(&mut s, "edit.select_all", json!({})); + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let t = std::time::Instant::now(); + for k in 0..10 { + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 10.0 * k as f32})); + } + times.push(t.elapsed().as_secs_f64() * 1e3 / 10.0); + } + eprintln!("envelope move, a 32-point star and an oval: {:.2} ms", median(times)); +} + +/// Warped artwork (ADR 0079) neither opens in place nor takes an envelope: its warp keeps the +/// outline as drawn on every keyframe. +#[test] +fn warped_objects_refuse_envelope_and_editing() { + let mut s = blank(true); + let v = run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "warp.add", json!({"element": id})); + run(&mut s, "element.select", json!({"ids": [id]})); + assert!(s.execute("modify.envelope", &json!({})).is_err()); + assert!(s.execute("symbol.edit", &json!({"id": id})).is_err()); + assert!(s.editing.is_empty()); +} diff --git a/crates/engine/src/path_text_tests.rs b/crates/engine/src/path_text_tests.rs new file mode 100644 index 00000000..ff4f6f0e --- /dev/null +++ b/crates/engine/src/path_text_tests.rs @@ -0,0 +1,164 @@ +//! Text on a path (ADR 0070): attaching text to a shape's outline, by selection or by picking, +//! moving it along, flipping and releasing it, edits keeping it on the path, undo, the file. + +use crate::Session; +use anicraft_doc::{ElementId, ElementKind, TextBlock}; +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 fonts() -> bool { + let ok = !anicraft_text::Fonts::get().families().is_empty(); + if !ok { + eprintln!("no fonts on this computer: text on a path tests skipped"); + } + ok +} + +fn text_of(s: &Session, id: ElementId) -> (anicraft_geom::Affine, Arc) { + let e = s.visible_elements().into_iter().find(|e| e.id == id).unwrap(); + match &e.kind { + ElementKind::Text(t) => (e.transform, t.clone()), + other => panic!("not text: {other:?}"), + } +} + +/// A session with "Along the line" and a 400 px line from (100, 300) to (500, 300). +fn text_and_line() -> (Session, ElementId, ElementId) { + let mut s = Session::default(); + let text = ElementId(run(&mut s, "text.create", json!({"text": "Along the line", "x": 50, "y": 50, "size": 24}))["element"].as_u64().unwrap()); + let line = ElementId(run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 500, "y1": 300}))["element"].as_u64().unwrap()); + (s, text, line) +} + +#[test] +fn text_attaches_to_a_selected_shape_and_sits_on_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + let steps = s.history().undo_len(); + let v = run(&mut s, "text.attach_path", json!({})); + assert_eq!(s.history().undo_len(), steps + 1, "one undo step"); + assert!((v["length"].as_f64().unwrap() - 400.0).abs() < 0.5, "{v}"); + assert_eq!(v["offset"], 0.0, "left-aligned text starts at the path's start"); + let (xf, t) = text_of(&s, text); + let on = t.on_path.as_ref().expect("on a path"); + // In stage space the glyphs stand on the line, starting at its start. + let b = t.outline.bounds().transformed(&xf); + assert!(b.max.y <= 300.0 + 8.0 && b.max.y > 295.0 && b.min.y < 290.0, "standing on y 300 (descenders a little below): {b:?}"); + assert!((b.min.x - 100.0).abs() < 4.0, "{b:?}"); + let path = on.path.transformed(&xf).bounds(); + assert!((path.min.x - 100.0).abs() < 1e-3 && (path.max.x - 500.0).abs() < 1e-3); + // The box holds the path and the glyphs from the origin. + let local = t.outline.bounds().union(&on.path.bounds()); + assert!(local.min.x.abs() < 1e-3 && local.min.y.abs() < 1e-3 && (local.width() - t.box_width).abs() < 1e-3 && (local.height() - t.box_height).abs() < 1e-3, "{local:?}"); + // The shape is left as it is, and only the text is selected. + assert!(s.visible_elements().iter().any(|e| e.id == line)); + assert_eq!(s.selection.on(s.layer), vec![text]); + // Undo puts the text back in its lines. + s.undo().unwrap(); + assert!(text_of(&s, text).1.on_path.is_none()); +} + +#[test] +fn offset_flip_alignment_and_edits_keep_text_on_its_path() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0]})); + // Picking the shape at a stage point (the stage's pick mode does this). + run(&mut s, "text.attach_path", json!({"x": 300, "y": 300})); + let left = |s: &Session| { + let (xf, t) = text_of(s, text); + t.outline.bounds().transformed(&xf) + }; + let at0 = left(&s); + run(&mut s, "text.path", json!({"offset": 100})); + let at100 = left(&s); + assert!((at100.min.x - at0.min.x - 100.0).abs() < 0.5, "{at0:?} → {at100:?}"); + // Flipped: from the other end, below the line. + run(&mut s, "text.path", json!({"flip": true})); + let f = left(&s); + assert!(f.min.y > 290.0 && f.max.y > 310.0 && (f.max.x - 400.0).abs() < 1.0, "{f:?}"); + run(&mut s, "text.path", json!({"flip": false, "offset": 200})); + // Centred text is centred on its offset. + run(&mut s, "text.edit", json!({"align": "center"})); + let c = left(&s); + assert!((c.center().x - 300.0).abs() < 3.0, "centred on x 300: {c:?}"); + // Editing the words or the size keeps it on the path, where it was. + run(&mut s, "text.edit", json!({"text": "Hi", "size": 40})); + let (xf, t) = text_of(&s, text); + assert_eq!(t.text, "Hi"); + assert!(t.on_path.is_some()); + assert!((t.on_path.as_ref().unwrap().path.transformed(&xf).bounds().min.x - 100.0).abs() < 1e-3, "the path doesn't move"); + assert!((left(&s).center().x - 300.0).abs() < 3.0); + // Text on a path is static text. + assert!(s.execute("text.field", &json!({"type": "dynamic"})).is_err()); + // Released: back to a line of text where it started. + let before = left(&s); + run(&mut s, "text.release_path", json!({})); + let (_, t) = text_of(&s, text); + assert!(t.on_path.is_none()); + let after = left(&s); + assert!((after.min.x - before.min.x).abs() < 6.0 && (after.min.y - before.min.y).abs() < 12.0, "{before:?} → {after:?}"); + assert!(s.execute("text.path", &json!({"offset": 5})).is_err(), "no text on a path selected"); + let _ = line; +} + +#[test] +fn bad_requests_change_nothing() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + // No shape anywhere selected or there. + run(&mut s, "element.select", json!({"ids": [text.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5, "y": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"path": line.0, "offset": 1e9})).is_err()); + // Only the shape selected: no text. + run(&mut s, "element.select", json!({"ids": [line.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(text_of(&s, text).1.on_path.is_none()); + // By id works from another layer too. + run(&mut s, "layer.new", json!({})); + let other = ElementId(run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 200, "h": 200}))["element"].as_u64().unwrap()); + let base = s.timeline().layers.last().unwrap().id; + run(&mut s, "layer.select", json!({"layer": base.0})); + run(&mut s, "element.select", json!({"ids": [text.0]})); + run(&mut s, "text.attach_path", json!({"path": other.0})); + assert!(text_of(&s, text).1.on_path.is_some()); +} + +#[test] +fn text_on_a_path_is_saved_and_older_files_open_without_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + run(&mut s, "text.attach_path", json!({"offset": 12.5, "flip": true})); + let (_, t) = text_of(&s, text); + let json = serde_json::to_string(&*t).unwrap(); + assert!(json.contains("\"on_path\"") && json.contains("\"offset\":12.5") && json.contains("\"flip\":true"), "{json}"); + let back: TextBlock = serde_json::from_str(&json).unwrap(); + assert_eq!(back, *t); + // The whole document round-trips through the file format. + let saved = crate::format::to_json(&s.doc).unwrap(); + let doc = crate::format::from_json(&saved).unwrap(); + assert_eq!(doc, s.doc); + // A block saved before text on a path opens as plain text. + let mut v: Value = serde_json::from_str(&json).unwrap(); + v.as_object_mut().unwrap().remove("on_path"); + assert!(serde_json::from_value::(v).unwrap().on_path.is_none()); + // It renders from its outlines alone: the same pixels without the font. + let a = anicraft_render::render_frame(&s.doc, 0, 0.5).unwrap(); + assert!(a.data.iter().any(|p| p[0] < 0.5), "the text draws"); +} diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index df41bd67..9306aaea 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -9,9 +9,11 @@ //! its scripts, so a script that loops forever costs one frame's budget, then stops with a //! message. +use anicraft_doc::actions::as3::Problem; 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, LayerKind, SymbolKind, Timeline, player}; +use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef}; +use anicraft_doc::field::{CaretLine, FieldLook}; +use anicraft_doc::{Document, LayerKind, SymbolKind, TextBlock, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; use serde_json::{Map, Value, json}; @@ -91,6 +93,22 @@ impl ScriptHost for ScriptRunner<'_> { } } } + + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + field_look(block, shown) + } +} + +/// A field's text laid out with this computer's fonts, as the player draws and edits it +/// (ADR 0066). +pub fn field_look(block: &TextBlock, shown: &str) -> Option { + let f = block.field.as_ref()?; + let l = crate::cmds_text::field_layout(anicraft_text::Fonts::get(), &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?; + let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); + if lines.is_empty() { + lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); + } + Some(FieldLook { outline: std::sync::Arc::new(l.outline), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } /// What a running frame script talks to. @@ -164,6 +182,26 @@ pub fn state_view(doc: &Document, st: &PlayerState, nodes: &[Node], here: Option "hover": path_of(&st.hover), "tick": st.tick, }); + // Text fields (ADR 0066): their text as it is now, and which has the keyboard. + let fields: Vec = nodes + .iter() + .enumerate() + .filter_map(|(i, n)| n.field().map(|(t, f)| (i, n, t, f))) + .take(MAX_VIEW_CLIPS) + .map(|(i, n, t, f)| { + let fs = st.fields.get(&n.path); + let text = fs.map_or(t.text.as_str(), |x| x.value(t)); + let mut o = json!({"path": path_name(nodes, i), "name": n.name, "type": f.kind.key(), "text": text}); + if st.focus.as_ref() == Some(&n.path) { + let (a, b) = fs.map_or((0, 0), |x| x.selection()); + o["focus"] = json!({"caret": fs.map_or(0, |x| x.caret), "selection": [a, b]}); + } + o + }) + .collect(); + if !fields.is_empty() { + v["fields"] = Value::Array(fields); + } if let Some((i, frame, label)) = here { let n = nodes.get(i); v["timeline"] = json!({"path": path_name(nodes, i), "frame": frame, "frames": n.map_or(1, |n| n.frames), "label": label, "playing": n.and_then(|n| st.playhead(&n.path)).is_some_and(|c| c.playing)}); @@ -191,9 +229,14 @@ impl Movie { /// 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 { + Movie::start_seeded(doc, player::DEFAULT_SEED, scripts) + } + + /// [`Movie::start`] with `Math.random()` seeded by `seed`. + pub fn start_seeded(doc: &Document, seed: u64, 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); + let s = player::start_seeded(doc, seed, scripts); m.take(s); m } @@ -233,10 +276,51 @@ impl Movie { } } -/// Parses a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a press and -/// a release at one point). +/// The ActionScript key code a key event names: a number (1-255), a `Keyboard` constant +/// (`"LEFT"`, `"SPACE"`) or one letter or digit. +pub fn parse_key(v: &Value) -> Result { + match v { + Value::Number(n) => n.as_u64().filter(|k| (1..=255).contains(k)).map(|k| k as u32).ok_or_else(|| "a key code is 1-255".to_string()), + Value::String(s) => { + let t = s.trim(); + let one = t.chars().count() == 1 && t.chars().all(|c| c.is_ascii_alphanumeric()); + if one { + let c = t.to_ascii_uppercase(); + return anicraft_doc::actions::as3::ir::key_code(&c).or_else(|| anicraft_doc::actions::as3::ir::key_code(&format!("NUMBER_{c}"))).ok_or_else(|| format!("unknown key '{t}'")); + } + anicraft_doc::actions::as3::ir::key_code(&t.to_ascii_uppercase()).ok_or_else(|| format!("unknown key '{t}' (a key code, a letter, or a Keyboard name such as LEFT or SPACE)")) + } + _ => Err("a key event needs a \"key\": a key code, a letter, or a Keyboard name such as LEFT".into()), + } +} + +/// Most characters one `text` event types. +pub const MAX_TYPED: usize = 10_000; + +/// Parses an event: a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a +/// press and a release at one point), a key event `{type: key_down|key_up|key, key}` (`key` +/// is a press and a release), or typing into the focused text field (ADR 0066): +/// `{type: text, text}` (each character typed in turn) and `{type: select_all}`. pub fn parse_events(v: &Value) -> Result, String> { - let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click or leave")?; + let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click, leave, key_down, key_up, key, text or select_all")?; + if kind == "text" { + let t = v.get("text").and_then(Value::as_str).ok_or("a text event needs a \"text\" to type")?; + if t.chars().count() > MAX_TYPED { + return Err(format!("a text event types at most {MAX_TYPED} characters")); + } + return Ok(t.chars().map(Event::Char).collect()); + } + if kind == "select_all" { + return Ok(vec![Event::SelectAll]); + } + if matches!(kind, "key_down" | "key_up" | "key") { + let k = parse_key(v.get("key").unwrap_or(&Value::Null))?; + return Ok(match kind { + "key_down" => vec![Event::KeyDown(k)], + "key_up" => vec![Event::KeyUp(k)], + _ => vec![Event::KeyDown(k), Event::KeyUp(k)], + }); + } let num = |k: &str| -> Result { v.get(k).and_then(Value::as_f64).filter(|f| f.is_finite() && f.abs() <= 1e7).map(|f| f as f32).ok_or(format!("a {kind} event needs a finite \"{k}\"")) }; Ok(match kind { "leave" => vec![Event::Leave], @@ -247,7 +331,7 @@ pub fn parse_events(v: &Value) -> Result, String> { let p = Vec2::new(num("x")?, num("y")?); vec![Event::Move(p), Event::Down(p), Event::Up(p)] } - other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")), + other => return Err(format!("unknown event type '{other}' (move, down, up, click, leave, key_down, key_up, key, text or select_all)")), }) } @@ -258,12 +342,15 @@ pub struct KeptScript<'a> { /// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays). pub plays: bool, pub compiled: &'a CompileResult, + /// Why it doesn't run on its timeline although it compiles: names from other frames that + /// aren't there (ADR 0052). + pub links: Vec, } impl KeptScript<'_> { /// It runs when the movie plays. pub fn runs(&self) -> bool { - self.plays && self.compiled.is_ok() + self.plays && self.compiled.is_ok() && self.links.is_empty() } } @@ -276,17 +363,28 @@ fn layer_plays(tl: &Timeline, index: usize) -> bool { /// Every kept script in the document: the scenes' first, then the symbols'. pub fn kept_scripts(doc: &Document) -> Vec> { - 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 scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, Some(TimelineRef::Root))); + let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, (s.kind == SymbolKind::MovieClip).then_some(TimelineRef::Symbol(s.id)))); let mut out = Vec::new(); - for (name, tl, runs) in scenes.chain(symbols) { + let mut root = None; + for (name, tl, which) in scenes.chain(symbols) { + let runs = which.is_some(); + let decls = match which { + Some(TimelineRef::Root) => root.get_or_insert_with(|| player::decls(doc, TimelineRef::Root)).clone(), + Some(w) => player::decls(doc, w), + None => Default::default(), + }; 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() }); + let links = match src.compiled() { + Ok(c) if runs => decls.problems(c), + _ => Vec::new(), + }; + out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled(), links }); } } } @@ -300,20 +398,24 @@ pub fn script_summary(doc: &Document) -> Vec { 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)) => { + (true, Ok(c)) if k.links.is_empty() => { 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)); - } + (true, Ok(_)) => lines.push(not_run(&k.place, &k.links)), + (true, Err(problems)) => lines.push(not_run(&k.place, problems)), } } lines } + +/// "Frame script not run: …" with the first problem and how many more there are. +fn not_run(place: &str, problems: &[Problem]) -> String { + 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), + }; + format!("Frame script not run: {place}: {first}{more}") +} diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 35ced9f4..c1012f91 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -136,6 +136,8 @@ fn plugins_cannot_reach_files_history_the_clipboard_or_other_plugins() { let forbidden = [ save.as_str(), r#"{"op":"command","id":"file.export_png","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_apng","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_webp","params":{"path":"x.webp"}}"#, r#"{"op":"command","id":"plugin.run","params":{"id":"org.test.sneaky"}}"#, r#"{"op":"command","id":"plugin.remove","params":{"id":"org.test.sneaky","confirm":true}}"#, r#"{"op":"command","id":"edit.undo"}"#, @@ -169,7 +171,15 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" => assert!(verdict.is_err(), "{} must be refused", c.id), + // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). + "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), + // Brushes (ADR 0068): list yes; your own brushes and brush set files no. + "brush" => assert_eq!(verdict.is_ok(), c.id == "brush.preset_list", "{}", c.id), + // Swatches (ADR 0078): document data yes, swatch files no. + "swatch" => assert_eq!(verdict.is_ok(), !matches!(c.id, "swatch.import" | "swatch.export"), "{}", c.id), + // Rulers, grid and guides (ADR 0076): a scene's guides yes, how you see and snap no. + "view" => assert_eq!(verdict.is_ok(), matches!(c.id, "view.aids" | "view.guide_add" | "view.guide_move" | "view.guide_delete" | "view.guides_clear"), "{}", c.id), _ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id), } } diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs new file mode 100644 index 00000000..64d83afc --- /dev/null +++ b/crates/engine/src/publish.rs @@ -0,0 +1,801 @@ +//! File › Publish Settings and File › Publish (ADR 0060). +//! +//! The document holds a [`PublishProfile`]: every format, on or off, with its options and an +//! output template relative to the document's folder (`{name}` is the document's name). Publish +//! turns the formats that are on into a [`Step`] each (the export command and its params), and +//! runs them in order through the same export commands File › Export uses, on a session of its +//! own: on the caller's thread for `file.publish` (CLI, MCP, the web build one step per frame), +//! or on a background worker in the desktop editor ([`Publisher`]). A [`Control`] cancels the +//! run between and inside exports and counts frames for the progress view. One [`Report`] says +//! what each format wrote, skipped or left out. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::Document; +use anicraft_doc::publish::{FrameRange, MAX_OUTPUT_CHARS, MAX_PUBLISH_SCALE, MAX_TITLE_CHARS, PublishFormat, PublishProfile}; +use serde_json::{Map, Value, json}; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "publish.settings_get", + label: "Publish Settings…", + menu: "File", + shortcut: Some("Ctrl+Shift+F12"), + params: "{} (the document's publish profile, and where each format would go)", + mutates: false, + run: settings_get, + }, + CommandSpec { + id: "publish.settings_set", + label: "Publish Settings", + menu: "", + shortcut: None, + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + mutates: true, + run: settings_set, + }, + CommandSpec { + id: "file.publish", + label: "Publish", + menu: "File", + shortcut: Some("Shift+F12"), + params: "{formats? ([format, …]: only these; default: the ones Publish Settings has on), confirm? (to replace files already there)}", + mutates: false, + run: publish_cmd, + }, + ] +} + +// ----- cancel and progress ------------------------------------------------------------------- + +/// Shared between a running publish and whoever watches it: Cancel, and frames done of the +/// format running. Exports check it between frames (`tick`). +#[derive(Debug, Default)] +pub struct Control { + cancel: AtomicBool, + done: AtomicU64, + total: AtomicU64, +} + +impl Control { + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + pub fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } + /// Frames done and frames in all, of the format running (0 in all: no frame count). + pub fn progress(&self) -> (u64, u64) { + (self.done.load(Ordering::Relaxed), self.total.load(Ordering::Relaxed)) + } + fn begin(&self, total: u64) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + } +} + +/// An export made `frames` more frames: counts them, and stops it when Publish was cancelled. +pub(crate) fn tick(job: Option<&Control>, frames: u64) -> Result<()> { + let Some(j) = job else { return Ok(()) }; + j.done.fetch_add(frames, Ordering::Relaxed); + if j.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) } +} + +// ----- where things go ----------------------------------------------------------------------- + +/// The folder outputs are relative to and the `{name}` they use: the document's folder and file +/// name. An untitled document has no folder on disk, so it can't publish until it is saved; in +/// the browser (no folders, files become downloads) it publishes as "Untitled". +pub fn base(path: Option<&Path>) -> std::result::Result<(PathBuf, String), String> { + match path { + Some(p) => { + let name = p.file_stem().map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); + Ok((p.parent().map(Path::to_path_buf).unwrap_or_default(), name)) + } + None if crate::vfs::in_memory() => Ok((PathBuf::new(), "Untitled".into())), + None => Err("save the document first: Publish writes its files beside it".into()), + } +} + +/// Output template `template` of format `f`, for a document named `name`: a path inside the +/// document's folder. `{name}` is the only placeholder; the path may go into folders below +/// but never above or elsewhere (a document opened from someone else can't write anywhere +/// else on this computer); a file without an extension gets the format's. +pub fn resolve(f: PublishFormat, template: &str, name: &str) -> std::result::Result { + let t = template.trim(); + if t.is_empty() { + return Err("the output name is empty".into()); + } + if t.chars().count() > MAX_OUTPUT_CHARS { + return Err(format!("the output name is longer than {MAX_OUTPUT_CHARS} characters")); + } + let text = t.replace("{name}", name); + if t.replace("{name}", "").contains(['{', '}']) { + return Err(format!("“{t}” has a placeholder Publish doesn't know: {{name}} (the document's name) is the only one")); + } + let mut rel = PathBuf::new(); + for c in Path::new(&text).components() { + match c { + Component::Normal(part) => rel.push(part), + Component::CurDir => {} + _ => return Err(format!("“{t}” must stay in the document's folder (a name, or folders below it like web/{{name}}.html)")), + } + } + if rel.as_os_str().is_empty() { + return Err("the output name is empty".into()); + } + let exts = f.extensions(); + if !exts.is_empty() { + match rel.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) { + None => { + let file = rel.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + rel.set_file_name(format!("{file}.{}", exts.first().copied().unwrap_or(""))); + } + Some(e) if exts.contains(&e.as_str()) => {} + Some(_) => return Err(format!("{} goes to {}", f.label(), exts.iter().map(|e| format!(".{e}")).collect::>().join(" or "))), + } + } + Ok(rel) +} + +// ----- the plan -------------------------------------------------------------------------------- + +/// One format to publish: the export command that writes it and its params. +#[derive(Clone, Debug)] +pub struct Step { + pub format: PublishFormat, + pub command: &'static str, + pub params: Value, + /// The files (or, for the PNG sequence, the folder) it writes. + pub outputs: Vec, + /// The scene the export runs in (one-frame formats), and frames it makes (0: not counted). + pub scene: usize, + pub frames: u64, + /// Why it won't run here, when it won't. + pub skip: Option, +} + +fn range_params(p: &mut Map, r: FrameRange, last: u32) -> u64 { + if let Some(f) = r.from { + p.insert("from".into(), json!(f)); + } + if let Some(t) = r.to { + p.insert("to".into(), json!(t)); + } + let from = r.from.unwrap_or(0).min(last); + let to = r.to.unwrap_or(last).min(last); + u64::from(to.saturating_sub(from)) + 1 +} + +/// The steps Publish runs for `doc` saved at `path`: the formats that are on (or `only`), in +/// order, or why it can't run (an output that isn't one, two formats writing the same file). +pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) -> std::result::Result, String> { + let (dir, name) = base(path)?; + let prof = &doc.publish; + let formats: Vec = match only { + Some(list) => PublishFormat::ALL.into_iter().filter(|f| list.contains(f)).collect(), + None => prof.enabled(), + }; + let last = doc.frame_count().saturating_sub(1); + let mut steps: Vec = Vec::new(); + for f in formats { + let rel = resolve(f, prof.target(f).1, &name).map_err(|e| format!("{}: {e}", f.label()))?; + let out = dir.join(&rel); + let path_s = out.display().to_string(); + let mut p = Map::new(); + let (mut scene, mut skip) = (0, None); + let (command, frames, outputs) = match f { + PublishFormat::Html => { + let h = &prof.html; + if !h.title.trim().is_empty() { + p.insert("title".into(), json!(h.title)); + } + p.insert("sound".into(), json!(h.sound)); + p.insert("fit".into(), json!(h.fit)); + ("file.export_html", 0, vec![out]) + } + PublishFormat::Gif => { + let g = &prof.gif; + let n = range_params(&mut p, g.range, last); + p.insert("scale".into(), json!(g.scale)); + p.insert("loop".into(), json!(g.looping)); + ("file.export_gif", n, vec![out]) + } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background, command) = match f { + PublishFormat::Apng => (prof.apng.range, prof.apng.scale, prof.apng.plays, prof.apng.background, "file.export_apng"), + _ => (prof.webp.range, prof.webp.scale, prof.webp.plays, prof.webp.background, "file.export_webp"), + }; + let n = range_params(&mut p, range, last); + p.insert("scale".into(), json!(scale)); + p.insert("loop".into(), json!(plays)); + p.insert("background".into(), json!(background)); + (command, n, vec![out]) + } + PublishFormat::Video => { + let v = &prof.video; + let n = range_params(&mut p, v.range, last); + p.insert("scale".into(), json!(v.scale)); + p.insert("audio".into(), json!(v.audio)); + if crate::vfs::in_memory() { + skip = Some("video is made with ffmpeg, which a web browser can't run".to_string()); + } + ("file.export_video", n, vec![out]) + } + PublishFormat::Lottie => { + let l = &prof.lottie; + range_params(&mut p, l.range, last); + p.insert("background".into(), json!(l.background)); + ("file.export_lottie", 0, vec![out]) + } + PublishFormat::SpriteSheet => { + let sh = &prof.sprite_sheet; + let n = range_params(&mut p, sh.range, last); + p.insert("scale".into(), json!(sh.scale)); + if sh.columns > 0 { + p.insert("columns".into(), json!(sh.columns)); + } + p.insert("padding".into(), json!(sh.padding)); + p.insert("background".into(), json!(sh.background)); + let map = out.with_extension("json"); + ("file.export_sprite_sheet", n, vec![out, map]) + } + PublishFormat::PngSequence => { + let q = &prof.png_sequence; + let n = range_params(&mut p, q.range, last); + p.insert("scale".into(), json!(q.scale)); + ("file.export_png_sequence", n, vec![out]) + } + PublishFormat::Png => { + let (sc, local) = doc.locate(prof.png.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + p.insert("scale".into(), json!(prof.png.scale)); + ("file.export_png", 1, vec![out]) + } + PublishFormat::Svg => { + let (sc, local) = doc.locate(prof.svg.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + ("file.export_svg", 1, vec![out]) + } + PublishFormat::Audio => { + let a = &prof.audio; + range_params(&mut p, a.range, last); + p.insert("rate".into(), json!(a.rate)); + p.insert("bits".into(), json!(a.bits)); + if !anicraft_doc::sound::has_sounds(doc) { + skip = Some("the movie has no sounds".to_string()); + } + ("file.export_audio", 0, vec![out]) + } + }; + let key = if f == PublishFormat::PngSequence { "dir" } else { "path" }; + p.insert(key.into(), json!(path_s)); + // Publish's own confirmation covers replacing files (`existing`). + p.insert("confirm".into(), json!(true)); + // Two formats writing one file would leave only the second (names compared as the + // case-insensitive file systems of Windows and macOS see them). + let same = |a: &Path, b: &Path| a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase(); + if let Some(other) = steps.iter().find(|s| s.outputs.iter().any(|o| outputs.iter().any(|n| same(o, n)))) { + return Err(format!("{} and {} would both write {}: give one of them another output name", other.format.label(), f.label(), rel.display())); + } + steps.push(Step { format: f, command, params: Value::Object(p), outputs, scene, frames, skip }); + } + Ok(steps) +} + +/// Files already there that publishing `steps` would replace (a PNG sequence's folder when it +/// holds exported frames), leaving out those this session published itself. +pub fn existing(s: &Session, steps: &[Step]) -> Vec { + let mut v = Vec::new(); + for st in steps.iter().filter(|st| st.skip.is_none()) { + for o in &st.outputs { + if s.published.contains(o) { + continue; + } + let there = if st.format == PublishFormat::PngSequence { + crate::vfs::list(o, 10_000).iter().any(|e| { + let n = e.file_name().map(|n| n.to_string_lossy()).unwrap_or_default(); + n.starts_with("frame_") && n.ends_with(".png") + }) + } else { + crate::vfs::exists(o) + }; + if there { + v.push(o.clone()); + } + } + } + v +} + +/// The formats `file.publish` params name, if they name any. +pub fn formats_param(p: &Value) -> Result>> { + match p.get("formats") { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(list)) => list + .iter() + .take(64) + .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) + .collect::>>() + .map(Some), + Some(_) => Err(EngineError::Param("param 'formats' must be a list of format names".into())), + } +} + +/// The plan `file.publish` with `p` would run, for the confirmation (ADR 0004). +pub(crate) fn planned(s: &Session, p: &Value) -> Option> { + plan(&s.doc, s.path.as_deref(), formats_param(p).ok()?.as_deref()).ok() +} + +// ----- running --------------------------------------------------------------------------------- + +/// How one format went. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Published, + Skipped, + Failed, + Cancelled, +} + +impl Status { + pub fn key(self) -> &'static str { + match self { + Status::Published => "published", + Status::Skipped => "skipped", + Status::Failed => "failed", + Status::Cancelled => "cancelled", + } + } +} + +/// What one format did: the files it wrote, and what its exporter left out or why it failed. +#[derive(Clone, Debug)] +pub struct Outcome { + pub format: PublishFormat, + pub status: Status, + pub files: Vec, + /// The exporter's report of what it approximated or left out (HTML, Lottie), or why the + /// format was skipped, failed or stopped. + pub message: String, +} + +impl Outcome { + pub fn to_json(&self) -> Value { + json!({ + "format": self.format.key(), + "label": self.format.label(), + "status": self.status.key(), + "files": self.files.iter().map(|f| f.display().to_string()).collect::>(), + "message": self.message, + }) + } +} + +/// Every format's outcome, in order. +#[derive(Clone, Debug, Default)] +pub struct Report { + pub outcomes: Vec, +} + +impl Report { + pub fn count(&self, s: Status) -> usize { + self.outcomes.iter().filter(|o| o.status == s).count() + } + pub fn files(&self) -> Vec { + self.outcomes.iter().flat_map(|o| o.files.iter().cloned()).collect() + } + /// One sentence per format with something to say (left out, skipped, failed), in order. + pub fn summary(&self) -> String { + self.outcomes + .iter() + .filter(|o| !o.message.is_empty()) + .map(|o| { + let m = o.message.trim_end_matches('.'); + match o.status { + Status::Published => format!("{}: {m}.", o.format.label()), + Status::Skipped => format!("{} skipped: {m}.", o.format.label()), + Status::Failed => format!("{} failed: {m}.", o.format.label()), + Status::Cancelled => format!("{}: {m}.", o.format.label()), + } + }) + .collect::>() + .join(" ") + } + pub fn to_json(&self) -> Value { + json!({ + "published": self.count(Status::Published), + "skipped": self.count(Status::Skipped), + "failed": self.count(Status::Failed), + "cancelled": self.count(Status::Cancelled) > 0, + "files": self.files().iter().map(|f| f.display().to_string()).collect::>(), + "formats": self.outcomes.iter().map(Outcome::to_json).collect::>(), + "report": self.summary(), + }) + } +} + +/// Runs the steps of a publish one at a time, on a session of its own (the document as it was +/// when Publish started), so the editor keeps working while it runs. +pub struct Publisher { + s: Session, + steps: Vec, + next: usize, + report: Report, + control: Arc, +} + +impl Publisher { + pub fn new(doc: Document, path: Option, steps: Vec, control: Arc) -> Publisher { + let mut s = Session::new(doc); + s.path = path; + s.job = Some(control.clone()); + Publisher { s, steps, next: 0, report: Report::default(), control } + } + + /// The format running next (or now), if any is left. + pub fn current(&self) -> Option { + self.steps.get(self.next).map(|s| s.format) + } + + pub fn done(&self) -> bool { + self.next >= self.steps.len() + } + + /// Runs the next format; `None` when every format has run. Once cancelled, the formats + /// left are cancelled without running. + pub fn step(&mut self) -> Option<&Outcome> { + let st = self.steps.get(self.next)?.clone(); + self.next += 1; + let out = self.run(&st); + self.report.outcomes.push(out); + self.report.outcomes.last() + } + + fn run(&mut self, st: &Step) -> Outcome { + let mut out = Outcome { format: st.format, status: Status::Published, files: Vec::new(), message: String::new() }; + if self.control.cancelled() { + out.status = Status::Cancelled; + out.message = "not published (cancelled)".into(); + return out; + } + if let Some(why) = &st.skip { + out.status = Status::Skipped; + out.message.clone_from(why); + return out; + } + self.control.begin(st.frames); + // Folders below the document's are made as needed. + for o in &st.outputs { + let dir = if st.format == PublishFormat::PngSequence { Some(o.as_path()) } else { o.parent() }; + if let Some(d) = dir.filter(|d| !d.as_os_str().is_empty()) + && let Err(e) = crate::vfs::create_dir_all(d) + { + out.status = Status::Failed; + out.message = format!("could not make the folder {}: {e}", d.display()); + return out; + } + } + self.s.scene = st.scene.min(self.s.doc.scenes.len().saturating_sub(1)); + self.s.editing.clear(); + self.s.frame = 0; + let result = crate::find_command(st.command).ok_or_else(|| EngineError::UnknownCommand(st.command.into())).and_then(|spec| (spec.run)(&mut self.s, &st.params)); + match result { + Ok(v) => { + out.files.clone_from(&st.outputs); + out.message = v.get("report").and_then(Value::as_str).unwrap_or("").to_string(); + } + Err(EngineError::Cancelled) => { + out.status = Status::Cancelled; + out.message = if st.format == PublishFormat::PngSequence { "stopped part-way (the frames written so far are kept)".into() } else { "stopped before it was written".into() }; + } + Err(e) => { + out.status = Status::Failed; + out.message = e.to_string(); + } + } + out + } + + /// Runs every format left. + pub fn run_all(&mut self) { + while self.step().is_some() {} + } + + pub fn report(&self) -> &Report { + &self.report + } +} + +fn publish_cmd(s: &mut Session, p: &Value) -> Result { + let steps = plan(&s.doc, s.path.as_deref(), formats_param(p)?.as_deref()).map_err(EngineError::State)?; + if steps.is_empty() { + return Err(EngineError::State("no format is on in Publish Settings: turn one on first".into())); + } + let control = s.job.clone().unwrap_or_default(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control); + job.run_all(); + let report = job.report(); + s.published.extend(report.files()); + Ok(report.to_json()) +} + +// ----- the settings commands ------------------------------------------------------------------- + +fn settings_get(s: &mut Session, _: &Value) -> Result { + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// The profile, and for each format whether it is on, its output and where that goes now (or +/// why it can't go anywhere). +pub fn settings_json(doc: &Document, path: Option<&Path>) -> Value { + let base = base(path); + let formats: Vec = PublishFormat::ALL + .iter() + .map(|f| { + let (on, output) = doc.publish.target(*f); + let mut o = json!({"format": f.key(), "label": f.label(), "enabled": on, "output": output}); + match base.as_ref().map_err(Clone::clone).and_then(|(dir, name)| resolve(*f, output, name).map(|r| dir.join(r))) { + Ok(at) => { + o["path"] = json!(at.display().to_string()); + o["exists"] = json!(crate::vfs::exists(&at)); + } + Err(e) => o["error"] = json!(e), + } + o + }) + .collect(); + let (folder, name) = base.map_or((Value::Null, Value::Null), |(d, n)| (json!(d.display().to_string()), json!(n))); + json!({"profile": serde_json::to_value(&*doc.publish).unwrap_or(Value::Null), "formats": formats, "folder": folder, "name": name}) +} + +/// Keys each format's options take (besides `enabled` and `output`). +fn option_keys(f: PublishFormat) -> &'static [&'static str] { + match f { + PublishFormat::Html => &["title", "sound", "fit"], + PublishFormat::Gif => &["from", "to", "scale", "loop"], + PublishFormat::Apng | PublishFormat::Webp => &["from", "to", "scale", "loop", "background"], + PublishFormat::Video => &["from", "to", "scale", "audio"], + PublishFormat::Lottie => &["from", "to", "background"], + PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], + PublishFormat::PngSequence => &["from", "to", "scale"], + PublishFormat::Png => &["frame", "scale"], + PublishFormat::Svg => &["frame"], + PublishFormat::Audio => &["from", "to", "rate", "bits"], + } +} + +/// A movie-frame param: absent (unchanged), null (the movie's end) or a frame. +fn opt_end(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(_) => opt_u32(p, key).map(|v| Some(v.map(|f| f.min(crate::MAX_FRAME)))), + } +} + +fn set_range(r: &mut FrameRange, p: &Value) -> Result<()> { + if let Some(v) = opt_end(p, "from")? { + r.from = v; + } + if let Some(v) = opt_end(p, "to")? { + r.to = v; + } + if let (Some(a), Some(b)) = (r.from, r.to) + && b < a + { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + Ok(()) +} + +fn set_scale(v: &mut f32, p: &Value) -> Result<()> { + if let Some(x) = opt_f32(p, "scale")? { + if !(x > 0.0 && x <= MAX_PUBLISH_SCALE) { + return Err(EngineError::Param(format!("param 'scale' must be in (0, {MAX_PUBLISH_SCALE}]"))); + } + *v = x; + } + Ok(()) +} + +fn set_bool(v: &mut bool, p: &Value, key: &str) -> Result<()> { + if let Some(b) = opt_bool(p, key)? { + *v = b; + } + Ok(()) +} + +/// Changes format `f`'s switch, output and options from `p`. +fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { + if let Some(obj) = p.as_object() { + let known = option_keys(f); + if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "format" | "enabled" | "output" | "confirm") && !known.contains(&k.as_str())) { + return Err(EngineError::Param(format!("{} has no option '{k}' (it has {})", f.label(), known.join(", ")))); + } + } + if let Some(o) = opt_str(p, "output")? { + resolve(f, o, "name").map_err(|e| EngineError::Param(format!("{}: {e}", f.label())))?; + *prof.target_mut(f).1 = o.trim().to_string(); + } + if let Some(b) = opt_bool(p, "enabled")? { + *prof.target_mut(f).0 = b; + } + match f { + PublishFormat::Html => { + let h = &mut prof.html; + if let Some(t) = opt_str(p, "title")? { + if t.chars().count() > MAX_TITLE_CHARS { + return Err(EngineError::Param(format!("param 'title' is at most {MAX_TITLE_CHARS} characters"))); + } + h.title = t.to_string(); + } + set_bool(&mut h.sound, p, "sound")?; + set_bool(&mut h.fit, p, "fit")?; + } + PublishFormat::Gif => { + let g = &mut prof.gif; + set_range(&mut g.range, p)?; + set_scale(&mut g.scale, p)?; + set_bool(&mut g.looping, p, "loop")?; + } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = match f { + PublishFormat::Apng => (&mut prof.apng.range, &mut prof.apng.scale, &mut prof.apng.plays, &mut prof.apng.background), + _ => (&mut prof.webp.range, &mut prof.webp.scale, &mut prof.webp.plays, &mut prof.webp.background), + }; + set_range(range, p)?; + set_scale(scale, p)?; + if p.get("loop").is_some() { + *plays = crate::anim::plays(p)?; + } + set_bool(background, p, "background")?; + } + PublishFormat::Video => { + let v = &mut prof.video; + set_range(&mut v.range, p)?; + set_scale(&mut v.scale, p)?; + set_bool(&mut v.audio, p, "audio")?; + } + PublishFormat::Lottie => { + set_range(&mut prof.lottie.range, p)?; + set_bool(&mut prof.lottie.background, p, "background")?; + } + PublishFormat::SpriteSheet => { + let sh = &mut prof.sprite_sheet; + set_range(&mut sh.range, p)?; + set_scale(&mut sh.scale, p)?; + if let Some(c) = opt_u32(p, "columns")? { + sh.columns = c.min(10_000); + } + if let Some(x) = opt_u32(p, "padding")? { + if x > 256 { + return Err(EngineError::Param("param 'padding' must be at most 256".into())); + } + sh.padding = x; + } + set_bool(&mut sh.background, p, "background")?; + } + PublishFormat::PngSequence => { + set_range(&mut prof.png_sequence.range, p)?; + set_scale(&mut prof.png_sequence.scale, p)?; + } + PublishFormat::Png => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.png.frame = fr.min(crate::MAX_FRAME); + } + set_scale(&mut prof.png.scale, p)?; + } + PublishFormat::Svg => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.svg.frame = fr.min(crate::MAX_FRAME); + } + } + PublishFormat::Audio => { + let a = &mut prof.audio; + set_range(&mut a.range, p)?; + if let Some(r) = opt_u32(p, "rate")? { + if !(8_000..=192_000).contains(&r) { + return Err(EngineError::Param("param 'rate' must be between 8000 and 192000".into())); + } + a.rate = r; + } + if let Some(b) = opt_u32(p, "bits")? { + if !matches!(b, 16 | 24 | 32) { + return Err(EngineError::Param("param 'bits' must be 16, 24 or 32 (float)".into())); + } + a.bits = b; + } + } + } + Ok(()) +} + +fn settings_set(s: &mut Session, p: &Value) -> Result { + let mut prof = match p.get("profile") { + None | Some(Value::Null) => (*s.doc.publish).clone(), + Some(v) => { + let mut prof: PublishProfile = serde_json::from_value(v.clone()).map_err(|e| EngineError::Param(format!("param 'profile' is not a publish profile: {e}")))?; + prof.sanitize(); + prof + } + }; + match opt_str(p, "format")? { + Some(k) => { + let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; + apply(&mut prof, f, p)?; + } + None if p.get("profile").is_none_or(Value::is_null) && p.as_object().is_some_and(|o| o.keys().any(|k| k != "confirm" && k != "profile")) => { + return Err(EngineError::Param("name the 'format' to change, or pass a whole 'profile'".into())); + } + None => {} + } + if prof != *s.doc.publish { + s.doc.publish = Arc::new(prof); + } + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// Writes `files` (path, bytes) as one uncompressed ZIP archive, per PKWARE's APPNOTE (what the browser downloads +/// when Publish writes more than one file). Paths keep their folders, with `/` between them. +pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> { + let mut out: Vec = Vec::new(); + let mut central: Vec = Vec::new(); + let n = u16::try_from(files.len()).map_err(|_| "too many files for one archive".to_string())?; + let le16 = |v: &mut Vec, x: u16| v.extend_from_slice(&x.to_le_bytes()); + let le32 = |v: &mut Vec, x: u32| v.extend_from_slice(&x.to_le_bytes()); + for (path, data) in files { + let name: String = path.components().filter_map(|c| if let Component::Normal(p) = c { Some(p.to_string_lossy().into_owned()) } else { None }).collect::>().join("/"); + let name_len = u16::try_from(name.len()).map_err(|_| "a file name is too long".to_string())?; + let size = u32::try_from(data.len()).map_err(|_| format!("{name} is too large for a ZIP archive (4 GB)"))?; + let offset = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let crc = anicraft_xfl::zip::crc32(data); + // Local file header: version 2.0, UTF-8 names (bit 11), stored. + le32(&mut out, 0x0403_4b50); + for x in [20u16, 0x0800, 0, 0, 0x21] { + le16(&mut out, x); + } + for x in [crc, size, size] { + le32(&mut out, x); + } + le16(&mut out, name_len); + le16(&mut out, 0); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(data); + // Its central directory entry. + le32(&mut central, 0x0201_4b50); + for x in [20u16, 20, 0x0800, 0, 0, 0x21] { + le16(&mut central, x); + } + for x in [crc, size, size] { + le32(&mut central, x); + } + for x in [name_len, 0, 0, 0, 0] { + le16(&mut central, x); + } + le32(&mut central, 0); + le32(&mut central, offset); + central.extend_from_slice(name.as_bytes()); + } + let at = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let len = u32::try_from(central.len()).map_err(|_| "the archive is too large".to_string())?; + out.extend_from_slice(¢ral); + le32(&mut out, 0x0605_4b50); + for x in [0u16, 0, n, n] { + le16(&mut out, x); + } + le32(&mut out, len); + le32(&mut out, at); + le16(&mut out, 0); + Ok(out) +} + +#[cfg(test)] +#[path = "publish_tests.rs"] +mod tests; diff --git a/crates/engine/src/publish_tests.rs b/crates/engine/src/publish_tests.rs new file mode 100644 index 00000000..c30ac16b --- /dev/null +++ b/crates/engine/src/publish_tests.rs @@ -0,0 +1,307 @@ +//! Publish Settings and Publish (ADR 0060): the profile in the file, where outputs go, the +//! plan, running every exporter with its options, cancelling, the combined report, the +//! confirmation, the browser's archive. + +use super::*; +use crate::{EngineError, Session, vfs}; +use anicraft_doc::sample; +use serde_json::json; +use std::path::{Path, PathBuf}; + +fn temp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("anicraft-publish-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The demo, saved as `walk.anicraft` in a fresh folder. +fn saved(name: &str) -> (Session, PathBuf) { + let dir = temp(name); + let mut s = Session::new(sample::demo()); + run(&mut s, "file.save", json!({"path": dir.join("walk.anicraft").display().to_string()})); + (s, dir) +} + +#[test] +fn templates_resolve_inside_the_documents_folder() { + let r = |f, t: &str| resolve(f, t, "walk"); + assert_eq!(r(PublishFormat::Html, "{name}.html").unwrap(), PathBuf::from("walk.html")); + assert_eq!(r(PublishFormat::Gif, "web/{name}-small.gif").unwrap(), Path::new("web").join("walk-small.gif")); + assert_eq!(r(PublishFormat::Gif, "./{name}").unwrap(), PathBuf::from("walk.gif"), "a missing extension is the format's"); + assert_eq!(r(PublishFormat::Video, "{name}.MP4").unwrap(), PathBuf::from("walk.MP4")); + assert_eq!(r(PublishFormat::PngSequence, "{name}_frames").unwrap(), PathBuf::from("walk_frames"), "a folder has no extension"); + for bad in ["../{name}.gif", "/tmp/{name}.gif", "web/../../x.gif", "{title}.gif", "{name.gif", " ", "{name}.png"] { + assert!(r(PublishFormat::Gif, bad).is_err(), "{bad}"); + } + #[cfg(windows)] + assert!(r(PublishFormat::Gif, "C:\\x.gif").is_err() && r(PublishFormat::Gif, "C:x.gif").is_err()); + assert!(r(PublishFormat::Gif, &"a".repeat(600)).is_err()); + // The folder and name come from the document's path. + assert_eq!(base(Some(Path::new("art/walk.anicraft"))).unwrap(), (PathBuf::from("art"), "walk".to_string())); + assert!(base(None).is_err(), "an untitled document on disk saves first"); +} + +#[test] +fn settings_round_trip_through_the_file_and_older_files_get_defaults() { + let (mut s, dir) = saved("roundtrip"); + let v = run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "output": "web/{name}.gif", "scale": 0.5, "loop": false, "from": 2, "to": 9})); + let gif = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "gif").unwrap(); + assert_eq!(gif["path"], json!(dir.join("web").join("walk.gif").display().to_string())); + run(&mut s, "publish.settings_set", json!({"format": "html", "title": "Walk cycle", "sound": false})); + run(&mut s, "publish.settings_set", json!({"format": "audio", "rate": 22050, "bits": 24, "to": null})); + let path = dir.join("walk.anicraft"); + run(&mut s, "file.save", json!({})); + let back = crate::format::load(&path).unwrap(); + assert_eq!(*back.publish, *s.doc.publish); + let p = &back.publish; + assert!(p.gif.enabled && !p.gif.looping && p.gif.scale == 0.5 && p.gif.range == FrameRange { from: Some(2), to: Some(9) }); + assert_eq!((p.html.title.as_str(), p.html.sound, p.audio.rate, p.audio.bits), ("Walk cycle", false, 22050, 24)); + // An untouched profile isn't written at all, so files from before publish settings look + // the same: they open with the HTML page on and the rest off. + let mut fresh = Session::new(sample::demo()); + let text = serde_json::to_string(&fresh.doc).unwrap(); + assert!(!text.contains("\"publish\"")); + let older: anicraft_doc::Document = serde_json::from_str(&text).unwrap(); + assert_eq!(older.publish.enabled(), vec![PublishFormat::Html]); + // Settings are a document change: undo takes them back. + run(&mut fresh, "publish.settings_set", json!({"format": "svg", "enabled": true})); + assert!(fresh.is_dirty() && fresh.doc.publish.svg.enabled); + run(&mut fresh, "edit.undo", json!({})); + assert!(!fresh.doc.publish.svg.enabled); + // A whole profile, as publish.settings_get gives it. + let whole = run(&mut s, "publish.settings_get", json!({}))["profile"].clone(); + run(&mut fresh, "publish.settings_set", json!({"profile": whole})); + assert_eq!(*fresh.doc.publish, *s.doc.publish); +} + +#[test] +fn settings_refuse_what_publish_couldnt_use() { + let mut s = Session::new(sample::demo()); + let before = s.doc.publish.clone(); + for bad in [ + json!({"format": "flash"}), + json!({"format": "gif", "rate": 44100}), + json!({"format": "gif", "scale": 0}), + json!({"format": "gif", "scale": 9}), + json!({"format": "gif", "from": 9, "to": 2}), + json!({"format": "gif", "output": "../x.gif"}), + json!({"format": "gif", "output": "x.png"}), + json!({"format": "audio", "bits": 8}), + json!({"format": "audio", "rate": 1}), + json!({"format": "sprite_sheet", "padding": 999}), + json!({"format": "html", "title": "x".repeat(300)}), + json!({"format": "html", "enabled": "yes"}), + json!({"enabled": true}), + json!({"profile": 5}), + json!({"profile": {"gif": {"scale": "big"}}}), + ] { + assert!(s.execute("publish.settings_set", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc.publish, before, "a refused change changes nothing"); + assert!(!s.is_dirty()); +} + +#[test] +fn the_plan_runs_each_exporter_with_its_options() { + let mut doc = sample::demo(); + let p = std::sync::Arc::make_mut(&mut doc.publish); + p.gif.enabled = true; + p.gif.scale = 0.25; + p.gif.looping = false; + p.gif.range = FrameRange { from: Some(1), to: Some(4) }; + p.sprite_sheet.enabled = true; + p.sprite_sheet.columns = 2; + p.svg.enabled = true; + p.svg.frame = 5; + let steps = plan(&doc, Some(Path::new("art/walk.anicraft")), None).unwrap(); + let order: Vec = steps.iter().map(|s| s.format).collect(); + assert_eq!(order, [PublishFormat::Html, PublishFormat::Gif, PublishFormat::SpriteSheet, PublishFormat::Svg], "in Publish's order"); + let gif = &steps[1]; + assert_eq!(gif.command, "file.export_gif"); + assert_eq!((gif.params["scale"].as_f64(), gif.params["loop"].as_bool(), gif.params["from"].as_u64(), gif.params["to"].as_u64(), gif.frames), (Some(0.25), Some(false), Some(1), Some(4), 4)); + assert_eq!(gif.params["path"], json!(Path::new("art").join("walk.gif").display().to_string())); + assert_eq!(steps[2].outputs, vec![Path::new("art").join("walk_sheet.png"), Path::new("art").join("walk_sheet.json")], "the sheet and its frame map"); + assert_eq!(steps[2].params["columns"], 2); + assert_eq!((steps[3].scene, steps[3].params["frame"].as_u64()), (0, Some(5))); + // Only some formats, when asked. + let some = plan(&doc, Some(Path::new("walk.anicraft")), Some(&[PublishFormat::Svg])).unwrap(); + assert_eq!(some.len(), 1); + // Two formats writing one file is refused, whatever the case. + std::sync::Arc::make_mut(&mut doc.publish).png.enabled = true; + std::sync::Arc::make_mut(&mut doc.publish).png.output = "{name}_SHEET.png".into(); + let err = plan(&doc, Some(Path::new("walk.anicraft")), None).unwrap_err(); + assert!(err.contains("Sprite sheet") && err.contains("PNG image"), "{err}"); + // Untitled, it asks to save first. + assert!(plan(&doc, None, None).unwrap_err().contains("save")); +} + +#[test] +fn publish_writes_every_format_and_reports_once() { + let (mut s, dir) = saved("all"); + for p in [ + json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 3}), + json!({"format": "lottie", "enabled": true, "to": 3}), + json!({"format": "sprite_sheet", "enabled": true, "scale": 0.1, "to": 3, "columns": 2}), + json!({"format": "png_sequence", "enabled": true, "scale": 0.1, "to": 2, "output": "out/{name}_frames"}), + json!({"format": "png", "enabled": true, "scale": 0.1, "frame": 2}), + json!({"format": "svg", "enabled": true}), + json!({"format": "audio", "enabled": true}), + json!({"format": "video", "enabled": false}), + ] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let formats = v["formats"].as_array().unwrap(); + let status = |k: &str| formats.iter().find(|f| f["format"] == k).map(|f| f["status"].clone()).unwrap_or(Value::Null); + for k in ["html", "gif", "lottie", "sprite_sheet", "png_sequence", "png", "svg"] { + assert_eq!(status(k), "published", "{k}: {v}"); + } + assert_eq!(status("audio"), "skipped", "the demo has no sounds"); + assert_eq!(status("video"), Value::Null, "off formats don't run"); + assert_eq!((v["published"].as_u64(), v["skipped"].as_u64(), v["failed"].as_u64(), v["cancelled"].as_bool()), (Some(7), Some(1), Some(0), Some(false))); + let report = v["report"].as_str().unwrap(); + assert!(report.contains("Audio skipped: the movie has no sounds."), "{report}"); + // The files are there, made with each format's options. + for f in ["walk.html", "walk.gif", "walk.json", "walk_sheet.png", "walk_sheet.json", "walk.png", "walk.svg"] { + assert!(dir.join(f).is_file(), "{f}"); + } + let frames = std::fs::read_dir(dir.join("out").join("walk_frames")).unwrap().count(); + assert_eq!(frames, 3, "frames 1 to 3, in a folder made for them"); + let gif = std::fs::read(dir.join("walk.gif")).unwrap(); + let (w, h) = (u16::from_le_bytes([gif[6], gif[7]]), u16::from_le_bytes([gif[8], gif[9]])); + let view = anicraft_render::View::stage(&s.doc, 0.1); + assert_eq!((u32::from(w), u32::from(h)), (view.width, view.height), "the GIF's scale"); + let sheet: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("walk_sheet.json")).unwrap()).unwrap(); + assert_eq!(sheet["frames"].as_object().unwrap().len(), 4); + assert_eq!(v["files"].as_array().unwrap().len(), 8); + + // Publishing again replaces this session's own files without asking... + run(&mut s, "file.publish", json!({"formats": ["svg"]})); + // ...but another session (the next time the app starts) asks first. + run(&mut s, "file.save", json!({})); + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": dir.join("walk.anicraft").display().to_string()})); + let err = t.execute("file.publish", &json!({})).unwrap_err(); + assert!(matches!(err, EngineError::NeedsConfirmation(_)), "{err}"); + assert!(err.to_string().contains("walk.html"), "{err}"); + let c = t.confirmation("file.publish", &json!({})).unwrap(); + assert!(c.irreversible && c.message.contains("and 5 more"), "{}", c.message); + run(&mut t, "file.publish", json!({"confirm": true})); + assert!(t.confirmation("file.publish", &json!({})).is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn one_failing_format_doesnt_stop_the_others() { + let (mut s, dir) = saved("fail"); + run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 8})); + run(&mut s, "publish.settings_set", json!({"format": "svg", "enabled": true})); + let v = run(&mut s, "file.publish", json!({})); + assert_eq!((v["published"].as_u64(), v["failed"].as_u64()), (Some(2), Some(1)), "{v}"); + assert!(v["report"].as_str().unwrap().starts_with("Animated GIF failed: that GIF would be too large"), "{v}"); + assert!(dir.join("walk.svg").is_file() && !dir.join("walk.gif").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cancel_stops_cleanly() { + let (mut s, dir) = saved("cancel"); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1}), json!({"format": "svg", "enabled": true}), json!({"format": "png_sequence", "enabled": true, "scale": 0.1})] { + run(&mut s, "publish.settings_set", p); + } + // Cancelled after the first format: the rest never run. + let control = Arc::new(Control::default()); + let steps = plan(&s.doc, s.path.as_deref(), None).unwrap(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control.clone()); + assert_eq!(job.current(), Some(PublishFormat::Html)); + assert_eq!(job.step().map(|o| o.status), Some(Status::Published)); + control.cancel(); + job.run_all(); + let r = job.report(); + assert!(job.done() && r.count(Status::Cancelled) == 3, "{:?}", r.to_json()); + assert!(dir.join("walk.html").is_file() && !dir.join("walk.gif").exists() && !dir.join("walk.svg").exists() && !dir.join("walk_frames").exists()); + assert_eq!(r.to_json()["cancelled"], true); + + // Cancelled inside an export: the GIF stops between frames and writes nothing. + let stop = Arc::new(Control::default()); + stop.cancel(); + s.job = Some(stop.clone()); + let gif = dir.join("inside.gif"); + assert!(matches!(s.execute("file.export_gif", &json!({"path": gif.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!gif.exists()); + let seq = dir.join("seq"); + assert!(matches!(s.execute("file.export_png_sequence", &json!({"dir": seq.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(matches!(s.execute("file.export_sprite_sheet", &json!({"path": dir.join("s.png").display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!dir.join("s.png").exists()); + // Progress counts frames made. + let watch = Arc::new(Control::default()); + s.job = Some(watch.clone()); + watch.begin(4); + run(&mut s, "file.export_gif", json!({"path": gif.display().to_string(), "scale": 0.1, "to": 3})); + assert_eq!(watch.progress(), (4, 4)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn publish_refuses_what_it_cant_run() { + let mut s = Session::new(sample::demo()); + assert!(s.execute("file.publish", &json!({})).unwrap_err().to_string().contains("save the document first")); + for bad in [json!({"formats": "gif"}), json!({"formats": ["gif", 3]}), json!({"formats": ["nope"]}), json!({"formats": [null]})] { + assert!(s.execute("file.publish", &bad).is_err(), "{bad}"); + assert!(s.confirmation("file.publish", &bad).is_none()); + } + let (mut t, dir) = saved("none"); + run(&mut t, "publish.settings_set", json!({"format": "html", "enabled": false})); + assert!(t.execute("file.publish", &json!({})).unwrap_err().to_string().contains("no format is on")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn in_a_browser_every_file_comes_back_and_several_make_one_zip() { + std::thread::spawn(|| { + vfs::use_memory(); + // Untitled: the browser has no folders, so it publishes as "Untitled". + let mut s = Session::new(sample::demo()); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 2}), json!({"format": "video", "enabled": true}), json!({"format": "svg", "enabled": true, "output": "img/{name}.svg"})] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let video = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "video").unwrap().clone(); + assert_eq!(video["status"], "skipped"); + assert!(video["message"].as_str().unwrap().contains("web browser")); + let files = vfs::take_written(); + let names: Vec = files.iter().map(|(p, _)| p.to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(names, ["Untitled.gif", "Untitled.html", "img/Untitled.svg"]); + let z = zip(&files).unwrap(); + // The end record says three entries; each name is in the archive with `/` between folders. + let end = z.len() - 22; + assert_eq!(&z[end..end + 4], &[0x50, 0x4b, 0x05, 0x06]); + assert_eq!(u16::from_le_bytes([z[end + 10], z[end + 11]]), 3); + assert!(z.windows(16).any(|w| w == b"img/Untitled.svg")); + // AniCraft's hardened ZIP reader (the .fla one) opens it, checks every CRC, and gets + // each file back exactly. + let archive = anicraft_xfl::zip::Archive::open(&z).unwrap(); + for (p, data) in &files { + let name = p.to_string_lossy().replace('\\', "/"); + assert_eq!(archive.read(&name).unwrap().as_ref(), Some(data), "{name}"); + } + let total: usize = files.iter().map(|(_, d)| d.len()).sum(); + assert!(z.len() > total && z.len() < total + 400, "stored, not compressed: {} for {total}", z.len()); + }) + .join() + .unwrap(); +} + + +#[test] +fn plugins_may_read_but_not_change_or_run_publishing() { + use crate::cmds_plugin::plugin_may_call; + assert!(plugin_may_call("publish.settings_get").is_ok()); + assert!(plugin_may_call("publish.settings_set").is_err()); + assert!(plugin_may_call("file.publish").is_err()); +} diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs index e3a49050..6c8c003b 100644 --- a/crates/engine/src/rawsub_tests.rs +++ b/crates/engine/src/rawsub_tests.rs @@ -291,13 +291,14 @@ fn a_pasted_raw_shape_cuts_what_it_lands_on() { } 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) }] } + Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), 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()); + s.style.lock_fill = true; 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. @@ -383,6 +384,7 @@ fn subselection_timings() { fn the_eraser_takes_gradient_fills_too() { let mut s = raw_session(); s.style.fill_paint = Some(linear()); + s.style.lock_fill = true; 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})); diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index c28e4ecf..01014d59 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -94,14 +94,48 @@ impl FrameJob { } /// A stage picture's frame with the open symbol in front composed by `skin`: the timelines around -/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. +/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. With +/// onion skin on (not Edit Multiple Frames), the timeline the symbol was opened from shows its +/// own onion frames too, dimmed with it (ADR 0061). pub fn display_list_inside(doc: &Document, frame: u32, front: &Front, skin: &OnionSkin) -> DisplayList { let (scene, local) = doc.locate(frame); - let mut around = doc.timeline(scene).clone(); - around.layers.retain(|l| l.id != front.layer); - let mut dl = anicraft_doc::evaluate_timeline(doc, &around, local); let tl = &front.timeline; - dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + let parent = front.parent.as_ref().filter(|_| skin.ghosts && !skin.edit_multiple); + let mut dl = DisplayList::default(); + // Back to front: the picture's layers from the bottom up, each its own timeline. + for l in doc.timeline(scene).layers.iter().rev() { + if l.id == front.layer { + dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + } else if let Some(p) = parent.filter(|p| p.layer == l.id) { + dl.append(parent_onion(doc, p, front, skin)); + } else { + dl.append(anicraft_doc::evaluate_timeline(doc, &anicraft_doc::Timeline { layers: vec![l.clone()] }, local)); + } + } + dl +} + +/// The timeline around an open symbol with its onion frames, all at its dim opacity. Markers that +/// follow the playhead reach as many frames from the parent's frame; anchored ones (which name +/// the symbol's frames) as far as they reach from the symbol's playhead. +fn parent_onion(doc: &Document, p: &crate::editing::Around, front: &Front, skin: &OnionSkin) -> DisplayList { + let mut own = *skin; + if skin.anchored() { + let (first, last) = skin.range(front.frame, front.timeline.frame_count()); + own.markers = crate::onion::Markers::Relative { before: front.frame.saturating_sub(first), after: last.saturating_sub(front.frame) }; + } + let composed = crate::onion::compose_timeline(&p.timeline, p.frame, Some(&own), |f| anicraft_doc::evaluate_timeline_at(doc, &p.timeline, f, p.at)); + // It fades as one, as the dimmed instance it replaces does: everything in a group at `dim`. + let alpha = if p.dim.is_finite() { p.dim.clamp(0.0, 1.0) } else { 1.0 }; + let mut dl = DisplayList::default(); + dl.groups.push(anicraft_doc::Group { parent: None, alpha, blend: Default::default(), filters: Arc::from(Vec::new()), clip: None }); + dl.append(composed); + for g in dl.groups.iter_mut().skip(1) { + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in dl.items.iter_mut().filter(|i| i.masks.is_none()) { + it.group = Some(it.group.unwrap_or(0)); + } dl } diff --git a/crates/engine/src/scale_grid_tests.rs b/crates/engine/src/scale_grid_tests.rs new file mode 100644 index 00000000..74b1ca2e --- /dev/null +++ b/crates/engine/src/scale_grid_tests.rs @@ -0,0 +1,175 @@ +//! 9-slice scaling end to end (ADR 0055): the command, undo, the file format, plug-ins and what +//! a scaled instance renders. + +use crate::Session; +use anicraft_doc::{ScaleGrid, SymbolId}; +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}")) +} + +fn err(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 100 × 40 rounded drawing object turned into a symbol (its space runs from (−50, −20) to +/// (50, 20)), its instance selected. +fn panel() -> (Session, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 40, "radius": 10, "fill": "#3366cc", "stroke": "#000000", "stroke_width": 2})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"})); + (s, SymbolId(v["symbol"].as_u64().unwrap())) +} + +fn grid(s: &Session, id: SymbolId) -> Option { + s.doc.symbol(id).and_then(|x| x.scale_grid) +} + +#[test] +fn turning_guides_on_puts_them_a_quarter_in_and_moving_one_keeps_the_rest() { + let (mut s, id) = panel(); + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(v["symbol"], json!(id.0)); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -25.0, right: 25.0, top: -10.0, bottom: 10.0 })); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + run(&mut s, "symbol.set_scale_grid", json!({"top": -12})); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -40.0, right: 40.0, top: -12.0, bottom: 10.0 })); + // Off hides them: the symbol scales as a whole (ADR 0057). + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + assert_eq!(v["scale_grid"], Value::Null); + assert_eq!(grid(&s, id), None); + // Moving a guide turns them on, from where they were. + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "left": -45})); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -45.0, right: 40.0, top: -12.0, bottom: 10.0 })); +} + +#[test] +fn guides_switched_off_and_on_again_come_back_where_they_were() { + let (mut s, id) = panel(); + let moved = ScaleGrid { left: -40.0, right: 30.0, top: -12.0, bottom: 6.0 }; + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 30, "top": -12, "bottom": 6})); + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let kept = |s: &Session| s.doc.symbol(id).and_then(|x| x.scale_grid_kept); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved)), "kept, not applied"); + // Off twice keeps them still; saved and opened, they are still there. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let file = crate::format::to_json(&s.doc).unwrap(); + assert!(file.contains("scale_grid_kept")); + let mut s = Session::new(crate::format::from_json(&file).unwrap()); + assert_eq!(kept(&s), Some(moved)); + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "on": true})); + assert_eq!((grid(&s, id), kept(&s)), (Some(moved), None), "on again: back where they were"); + // Undo goes back to off with the guides kept. + s.undo().unwrap(); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved))); + // A kept grid that isn't usable, or kept beside guides that are on, is dropped on load. + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid_kept = Some(ScaleGrid { left: 5.0, right: -5.0, top: 0.0, bottom: 1.0 }); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!(d.library[0].scale_grid_kept, None); + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid = Some(moved); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!((d.library[0].scale_grid, d.library[0].scale_grid_kept), (Some(moved), None)); +} + +#[test] +fn bad_guides_are_refused_and_change_nothing() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + let before = grid(&s, id); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"left": 30})).contains("left"), "past the right guide"); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"bottom": -20})).contains("top")); + err(&mut s, "symbol.set_scale_grid", json!({"left": 1e30})); + err(&mut s, "symbol.set_scale_grid", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": false, "left": 1})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true, "symbol": 999_999})); + assert_eq!(grid(&s, id), before); + // With nothing selected and no symbol open there is nothing to set it on. + run(&mut s, "edit.deselect", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true})); +} + +#[test] +fn each_change_is_one_undo_step_and_a_drag_of_moves_is_one_too() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(s.undo_label(), Some("9-Slice Scaling")); + // A guide dragged: many moves, one step. + s.begin_gesture("Move 9-Slice Guide"); + for x in [-26, -30, -35, -38] { + run(&mut s, "symbol.set_scale_grid", json!({"left": x})); + } + s.end_gesture(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-38.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-25.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id), None); + s.redo().unwrap(); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn inside_the_open_symbol_it_needs_no_selection() { + let (mut s, id) = panel(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn the_guides_survive_the_file_and_older_files_open_without_them() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(text.contains("\"scale_grid\"")); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back.symbol(id).and_then(|x| x.scale_grid), grid(&s, id)); + // A symbol whose guides are off keeps them apart (ADR 0057), and one that never had any + // writes nothing for them, so older files read the same. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"scale_grid\"") && text.contains("\"scale_grid_kept\"")); + assert!(!crate::format::to_json(&panel().0.doc).unwrap().contains("scale_grid")); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); + // Unusable guides in a file are dropped, not drawn. + let mut doc = s.doc.clone(); + if let Some(sym) = doc.library.first_mut() { + std::sync::Arc::make_mut(sym).scale_grid = Some(ScaleGrid { left: 9.0, right: -9.0, top: 0.0, bottom: 1.0 }); + } + let text = crate::format::to_json(&doc).unwrap(); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); +} + +#[test] +fn a_scaled_instance_renders_with_unscaled_corners() { + // The CPU renderer (the oracle) draws the sliced instance: at 3× wide its top-left corner + // pixels match the unscaled instance's, while plain scaling stretches them. + let (mut s, _) = panel(); + s.doc.stage = anicraft_doc::Stage { width: 400, height: 200, ..s.doc.stage }; + let corner = |s: &Session| { + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + // The instance's top-left corner is at (100, 100): the 12 × 12 pixels there. + (0..12u32).flat_map(|y| (0..12u32).map(move |x| (x, y))).map(|(x, y)| format!("{:?}", img.pixel(100 + x, 100 + y))).collect::>() + }; + let at_one = corner(&s); + // Scale about the left edge: 3× wide. + run(&mut s, "modify.transform", json!({"a": 3, "b": 0, "c": 0, "d": 1, "e": -200, "f": 0})); + let plain = corner(&s); + assert_ne!(plain, at_one, "plain scaling stretches the corner"); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + assert_eq!(corner(&s), at_one, "9-slice keeps it"); +} + +#[test] +fn plug_ins_may_set_guides() { + assert!(crate::cmds_plugin::plugin_may_call("symbol.set_scale_grid").is_ok()); +} diff --git a/crates/engine/src/selection_tests.rs b/crates/engine/src/selection_tests.rs index 6ae32395..5ace4650 100644 --- a/crates/engine/src/selection_tests.rs +++ b/crates/engine/src/selection_tests.rs @@ -206,7 +206,7 @@ fn properties_edits_apply_to_each_layer() { 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.color, anicraft_doc::ColorEffect::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!() }; @@ -375,6 +375,41 @@ fn break_apart_works_on_each_layer() { assert_eq!(s.selected_layers(), vec![top, bottom]); } +/// #253: a drawing object (Object Drawing) breaks apart into raw shapes that merge with the raw +/// drawing they touch, so it can be edited as a merged shape again; one undo step brings the +/// object back. +#[test] +fn break_apart_turns_a_drawing_object_into_raw_shapes() { + let mut s = Session::default(); + s.style.object_drawing = false; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#00ff00", "stroke": null})); + let raw = s.visible_elements().len(); + let obj = el_id(&run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null, "object": true}))); + let squiggle = el_id(&run(&mut s, "draw.freehand", json!({"points": [[300, 0], [320, 30], [340, 0], [360, 30]], "object": true}))); + let shapes = |s: &Session| -> Vec<(ElementId, bool)> { + s.visible_elements().iter().filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.id, sh.merge)), + _ => None, + }).collect() + }; + assert!(shapes(&s).iter().filter(|(id, _)| [obj, squiggle].contains(id)).all(|(_, m)| !m), "drawn as objects"); + let before = s.doc.clone(); + let steps = s.history_len(); + run(&mut s, "element.select", json!({"ids": [obj.0, squiggle.0]})); + let v = run(&mut s, "modify.break_apart", json!({})); + assert!(v["created"].as_u64().unwrap() >= 2, "{v}"); + assert!(shapes(&s).iter().all(|(_, m)| *m), "every shape is raw now: {:?}", shapes(&s)); + assert!(!shapes(&s).iter().any(|(id, _)| *id == obj), "the object merged into the drawing"); + assert!(s.visible_elements().len() > raw + 1, "the red square cut the green one"); + assert!(!s.selection.is_empty(), "what came out of it is selected"); + assert_eq!(s.history_len(), steps + 1); + s.undo().unwrap(); + assert!(s.doc == before, "one undo brings the objects back"); + // Nothing to break apart: an error, not a no-op step. + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("modify.break_apart", &json!({})).is_err()); +} + // ----- 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). @@ -562,3 +597,14 @@ fn clicking_a_layer_name_selects_its_artwork() { run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); assert!(s.selection.is_empty()); } + +#[test] +fn select_with_toggle_takes_one_out_and_puts_it_back_across_layers() { + // Shift+Space on a stage element (ADR 0064): the others stay selected, on either layer. + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && !s.selection.contains(bottom, b)); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b)); + assert!(s.execute("element.select", &json!({"ids": [b.0], "toggle": "yes"})).is_err(), "toggle is a bool"); +} diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs new file mode 100644 index 00000000..1468ae5d --- /dev/null +++ b/crates/engine/src/snap.rs @@ -0,0 +1,273 @@ +//! One snap engine for every tool (ADR 0076): a point being drawn, dragged or moved snaps to +//! the artwork (Snap to Objects, ADR 0041/0045), the scene's guides, the grid and whole pixels, +//! in a fixed order of priority: +//! +//! 1. an object's **point** (corner or end) within the radius: both coordinates; +//! 2. a **guide**, each coordinate on its own (a vertical guide takes x, a horizontal one y; two +//! together are their crossing); +//! 3. an object's **line** or fill edge, only when no guide took either coordinate; +//! 4. the **grid**, each coordinate not yet taken; +//! 5. a whole **pixel**, each coordinate not yet taken (Snap to Pixels). +//! +//! The radius is what the caller asks (`snap`, in the space the tool works in: 10 screen pixels +//! at the zoom of the moment), so snapping feels the same at every zoom. The guides' and grid's +//! own accuracy scales it. Guides and the grid are in stage pixels; while a symbol is open in +//! place (ADR 0045) points are mapped there and back, so they line up with what the stage shows. + +use crate::Session; +use anicraft_doc::GuideAxis; +use anicraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +/// How near a point must come to a guide or a grid line to snap to it (Animate's Snap +/// accuracy), as a factor of the radius the tool asks for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Accuracy { + /// Must be close: half the usual distance. + Close, + #[default] + Normal, + /// Can be distant: twice the usual distance. + Distant, + /// Always snap (the grid only): every point goes to the nearest line. + Always, +} + +impl Accuracy { + pub const ALL: [Accuracy; 4] = [Accuracy::Close, Accuracy::Normal, Accuracy::Distant, Accuracy::Always]; + + pub fn key(self) -> &'static str { + match self { + Accuracy::Close => "close", + Accuracy::Normal => "normal", + Accuracy::Distant => "distant", + Accuracy::Always => "always", + } + } + pub fn parse(s: &str) -> Option { + Accuracy::ALL.into_iter().find(|a| a.key() == s.trim().to_ascii_lowercase()) + } + /// The name a menu or dialog shows (English; translated where it is drawn). + pub fn label(self) -> &'static str { + match self { + Accuracy::Close => "Must be close", + Accuracy::Normal => "Normal", + Accuracy::Distant => "Can be distant", + Accuracy::Always => "Always snap", + } + } + fn factor(self) -> f32 { + match self { + Accuracy::Close => 0.5, + Accuracy::Normal => 1.0, + Accuracy::Distant => 2.0, + Accuracy::Always => f32::INFINITY, + } + } +} + +/// Whether the rulers, grid and guides show and snap (View › Rulers, Grid, Guides, Snapping): +/// the editor's working preferences, kept from session to session by the editor and never in +/// the document or its undo history (ADR 0076). How the grid and guides look, and where the +/// guides are, is the document's (`anicraft_doc::Aids`, `Scene::guides`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ViewAids { + pub rulers: bool, + pub show_grid: bool, + pub show_guides: bool, + /// Guides can't be dragged (commands that move or delete one refuse too). + pub lock_guides: bool, + pub snap_grid: bool, + pub snap_guides: bool, + pub snap_pixels: bool, + pub grid_accuracy: Accuracy, + pub guide_accuracy: Accuracy, +} + +impl Default for ViewAids { + fn default() -> Self { + // As in Animate: guides show and snap; the rulers, grid and pixel snapping are off. + ViewAids { rulers: false, show_grid: false, show_guides: true, lock_guides: false, snap_grid: false, snap_guides: true, snap_pixels: false, grid_accuracy: Accuracy::Normal, guide_accuracy: Accuracy::Normal } + } +} + +/// What a point snapped to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SnapTo { + /// An anchor (corner or end). + Point, + /// A guide. + Guide, + /// A stroke or a fill's edge. + Line, + /// A grid line. + Grid, + /// A whole pixel. + Pixel, +} + +impl SnapTo { + pub fn key(&self) -> &'static str { + match self { + SnapTo::Point => "point", + SnapTo::Guide => "guide", + SnapTo::Line => "line", + SnapTo::Grid => "grid", + SnapTo::Pixel => "pixel", + } + } + /// Lower wins (the order of priority above). + pub(crate) fn rank(self) -> u8 { + match self { + SnapTo::Point => 0, + SnapTo::Guide => 1, + SnapTo::Line => 2, + SnapTo::Grid => 3, + SnapTo::Pixel => 4, + } + } +} + +/// The artwork's points and lines to snap to, as each caller gathers them. +pub(crate) trait ObjectTargets { + /// The nearest point within `r` of `p`, and how far it is. + fn nearest_point(&self, p: Vec2, r: f32) -> Option<(Vec2, f32)>; + /// The nearest point on a line or fill edge within `r` of `p`. + fn nearest_line(&self, p: Vec2, r: f32) -> Option<(Vec2, f32)>; +} + +/// Where stage space is from the space tools work in: `stage = origin + scale · p`. +fn space(s: &Session) -> (Vec2, f32) { + match s.edit_view() { + Some(v) if v.scale.is_finite() && v.scale > 1e-4 && v.origin.is_finite() => (v.origin, v.scale), + _ => (Vec2::ZERO, 1.0), + } +} + +impl Session { + /// Whether anything snaps at all: a radius, and Snap to Objects, Guides, Grid or Pixels on. + pub(crate) fn snaps(&self, r: f32) -> bool { + r > 0.0 && (self.style.snap_objects || self.aids.snap_guides || self.aids.snap_grid || self.aids.snap_pixels) + } + + /// The scene's guides (the main timeline's, also while a symbol is open). + pub fn guides(&self) -> &[anicraft_doc::Guide] { + self.doc.scenes.get(self.scene).map_or(&[], |sc| &sc.guides[..]) + } +} + +/// The nearest of `lines` within `r` of `v`. +fn nearest(v: f32, r: f32, lines: impl Iterator) -> Option { + lines.map(|q| (q, (q - v).abs())).filter(|(_, d)| *d <= r).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(q, _)| q) +} + +/// The nearest grid line within `r` of `v`, lines every `spacing`. +fn grid_line(v: f32, spacing: f32, r: f32) -> Option { + if spacing.is_nan() || spacing <= 0.0 { + return None; + } + let q = (v / spacing).round() * spacing; + ((q - v).abs() <= r && q.is_finite()).then_some(q) +} + +/// Where `p` (in the space tools work in) snaps within `r`, by the order of priority above; +/// `objects` are the artwork's points and lines (`None`: not looked at). `None` when nothing is +/// near or nothing snaps. +pub(crate) fn resolve(s: &Session, p: Vec2, r: f32, objects: Option<&dyn ObjectTargets>) -> Option<(Vec2, SnapTo)> { + if !(r > 0.0 && r.is_finite() && p.is_finite()) { + return None; + } + let objects = objects.filter(|_| s.style.snap_objects); + if let Some((q, _)) = objects.and_then(|t| t.nearest_point(p, r)) { + return Some((q, SnapTo::Point)); + } + let (o, k) = space(s); + let sp = o + p * k; + let sr = r * k; + let a = &s.aids; + // Each coordinate: where it goes and why. + type Axis = Option<(f32, SnapTo)>; + let (mut x, mut y): (Axis, Axis) = (None, None); + if a.snap_guides { + // Guides snap within the radius at most ("always" is the grid's). + let gr = sr * a.guide_accuracy.factor().min(2.0); + let at = |axis: GuideAxis| s.guides().iter().filter(move |g| g.axis == axis).map(|g| g.at); + x = nearest(sp.x, gr, at(GuideAxis::Vertical)).map(|v| (v, SnapTo::Guide)); + y = nearest(sp.y, gr, at(GuideAxis::Horizontal)).map(|v| (v, SnapTo::Guide)); + } + if x.is_none() + && y.is_none() + && let Some((q, _)) = objects.and_then(|t| t.nearest_line(p, r)) + { + return Some((q, SnapTo::Line)); + } + if a.snap_grid { + let g = s.doc.aids.grid; + let gr = sr * a.grid_accuracy.factor(); + x = x.or_else(|| grid_line(sp.x, g.spacing_x, gr).map(|v| (v, SnapTo::Grid))); + y = y.or_else(|| grid_line(sp.y, g.spacing_y, gr).map(|v| (v, SnapTo::Grid))); + } + if a.snap_pixels { + x = x.or(Some((sp.x.round(), SnapTo::Pixel))); + y = y.or(Some((sp.y.round(), SnapTo::Pixel))); + } + let to = [x, y].into_iter().flatten().map(|(_, t)| t).min_by_key(|t| t.rank())?; + let q = Vec2::new(x.map_or(sp.x, |v| v.0), y.map_or(sp.y, |v| v.0)); + let back = (q - o) * (1.0 / k); + back.is_finite().then_some((back, to)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Session; + use anicraft_doc::{Document, Guide}; + use std::sync::Arc; + + fn session(guides: &[Guide]) -> Session { + let mut d = Document::default(); + Arc::make_mut(&mut d.scenes[0]).guides = guides.to_vec(); + let mut s = Session::new(d); + s.style.snap_objects = false; + s + } + + #[test] + fn guides_snap_each_axis_and_their_crossing() { + let s = session(&[Guide { axis: GuideAxis::Vertical, at: 100.0 }, Guide { axis: GuideAxis::Horizontal, at: 50.0 }]); + assert_eq!(resolve(&s, Vec2::new(104.0, 300.0), 10.0, None), Some((Vec2::new(100.0, 300.0), SnapTo::Guide))); + assert_eq!(resolve(&s, Vec2::new(97.0, 58.0), 10.0, None), Some((Vec2::new(100.0, 50.0), SnapTo::Guide))); + assert_eq!(resolve(&s, Vec2::new(120.0, 300.0), 10.0, None), None, "too far"); + assert_eq!(resolve(&s, Vec2::new(104.0, 300.0), 0.0, None), None, "no radius: nothing snaps (Shift)"); + } + + #[test] + fn the_radius_follows_the_zoom() { + // The shell asks for 10 screen pixels: 10 / zoom stage pixels. + let s = session(&[Guide { axis: GuideAxis::Vertical, at: 100.0 }]); + for (zoom, off, snaps) in [(1.0, 8.0, true), (1.0, 12.0, false), (4.0, 2.0, true), (4.0, 3.0, false), (0.25, 39.0, true), (0.25, 41.0, false)] { + let r = 10.0 / zoom; + assert_eq!(resolve(&s, Vec2::new(100.0 + off, 0.0), r, None).is_some(), snaps, "zoom {zoom}, {off} px off"); + } + } + + #[test] + fn grid_pixels_and_accuracy() { + let mut s = session(&[]); + s.aids.snap_grid = true; + assert_eq!(resolve(&s, Vec2::new(43.0, 18.0), 10.0, None), Some((Vec2::new(40.0, 20.0), SnapTo::Grid))); + s.aids.grid_accuracy = Accuracy::Close; + assert_eq!(resolve(&s, Vec2::new(46.0, 13.0), 10.0, None), None, "Must be close: within 5"); + s.aids.grid_accuracy = Accuracy::Always; + assert_eq!(resolve(&s, Vec2::new(49.0, 9.0), 1.0, None), Some((Vec2::new(40.0, 0.0), SnapTo::Grid))); + s.aids.snap_grid = false; + s.aids.snap_pixels = true; + assert_eq!(resolve(&s, Vec2::new(4.4, 7.6), 10.0, None), Some((Vec2::new(4.0, 8.0), SnapTo::Pixel))); + // A guide on x wins over the grid there; y still goes to the grid, then pixels. + let mut s = session(&[Guide { axis: GuideAxis::Vertical, at: 33.0 }]); + s.aids.snap_grid = true; + assert_eq!(resolve(&s, Vec2::new(36.0, 22.0), 10.0, None), Some((Vec2::new(33.0, 20.0), SnapTo::Guide))); + } +} diff --git a/crates/engine/src/swatch_tests.rs b/crates/engine/src/swatch_tests.rs new file mode 100644 index 00000000..d4e6b061 --- /dev/null +++ b/crates/engine/src/swatch_tests.rs @@ -0,0 +1,261 @@ +//! The Swatches panel's commands (ADR 0078). + +use crate::Session; +use anicraft_doc::{Document, ElementId, ElementKind, Paint, Rgba, Shape, Swatch, SwatchPaint}; +use serde_json::{Value, json}; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn blank() -> Session { + Session::new(Document::default()) +} + +fn shape(s: &Session, id: u64) -> Shape { + s.visible_elements() + .iter() + .find(|e| e.id == ElementId(id)) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + .expect("a shape") +} + +/// A selected 100 × 100 square at (x, 100), red with a black stroke. +fn square(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"}))["element"].as_u64().unwrap() +} + +fn find(s: &Session, name: &str) -> usize { + s.doc.swatches.iter().position(|w| w.name == name).unwrap_or_else(|| panic!("no swatch {name}")) +} + +#[test] +fn a_new_document_has_the_default_swatches_and_older_files_open_with_them() { + let s = blank(); + assert_eq!(s.doc.swatches.len(), 19); + // A file from before swatches (no "swatches" key) opens with the default set; the set is + // not written while unchanged, so such files stay as they were. + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"swatches\""), "the default set isn't written"); + let back = crate::format::from_json(&text).unwrap(); + assert!(anicraft_doc::swatch::is_default_set(&back.swatches)); +} + +#[test] +fn swatches_round_trip_through_the_file() { + let mut s = blank(); + run(&mut s, "swatch.clear", json!({"confirm": true})); + run(&mut s, "swatch.add", json!({"color": "#12345680", "name": "Ink"})); + run(&mut s, "swatch.add", json!({"type": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.7, "color": "#ff000080"}], "spread": "reflect", "linear_rgb": true, "focal": 0.5, "name": "Glow"})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(*back.swatches, *s.doc.swatches); + assert_eq!(back.swatches.len(), 4); + let SwatchPaint::Radial { spread, linear_rgb, focal, stops } = &back.swatches[3].paint else { panic!("a radial swatch") }; + assert_eq!((spread.key(), *linear_rgb, *focal, stops.len()), ("reflect", true, 0.5, 2)); + // An explicitly empty list stays empty (it isn't the default set). + let mut e = blank(); + run(&mut e, "swatch.clear", json!({"confirm": true})); + run(&mut e, "swatch.remove", json!({"index": 0})); + run(&mut e, "swatch.remove", json!({"index": 0})); + let back = crate::format::from_json(&crate::format::to_json(&e.doc).unwrap()).unwrap(); + assert!(back.swatches.is_empty()); + // A damaged file's swatches are repaired or dropped on open. + let mut v: Value = serde_json::from_str(&text).unwrap(); + v["document"]["swatches"] = json!([{"paint": {"type": "linear", "stops": [{"offset": 0, "color": {"r": 0, "g": 0, "b": 0, "a": 1}}]}}, {"name": "ok", "paint": {"type": "solid", "color": {"r": 9, "g": 0.5, "b": 0, "a": 1}}}]); + let fixed = crate::format::from_json(&v.to_string()).unwrap(); + assert_eq!(fixed.swatches.len(), 1); + assert_eq!(fixed.swatches[0].paint.primary_color().r, 1.0); +} + +#[test] +fn add_takes_the_current_fill_or_stroke_or_a_given_swatch() { + let mut s = blank(); + let n = s.doc.swatches.len(); + s.style.set_fill_color(Rgba::hex(0x3366ff)); + s.style.stroke = Rgba::hex(0x00aa00); + assert_eq!(run(&mut s, "swatch.add", json!({}))["index"], n); + assert_eq!(s.doc.swatches[n].paint, SwatchPaint::Solid { color: Rgba::hex(0x3366ff) }); + run(&mut s, "swatch.add", json!({"from": "stroke", "at": 0, "name": "Leaf"})); + assert_eq!((s.doc.swatches[0].name.as_str(), s.doc.swatches[0].paint.primary_color()), ("Leaf", Rgba::hex(0x00aa00))); + // A gradient fill swatch adds its ramp and options. + run(&mut s, "paint.set_fill", json!({"type": "radial", "spread": "repeat", "selection": false})); + let i = run(&mut s, "swatch.add", json!({"from": "fill"}))["index"].as_u64().unwrap() as usize; + assert!(matches!(&s.doc.swatches[i].paint, SwatchPaint::Radial { spread: anicraft_doc::Spread::Repeat, .. })); + // Each add is one undo step. + let len = s.doc.swatches.len(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), len - 1); + for bad in [json!({"from": "middle"}), json!({"type": "solid"}), json!({"type": "linear"}), json!({"type": "conic", "color": "#000000"}), json!({"from": "fill", "color": "#000000"}), json!({"color": "#00"}), json!({"color": "#000000", "at": 9999})] { + assert!(s.execute("swatch.add", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn remove_move_duplicate_and_rename() { + let mut s = blank(); + let n = s.doc.swatches.len(); + let red = s.doc.swatches[6].clone(); + run(&mut s, "swatch.move", json!({"from": 6, "to": 0})); + assert_eq!(s.doc.swatches[0], red); + assert_eq!(s.doc.swatches.len(), n); + run(&mut s, "swatch.move", json!({"from": 0, "to": n - 1})); + assert_eq!(s.doc.swatches[n - 1], red, "to the end"); + assert_eq!(run(&mut s, "swatch.duplicate", json!({"index": n - 1}))["index"], n); + assert_eq!(s.doc.swatches[n], red); + run(&mut s, "swatch.rename", json!({"index": n, "name": " Fire engine "})); + assert_eq!(s.doc.swatches[n].name, "Fire engine"); + run(&mut s, "swatch.remove", json!({"index": n})); + assert_eq!(s.doc.swatches.len(), n); + for (id, bad) in [("swatch.remove", json!({"index": n})), ("swatch.remove", json!({})), ("swatch.move", json!({"from": 0, "to": n})), ("swatch.duplicate", json!({"index": -1})), ("swatch.rename", json!({"index": 0}))] { + assert!(s.execute(id, &bad).is_err(), "{id} {bad}"); + } +} + +#[test] +fn apply_sets_the_fill_or_the_stroke_of_the_selection_and_the_tool() { + let mut s = blank(); + let id = square(&mut s, 50.0); + let blue = find_colour(&s, 0x0000ff); + // Fill: the selection and the fill swatch. + assert_eq!(run(&mut s, "swatch.apply", json!({"index": blue}))["changed"], 1); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::hex(0x0000ff))); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::BLACK, "the stroke is untouched"); + // Stroke: the selection's lines and the stroke colour; the fill stays. + let yellow = find_colour(&s, 0xffff00); + run(&mut s, "swatch.apply", json!({"index": yellow, "target": "stroke"})); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + assert_eq!(s.style.stroke, Rgba::hex(0xffff00)); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + // A gradient swatch is fitted to the shape, and the swatch holds it. + let glow = find(&s, "Red ball"); + run(&mut s, "swatch.apply", json!({"index": glow})); + let Some(Paint::Radial { center, radius, stops, .. }) = shape(&s, id).fill else { panic!("a radial fill") }; + assert_eq!(stops[0].color, Rgba::hex(0xff8080)); + assert!(center.x.abs() < 1e-3 && center.y.abs() < 1e-3 && (radius - 50.0).abs() < 1.0, "fitted to the 100-unit square: {center:?} {radius}"); + assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. }))); + // Strokes are one colour. + assert!(s.execute("swatch.apply", &json!({"index": glow, "target": "stroke"})).is_err()); + // With `selection: false` only the tool colour changes. + let white = find_colour(&s, 0xffffff); + assert_eq!(run(&mut s, "swatch.apply", json!({"index": white, "selection": false}))["changed"], 0); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::WHITE)); + assert!(matches!(shape(&s, id).fill, Some(Paint::Radial { .. }))); + // Nothing selected: the tool colour. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "stroke"})); + assert_eq!(s.style.stroke, Rgba::hex(0x0000ff)); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + // On the selection: one undo step (the tool colour alone is no document change). + run(&mut s, "edit.select_all", json!({})); + let before = s.history_len(); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "fill"})); + assert_eq!(s.history_len(), before + 1); + assert!(s.execute("swatch.apply", &json!({"index": 0, "target": "outline"})).is_err()); +} + +fn find_colour(s: &Session, rgb: u32) -> usize { + s.doc.swatches.iter().position(|w| w.paint == SwatchPaint::Solid { color: Rgba::hex(rgb) }).expect("a default colour") +} + +#[test] +fn clear_and_reset_ask_first_and_undo() { + let mut s = blank(); + let c = s.confirmation("swatch.clear", &json!({})).expect("clearing 19 swatches asks"); + assert!(!c.irreversible, "undoable, so it asks by default only"); + run(&mut s, "swatch.clear", json!({})); + assert_eq!(*s.doc.swatches, vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + assert!(s.confirmation("swatch.clear", &json!({})).is_none(), "nothing to lose"); + assert!(s.confirmation("swatch.reset", &json!({})).is_some()); + run(&mut s, "swatch.reset", json!({})); + assert!(anicraft_doc::swatch::is_default_set(&s.doc.swatches)); + assert!(s.confirmation("swatch.reset", &json!({})).is_none(), "already the default set"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), 2); +} + +/// Runs `f` on a thread of its own with the in-memory file store, so no other test's files +/// (on a reused test thread) see it. +fn in_memory(f: impl FnOnce() + Send + 'static) { + std::thread::spawn(move || { + crate::vfs::use_memory(); + f(); + }) + .join() + .unwrap(); +} + +#[test] +fn swatch_files_export_and_import() { + in_memory(swatch_files_export_and_import_in_memory); +} + +fn swatch_files_export_and_import_in_memory() { + let mut s = blank(); + run(&mut s, "swatch.add", json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff00"}], "name": "Fade"})); + let v = run(&mut s, "swatch.export", json!({"path": "set.json"})); + assert_eq!(v["swatches"], 20); + let text = crate::vfs::read_to_string(Path::new("set.json")).unwrap(); + assert!(text.contains("\"format\": \"anicraft-swatches\"") && text.contains("\"Fade\"") && text.contains("#ffffff00")); + assert!(s.confirmation("swatch.export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible), "overwriting a file asks"); + // Another document: added at the end, or replacing (which asks by default). + let mut t = blank(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "set.json"}))["count"], 39); + assert!(t.confirmation("swatch.import", &json!({"path": "set.json", "replace": true})).is_some_and(|c| !c.irreversible)); + run(&mut t, "swatch.import", json!({"path": "set.json", "replace": true})); + assert_eq!(*t.doc.swatches, *s.doc.swatches, "the same swatches, exactly"); + // Unknown swatches in a newer file are skipped; junk is refused. + crate::vfs::put(Path::new("new.json"), br##"{"format": "anicraft-swatches", "version": 2, "swatches": [{"type": "conic"}, {"type": "solid", "color": "#010203"}]}"##.to_vec()).unwrap(); + let before = t.doc.swatches.len(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "new.json"}))["imported"], 1); + assert_eq!(t.doc.swatches.len(), before + 1); + for (name, body) in [("a.json", "{}"), ("b.json", "[1, 2]"), ("c.json", "not json"), ("d.json", r#"{"format": "anicraft-brushes"}"#), ("e.json", r#"{"format": "anicraft-swatches", "swatches": []}"#)] { + crate::vfs::put(Path::new(name), body.as_bytes().to_vec()).unwrap(); + assert!(t.execute("swatch.import", &json!({"path": name})).is_err(), "{name}"); + } + assert!(t.execute("swatch.import", &json!({"path": "missing.json"})).is_err()); +} + +#[test] +fn gimp_palettes_import() { + in_memory(gimp_palettes_import_in_memory); +} + +fn gimp_palettes_import_in_memory() { + let mut s = blank(); + crate::vfs::put(Path::new("brand.gpl"), b"GIMP Palette\nName: Brand\nColumns: 3\n#\n230 57 70\tRed\n 29 53 87\tNavy\n241 250 238 Untitled\n".to_vec()).unwrap(); + run(&mut s, "swatch.import", json!({"path": "brand.gpl", "replace": true, "confirm": true})); + assert_eq!(s.doc.swatches.len(), 3); + assert_eq!(s.doc.swatches[0].name, "Red"); + assert_eq!(s.doc.swatches[1].paint.primary_color().to_hex(), "#1d3557"); + assert_eq!(s.doc.swatches[2].name, ""); + // Then they paint like any swatch. + let id = square(&mut s, 0.0); + run(&mut s, "swatch.apply", json!({"index": 1})); + assert_eq!(shape(&s, id).fill.map(|p| p.primary_color().to_hex()), Some("#1d3557".into())); +} + +#[test] +fn swatches_are_bounded() { + let mut s = blank(); + s.doc.swatches = std::sync::Arc::new(vec![Swatch::solid(Rgba::BLACK); anicraft_doc::MAX_SWATCHES]); + assert!(s.execute("swatch.add", &json!({"color": "#ffffff"})).is_err()); + assert!(s.execute("swatch.duplicate", &json!({"index": 0})).is_err()); + let list = run(&mut s, "swatch.list", json!({})); + assert_eq!(list["count"], anicraft_doc::MAX_SWATCHES); + assert_eq!(list["swatches"][3]["index"], 3); +} + +#[test] +fn plug_ins_edit_swatches_but_not_swatch_files() { + use crate::cmds_plugin::plugin_may_call; + for id in ["swatch.add", "swatch.apply", "swatch.remove", "swatch.move", "swatch.list", "swatch.clear"] { + assert!(plugin_may_call(id).is_ok(), "{id}"); + } + assert!(plugin_may_call("swatch.import").is_err() && plugin_may_call("swatch.export").is_err()); +} diff --git a/crates/engine/src/template_tests.rs b/crates/engine/src/template_tests.rs new file mode 100644 index 00000000..c14f0678 --- /dev/null +++ b/crates/engine/src/template_tests.rs @@ -0,0 +1,153 @@ +//! Templates (ADR 0065): every built-in template opens as a new untitled document and saves, +//! and Save as Template keeps the document with a picture in the user's folder, round trip. + +use super::*; +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 temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-templates-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// `panic_hunt_every_command` leaves `file.*` out (they touch the disk): the template commands +/// and timeline drops get hostile params here, with every folder inside a temporary one. +#[test] +fn template_and_timeline_drop_commands_never_panic_on_hostile_params() { + let dir = temp_dir("fuzz"); + let folder = dir.display().to_string(); + let junk = [ + Value::Null, + json!([]), + json!("x"), + json!({}), + json!({"folder": folder}), + json!({"folder": folder, "name": 7}), + json!({"folder": folder, "name": "a", "category": ["x"]}), + json!({"folder": folder, "name": "\u{0}", "category": "\u{202e}"}), + json!({"folder": folder, "name": "é".repeat(64), "category": "ü".repeat(65)}), + json!({"folder": 3, "name": "a"}), + json!({"folder": folder, "name": "ok", "confirm": "yes"}), + json!({"template": 3}), + json!({"template": ""}), + json!({"path": ""}), + json!({"path": dir.join("nope.anicraft").display().to_string()}), + json!({"path": folder, "confirm": true}), + json!({"paths": ["a.png"], "to": "timeline", "layer": -1, "frame": 1e30}), + json!({"paths": ["a.wav"], "to": "timeline", "layer": "x", "frame": "y"}), + json!({"paths": ["a.svg"], "to": "timeline", "layer": 1, "frame": 0, "x": f64::NAN}), + ]; + for id in ["file.templates", "file.new_from_template", "file.save_as_template", "file.delete_template", "file.drop"] { + for p in &junk { + let mut s = Session::new(anicraft_doc::sample::demo()); + let _ = s.execute(id, p); + let mut confirmed = p.clone(); + if let Some(o) = confirmed.as_object_mut() { + o.insert("confirm".into(), json!(true)); + } + let _ = s.execute(id, &confirmed); + } + } +} + +#[test] +fn every_built_in_template_opens_untitled_and_survives_a_save() { + let dir = temp_dir("builtin"); + let list = run(&mut Session::default(), "file.templates", json!({})); + let builtin = list["builtin"].as_array().unwrap(); + assert_eq!(builtin.len(), anicraft_doc::templates::TEMPLATES.len()); + assert!(list["user"].as_array().unwrap().is_empty()); + for t in builtin { + let id = t["id"].as_str().unwrap(); + let mut s = Session::new(anicraft_doc::sample::demo()); + s.path = Some(dir.join("was.anicraft")); + let v = run(&mut s, "file.new_from_template", json!({"template": id})); + assert_eq!(v["template"], t["name"]); + assert!(s.path.is_none() && !s.is_dirty(), "{id}: a new, untitled document"); + assert_eq!((u64::from(s.doc.stage.width), u64::from(s.doc.stage.height)), (t["width"].as_u64().unwrap(), t["height"].as_u64().unwrap())); + // Drawing works straight away on a drawing layer, and it saves and opens again. + let active = s.active_layer().unwrap(); + assert!(active.kind == anicraft_doc::LayerKind::Normal && !active.locked, "{id}: the active layer takes drawing"); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); + let path = dir.join(format!("{id}.anicraft")); + run(&mut s, "file.save_as", json!({"path": path.display().to_string()})); + let saved = s.doc.clone(); + run(&mut s, "file.open", json!({"path": path.display().to_string()})); + assert!(s.doc == saved, "{id}: round trip"); + // Thumbnails render (the shell draws these on the start screen). + let png = crate::cmds_template::picture_png(&s.doc).unwrap(); + assert!(png.len() > 100); + } + let mut s = Session::default(); + assert!(s.execute("file.new_from_template", &json!({"template": "nope"})).is_err()); + assert!(s.execute("file.new_from_template", &json!({})).is_err()); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard", "path": "x.anicraft"})).is_err()); + // Over unsaved work it asks first, like New. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.new_from_template", &json!({"template": "storyboard"})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard"})).is_err()); + run(&mut s, "file.new_from_template", json!({"template": "storyboard", "confirm": true})); + assert_eq!(s.doc.stage.width, 1920); +} + +#[test] +fn save_as_template_keeps_the_document_and_a_picture_and_opens_as_new() { + let dir = temp_dir("user"); + let folder = dir.display().to_string(); + let mut s = Session::new(anicraft_doc::sample::demo()); + let mine = dir.join("walk.anicraft"); + run(&mut s, "file.save_as", json!({"path": mine.display().to_string()})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let doc = s.doc.clone(); + let v = run(&mut s, "file.save_as_template", json!({"folder": folder, "name": " Walk cycle ", "category": "Characters"})); + let path = dir.join("Characters").join("Walk cycle.anicraft"); + assert_eq!(v["path"].as_str(), Some(path.display().to_string().as_str())); + assert!(path.is_file() && path.with_extension("png").is_file(), "{v}"); + assert_eq!(s.path.as_deref(), Some(mine.as_path()), "the open document keeps its own file"); + assert!(s.is_dirty(), "and its unsaved changes"); + // Listed, with its picture; a default category when none is given. + run(&mut s, "file.save_as_template", json!({"folder": folder, "name": "Blank"})); + let list = run(&mut s, "file.templates", json!({"folder": folder})); + let user: Vec<(String, String, bool)> = list["user"].as_array().unwrap().iter().map(|t| (t["category"].as_str().unwrap().to_string(), t["name"].as_str().unwrap().to_string(), t["thumbnail"].is_string())).collect(); + assert_eq!(user, [("Characters".to_string(), "Walk cycle".to_string(), true), (crate::cmds_template::DEFAULT_CATEGORY.to_string(), "Blank".to_string(), true)]); + // Opened from the template: the same document, new and untitled. + let mut other = Session::default(); + run(&mut other, "file.new_from_template", json!({"path": path.display().to_string()})); + assert!(other.doc == doc && other.path.is_none() && !other.is_dirty()); + assert!(other.recent.is_empty(), "a template is not a recent file"); + // The same name again replaces it only when confirmed. + let again = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.confirmation("file.save_as_template", &again).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.save_as_template", &again).is_err()); + let mut confirmed = again.clone(); + confirmed["confirm"] = json!(true); + run(&mut s, "file.save_as_template", confirmed); + // Names that can't be file names are refused before anything is written. + for (name, category) in [("", "x"), (" ", "x"), ("a/b", "x"), ("a", "..\\up"), ("CON", "x"), ("ok", "lpt1"), (".hidden", "x"), ("x", "dot."), ("tab\there", "x")] { + let p = json!({"folder": folder, "name": name, "category": category}); + assert!(s.execute("file.save_as_template", &p).is_err(), "{p}"); + } + let long = "x".repeat(crate::cmds_template::MAX_NAME_CHARS + 1); + assert!(s.execute("file.save_as_template", &json!({"folder": folder, "name": long})).is_err()); + // Deleting always confirms, and takes the picture and the emptied category with it. + let del = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.execute("file.delete_template", &del).is_err()); + assert!(path.is_file()); + let mut del = del; + del["confirm"] = json!(true); + run(&mut s, "file.delete_template", del.clone()); + assert!(!path.exists() && !path.with_extension("png").exists() && !dir.join("Characters").exists()); + assert!(s.execute("file.delete_template", &del).is_err(), "gone already"); + assert_eq!(run(&mut s, "file.templates", json!({"folder": folder}))["user"].as_array().map(Vec::len), Some(1)); + // A folder that isn't there lists nothing, and a non-template file doesn't open. + assert_eq!(run(&mut s, "file.templates", json!({"folder": dir.join("nope").display().to_string()}))["user"].as_array().map(Vec::len), Some(0)); + assert!(s.execute("file.new_from_template", &json!({"path": dir.join("x.png").display().to_string(), "confirm": true})).is_err()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e1d514c7..06acd4a2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -552,6 +552,17 @@ 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::>()}), + // Brush presets, curves and the Paint Brush (ADR 0068): junk, extremes, both modes. + json!({"points": [[0, 0, 0.5], [300, 40, 1], [600, 0, 0]], "preset": "chalk", "as_stroke": true, "curve": [[0, 1], [0.5, 0], [1, 1]], "taper_start": 50, "taper_end": 50}), + json!({"points": [[0, 0], [1e5, 1e5]], "preset": "dotted", "spacing": 5, "jitter": 50, "size": 2000, "name": "x", "to": "y"}), + json!({"points": [[0, 0], [10, 0]], "preset": "nope", "curve": "wobbly", "spacing": 1, "jitter": -1, "name": "", "from": "missing", "names": [1, 2]}), + json!({"points": [[f64::MAX, 0]], "curve": [[f64::NAN, 2]], "pressure_size": "yes", "pressure_opacity": 1, "as_stroke": "no", "name": "Chalk", "to": "Pencil"}), + json!({"points": (0..2000).map(|i| json!([f64::from(i), f64::from(i % 7) * 3.0, f64::from(i % 3) * 0.5])).collect::>(), "preset": "ink_pen", "as_stroke": true, "name": "a".repeat(5000)}), + // Swatches (ADR 0078): junk kinds, indices and paints, both targets, a missing file. + json!({"index": 0, "from": 18, "to": 0, "target": "stroke", "name": "a".repeat(5000)}), + json!({"index": 12, "target": "stroke", "selection": false, "type": "radial", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}], "focal": 0.98, "at": 0}), + json!({"index": u64::MAX, "from": "nowhere", "target": 3, "type": "conic", "stops": [{"offset": 2, "color": "#00"}], "spread": "wrap", "path": "no/such/palette.gpl"}), + json!({"color": "#ff000000", "name": "\u{0}\n", "at": u64::MAX, "replace": true, "path": ""}), // 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"}), @@ -617,6 +628,11 @@ fn panic_hunt_every_command() { 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}), + // Shape armatures (ADR 0071): the shaped session's tail is 3, its bones 100 and 103. + json!({"shape": 3, "head": [1e30, 0], "tail": [-1e30, 0], "parent": 103, "points": [0, 1, u64::MAX], "mode": "add"}), + json!({"shape": 3, "head": [150, 150], "tail": [150, 150], "bone": 103, "points": (0..30).collect::>(), "mode": "remove"}), + json!({"parent": 100, "tail": [250, 290], "bone": 100, "points": [], "mode": "auto", "points_": true}), + json!({"bone": 100, "points": ["a", -1, 1e30], "mode": 7}), // 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]]}), @@ -632,6 +648,19 @@ fn panic_hunt_every_command() { json!({"first": 0, "last": 50, "scale_x": -1, "pivot": [0, 0], "edge": "vcenter", "to_stage": true, "merge": false}), json!({"first": 3, "last": 1, "edge": "right", "layer": u64::MAX, "items": [[0, 0, 0]]}), json!({"first": 0, "last": 99_999, "layer": 0, "items": (0..200).map(|i| json!([i, i, i])).collect::>()}), + // 9-slice guides (ADR 0055): crossed, huge, not numbers, moved while turned off. + json!({"on": true, "left": 90, "right": 10, "top": 1e30, "bottom": -1e30, "symbol": 1}), + json!({"on": false, "left": 5}), + json!({"on": "x", "left": f64::NAN, "right": "y", "top": null}), + json!({"left": -1e7, "right": 1e7, "top": -1e7, "bottom": 1e7}), + json!({"on": true, "symbol": u64::MAX}), + // Publish Settings (ADR 0060): ends past the movie, junk scales and names, whole + // profiles out of range. + json!({"format": "gif", "from": u64::MAX, "to": -1, "scale": f64::NAN, "output": "{name}\u{0}.gif"}), + json!({"format": "png", "frame": u64::MAX, "scale": 1e-30, "output": "a/b/c/../../{name}"}), + json!({"format": "sprite_sheet", "columns": u64::MAX, "padding": 256, "from": null, "to": null, "output": "{name}{name}{name}.png"}), + json!({"profile": {"gif": {"scale": 1e30, "range": {"from": 5, "to": 1}, "output": ""}, "audio": {"bits": 3, "rate": 0}, "html": {"title": "x"}}}), + json!({"profile": {"png": {"frame": 99_999, "enabled": true}}, "format": "svg", "enabled": true}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -672,6 +701,38 @@ fn panic_hunt_every_command() { } assert_eq!((b1, b2), (100, 102), "the hostile params name these bones"); rig.set_frame(4); + // A shape armature: a tail with two bones, bent at frame 8, a point bound by hand (ADR 0071). + let mut shaped = Session::default(); + shaped.style.object_drawing = false; + shaped.execute("draw.rect", &json!({"x": 100, "y": 140, "w": 200, "h": 20})).unwrap(); + shaped.doc.next_id = 100; + let tail = shaped.doc.timeline(0).layers[0].keyframes[0].elements[0].id.0; + let sb1 = shaped.execute("bone.add_in_shape", &json!({"shape": tail, "head": [100, 150], "tail": [200, 150]})).unwrap()["bone"].as_u64().unwrap(); + let sb2 = shaped.execute("bone.add_in_shape", &json!({"parent": sb1, "tail": [300, 150]})).unwrap()["bone"].as_u64().unwrap(); + for (id, p) in [("bone.pose", json!({"bone": sb2, "angle": 60, "frame": 8})), ("bone.bind", json!({"bone": sb1, "points": [0], "mode": "add"}))] { + shaped.execute(id, &p).unwrap(); + } + assert_eq!((tail, sb1, sb2), (3, 100, 103), "the hostile params name these"); + shaped.set_frame(4); + // Asset Warp (ADR 0079): a warped rectangle and bitmap, a pin moved at frame 8 inside a + // tween, the playhead mid-tween, the rectangle selected. + let (mut warped, wr, wb) = crate::tests_warp::warped(); + let pin = |s: &mut Session, el: u64, x: f32, y: f32| s.execute("warp.pin_add", &json!({"element": el, "x": x, "y": y})).unwrap()["pin"].as_u64().unwrap(); + let (wp1, wp2) = (pin(&mut warped, wr, 110.0, 140.0), pin(&mut warped, wr, 290.0, 140.0)); + let wp3 = pin(&mut warped, wb, 290.0, 230.0); + for (id, p) in [("timeline.goto", json!({"frame": 8})), ("timeline.insert_keyframe", json!({})), ("timeline.goto", json!({"frame": 0})), ("timeline.create_tween", json!({})), ("warp.pin_move", json!({"element": wr, "pin": wp2, "x": 300, "y": 220, "frame": 8}))] { + warped.execute(id, &p).unwrap(); + } + warped.selection = crate::Selection::only(warped.layer, [anicraft_doc::ElementId(wr)]); + warped.set_frame(4); + hostile.extend([ + json!({"element": wr, "pin": wp2, "x": 1e30, "y": -1e30, "dx": 1e7, "dy": -1e7, "frame": 99_999, "resolution": 0}), + json!({"element": wr, "pin": wp1, "x": 200, "y": 140, "dx": f64::NAN, "resolution": 48}), + json!({"element": wb, "pin": wp3, "x": 0, "y": 0, "dx": -1e6, "dy": 1e6, "resolution": u64::MAX}), + json!({"element": wb, "pin": u64::MAX, "x": 290, "y": 231, "frame": 4, "resolution": 2}), + json!({"element": u64::MAX, "pin": "a", "x": "b", "y": [1], "resolution": -3}), + json!({"element": wr, "x": 299.9, "y": 179.9, "pin": wp1, "dx": 0.0001}), + ]); // 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(); @@ -741,8 +802,54 @@ fn panic_hunt_every_command() { json!({"items": [{"symbol": ball}, {"symbol": ball}, {"folder": inner}, null], "x": "a"}), json!({"items": (0..1500).map(|_| json!({"symbol": ball})).collect::>(), "x": 0, "y": 0}), json!({"sound": SOUND, "symbol": ball, "x": 10, "y": 10}), + // Find and Replace and the Movie Explorer (ADR 0058): patterns that are slow in + // backtracking engines or too large, replacements that would nest a symbol in itself, + // stale hits, junk paths, rows and pages. + json!({"kind": "text", "text": "(a+)+$", "regex": true, "with": "$1$1$1${x}", "in": ["text", "labels", "layers", "instances", "scripts"], "scope": "document"}), + json!({"kind": "text", "text": "a{1000}{1000}", "regex": true, "with": ""}), + json!({"kind": "text", "text": "", "with": "x"}), + json!({"kind": "text", "text": "[a-z]", "regex": true, "with": "", "whole_word": false, "match_case": true, "confirm": true}), + json!({"kind": "text", "text": "L", "with": "", "at": {"scene": 0, "layer": 1, "field": "layer_name", "start": u64::MAX}}), + json!({"kind": "text", "text": "e", "with": "x".repeat(1000), "at": {"symbol": ball, "layer": u64::MAX, "field": "text", "frame": -1}}), + json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "in": ["fills", "strokes", "text", "nope"]}), + json!({"kind": "color", "color": "#3d8bfd", "with": "#000000", "scope": "document"}), + json!({"kind": "font", "font": "Inter", "with": "No Such Font"}), + json!({"kind": "symbol", "symbol": ball, "with": ball, "scope": "document"}), + json!({"kind": "sound", "sound": SOUND, "with": SOUND}), + json!({"kind": "bitmap", "bitmap": bm.0, "with": bm.0, "scope": "document"}), + json!({"kind": "nope", "layer": u64::MAX, "path": [{"layer": 1, "frame": u32::MAX, "element": u64::MAX}], "symbol": ball, "scene": 0}), + json!({"path": (0..100).map(|i| json!({"layer": i, "frame": i, "element": i})).collect::>(), "layer": 1}), + json!({"all": true, "filter": "a", "show": {"frames": false, "symbols": "x"}, "expanded": ["s0", 5], "offset": u64::MAX, "limit": u64::MAX}), + json!({"all": true, "scope": "scene", "definitions": false, "show": {"frames": false}, "limit": 0}), ]); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library] { + // A button open for editing, its hit area drawn over its other states (ADR 0057). + let mut button = Session::new(sample::interactive()); + if let Some(id) = button.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id) { + button.execute("symbol.edit", &json!({"symbol": id.0})).unwrap(); + } + // Groups (ADR 0073): raw shapes, an object and a symbol instance in a group inside a group, + // the outer one moved and translucent, the inner one open for editing in place. + let mut grouped = Session::new(sample::demo()); + grouped.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("draw.ellipse", json!({"x": 20, "y": 20, "w": 60, "h": 60, "fill": "#ff0000", "object": true})), + ("edit.select_all", json!({})), + ("modify.group", json!({})), + ("draw.rect", json!({"x": 100, "y": 0, "w": 60, "h": 60, "object": true})), + ("edit.select_all", json!({})), + ("modify.group", json!({})), + ("element.translate", json!({"dx": 30, "dy": 15})), + ("element.set_alpha", json!({"alpha": 0.5})), + ("symbol.edit", json!({})), + ("edit.select_all", json!({})), + ] { + grouped.execute(id, &p).unwrap(); + } + let inner = grouped.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Group { .. })).map(|e| e.id.0).unwrap(); + grouped.execute("symbol.edit", &json!({"id": inner})).unwrap(); + assert_eq!(grouped.editing.len(), 2, "the fuzz starts inside a group inside a group"); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -758,7 +865,14 @@ fn panic_hunt_every_command() { for f in [0, 1, 5, 47, 1000] { let _ = anicraft_render::render_frame(&s.doc, f, 0.1); } + s.hit_area = Some((anicraft_doc::Rgba::WHITE, 0.4)); let pic = s.stage_picture(); + // ...and every button's hit area draws, under a pointer that goes over and presses. + let mut ns = anicraft_doc::player::NoScripts; + let st = anicraft_doc::player::start(&s.doc, &mut ns).state; + let p = anicraft_geom::Vec2::new(640.0, 400.0); + let st = anicraft_doc::player::input(&s.doc, &st, &[anicraft_doc::player::Event::Move(p), anicraft_doc::player::Event::Down(p), anicraft_doc::player::Event::Up(p)], &mut ns).state; + let _ = anicraft_render::render(&anicraft_doc::player::hit_overlay(&s.doc, &st, anicraft_doc::Rgba::WHITE, 0.4), &anicraft_render::View { transform: anicraft_geom::Affine::scale(0.1, 0.1), width: 128, height: 72, background: None }); let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); // ...and its sounds lay out and mix. let voices = anicraft_doc::sound::voices(&s.doc, 8000); @@ -1296,7 +1410,7 @@ fn opening_an_xfl_folder_imports_it_untitled() { assert_eq!((s.doc.stage.width, s.doc.stage.fps), (320, 12.0)); assert_eq!(s.doc.timeline(s.scene).layers[0].name, "Art"); assert_eq!(s.doc.frame_count(), 6); - assert!(v["report"].as_str().unwrap().contains("1 dynamic and input text fields (imported as static text)"), "{v}"); + assert!(v["report"].as_str().unwrap().contains("Runs in Test Movie: 1 dynamic text fields"), "{v}"); assert!(s.path.is_none(), "imported documents are untitled: Save never writes over the original"); assert!(s.execute("file.save", &json!({})).is_err()); // It renders. @@ -1319,6 +1433,8 @@ fn opening_an_xfl_folder_imports_it_untitled() { run(&mut back, "file.open", json!({"path": file.display().to_string()})); let ElementKind::Text(t) = &back.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.id == text.id).unwrap().kind else { panic!("text") }; assert_eq!((t.text.as_str(), t.size, t.bold), ("Hello again", 20.0, true)); + assert_eq!(t.kind(), anicraft_doc::TextKind::Dynamic, "a dynamic field stays one (ADR 0066)"); + assert_eq!((t.box_width, t.field.as_ref().map(|f| f.lines)), (200.0, Some(anicraft_doc::LineType::Single))); } std::fs::remove_dir_all(&dir).ok(); } @@ -1453,6 +1569,99 @@ fn masked_frames_round_trip_through_svg_onto_mask_layers() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn soft_masks_round_trip_through_svg_onto_soft_mask_layers() { + // A grey ellipse as a luminance mask (ADR 0070) over an orange rect, on a dark background. + let mut src = Session::default(); + run(&mut src, "draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 360, "fill": "#20304a"})); + run(&mut src, "layer.new", json!({"name": "Art"})); + run(&mut src, "draw.rect", json!({"x": 100, "y": 60, "w": 400, "h": 240, "fill": "#ff6b4a"})); + run(&mut src, "layer.new", json!({"name": "Mask"})); + run(&mut src, "draw.ellipse", json!({"x": 180, "y": 80, "w": 260, "h": 200, "fill": "#808080", "stroke": null})); + run(&mut src, "layer.toggle_mask", json!({})); + run(&mut src, "layer.set_mask", json!({"mask": "luminance"})); + // The middle shows half the orange (grey #808080 is 0.502 bright) over the background. + let pm = anicraft_render::render_frame(&src.doc, 0, 1.0).unwrap(); + let px = pm.pixel(310, 180).unwrap(); + let k = 128.0 / 255.0; + let want = [k * 1.0 + (1.0 - k) * 0x20 as f32 / 255.0, k * 0x6b as f32 / 255.0 + (1.0 - k) * 0x30 as f32 / 255.0]; + assert!((px[0] - want[0]).abs() < 2e-3 && (px[1] - want[1]).abs() < 2e-3, "{px:?} vs {want:?}"); + let svg_text = crate::cmds_file::frame_svg(&src.doc, 0); + assert!(svg_text.contains("() / a.len() as f64; + assert!(mean < 0.01 && worst <= 2, "mean {mean:.3}, worst {worst} of 255"); + assert_eq!(crate::cmds_file::frame_svg(&s.doc, 0).matches(" = tl.layers.iter().filter(|l| l.kind == anicraft_doc::LayerKind::Mask).map(|l| l.mask_mode).collect(); + modes.sort_by_key(|m| m.key()); + assert_eq!(modes, [anicraft_doc::MaskMode::Alpha, anicraft_doc::MaskMode::Luminance]); + let pm = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let px = |x, y| pm.pixel(x, y).unwrap(); + // Alpha mask: red fades out left to right, x 25 → 1 − 25.5 / 100. + for (x, y) in [(25u32, 10u32), (75, 10)] { + let want = 1.0 - (x as f32 + 0.5) / 100.0; + assert!((px(x, y)[0] - want).abs() < 6e-3 && px(x, y)[1] < 1e-3, "({x}, {y}): {:?} vs {want}", px(x, y)); + } + // Luminance mask: #808080 shows 128 / 255 of the green. + assert!((px(150, 95)[1] - 128.0 / 255.0).abs() < 3e-3 && px(150, 95)[0] < 1e-3, "{:?}", px(150, 95)); + // The text follows the arc, centred on it, when this computer has fonts. + if !anicraft_text::Fonts::get().families().is_empty() { + let els: Vec> = s.timeline().layers.iter().filter_map(|l| anicraft_doc::evaluate_layer_elements(l, 0)).flat_map(|(_, e)| e.into_owned()).collect(); + let text = els.into_iter().find_map(|e| match &e.kind { + anicraft_doc::ElementKind::Text(t) => Some((e.transform, t.clone())), + _ => None, + }); + let (xf, t) = text.expect("the text"); + assert_eq!(t.text, "on the arc"); + let on = t.on_path.as_ref().expect("on its path"); + assert!(t.align == anicraft_doc::TextAlign::Center && on.offset > 50.0); + let b = t.outline.bounds().transformed(&xf); + assert!((b.center().x - 100.0).abs() < 4.0 && b.min.y > 20.0 && b.max.y < 70.0, "{b:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn imported_svg_text_is_editable_text() { if anicraft_text::Fonts::get().families().is_empty() { diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs index d21f2a01..54b7f6e5 100644 --- a/crates/engine/src/tests_bone.rs +++ b/crates/engine/src/tests_bone.rs @@ -31,7 +31,7 @@ pub(crate) fn three_bars() -> Session { 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)] } })); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: 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]); diff --git a/crates/engine/src/tests_bone_chain.rs b/crates/engine/src/tests_bone_chain.rs new file mode 100644 index 00000000..61a77d0d --- /dev/null +++ b/crates/engine/src/tests_bone_chain.rs @@ -0,0 +1,97 @@ +//! A bone chain stays one chain (user report #239): bones join end to start wherever the Bone +//! tool's drag began on an instance, lengths hold, the joints stay joined through many IK drags, +//! a small pointer move is a small turn, and grabbing a bone along its length doesn't snap its +//! end to the pointer. + +use super::*; +use crate::tests_bone::{ARM, HAND, ROOT, three_bars}; +use anicraft_doc::armature; +use anicraft_geom::Vec2; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn bones(s: &mut Session) -> Vec { + run(s, "bone.info", json!({}))["armatures"][0]["bones"].as_array().cloned().unwrap_or_default() +} + +fn pt(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap_or(f64::NAN) as f32, v[1].as_f64().unwrap_or(f64::NAN) as f32) +} + +/// The reporter's steps: a bone from the first bar to the second, then one from the second bar +/// to the third, started on the bar a little way from the first bone's end (as a quick drag does). +fn drawn_by_hand() -> (Session, u64, u64) { + let mut s = three_bars(); + let b1 = run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [150, 100], "tail": [250, 100]}))["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add", json!({"from": ARM, "to": HAND, "head": [262, 103], "tail": [350, 100]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +#[test] +fn a_bone_from_an_instance_on_a_chain_starts_at_its_joint() { + let (mut s, _, _) = drawn_by_hand(); + let bs = bones(&mut s); + assert!(pt(&bs[1]["head"]).distance(pt(&bs[0]["tail"])) < 1e-3, "the second bone starts where the first ends: {} vs {}", bs[1]["head"], bs[0]["tail"]); + // A root's bones still start where they were drawn (a torso's shoulders and hips). + let mut s = three_bars(); + run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [150, 100]})); + run(&mut s, "bone.add", json!({"from": ROOT, "to": HAND, "head": [180, 100]})); + let bs = bones(&mut s); + assert!(pt(&bs[0]["head"]).distance(Vec2::new(150.0, 100.0)) < 1e-3); + assert!(pt(&bs[1]["head"]).distance(Vec2::new(180.0, 100.0)) < 1e-3); +} + +#[test] +fn repeated_ik_drags_keep_the_chain_joined_and_its_lengths() { + let (mut s, _, b2) = drawn_by_hand(); + let lengths = |bs: &[Value]| bs.iter().map(|b| pt(&b["head"]).distance(pt(&b["tail"]))).collect::>(); + let first = lengths(&bones(&mut s)); + let mut prev: Option> = None; + // Round and round, in and out of reach, several times over (400 small pointer moves). + for i in 0..400 { + let t = i as f32 / 400.0 * std::f32::consts::TAU * 3.0; + let r = 40.0 + 170.0 * (t * 0.5).sin().abs(); + let (x, y) = (150.0 + r * t.cos(), 100.0 + r * t.sin()); + run(&mut s, "bone.solve", json!({"bone": b2, "x": x, "y": y})); + let bs = bones(&mut s); + assert!(pt(&bs[0]["tail"]).distance(pt(&bs[1]["head"])) < 1e-3, "the elbow came apart at step {i}"); + for (a, b) in lengths(&bs).iter().zip(&first) { + assert!((a - b).abs() < 1e-2, "a bone changed length at step {i}: {a} vs {b}"); + } + let angles: Vec = bs.iter().map(|b| b["angle"].as_f64().unwrap_or(0.0)).collect(); + if let Some(p) = &prev { + let turn = angles.iter().zip(p).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + // About 4 px of pointer travel per step at 40–210 px from the shoulder. + assert!(turn < 30.0, "a small move turned a joint {turn:.1}° at step {i}"); + } + prev = Some(angles); + } +} + +#[test] +fn grabbing_a_bone_along_its_length_moves_from_where_it_was_grabbed() { + let (mut s, b1, _) = drawn_by_hand(); + let (l, arm) = { + let l = s.timeline().layers.iter().find(|l| l.armature.is_some()).cloned().unwrap(); + let arm = l.armature.clone().unwrap(); + (l, arm) + }; + let (_, els) = anicraft_doc::evaluate_layer_elements(&l, 0).unwrap(); + let pose = armature::pose_at(&l, 0).unwrap_or_default(); + // Pressed a quarter of the way along the first bone, near the shoulder. + let press = Vec2::new(175.0, 100.0); + let local = armature::grab_point(&arm, &els, &pose, anicraft_doc::BoneId(b1), press).unwrap(); + let v = run(&mut s, "bone.solve", json!({"bone": b1, "x": press.x, "y": press.y, "local": [local.x, local.y]})); + assert!(v["error"].as_f64().unwrap() < 0.05, "{v}"); + let bs = bones(&mut s); + assert!(bs[0]["angle"].as_f64().unwrap().abs() < 1e-3, "pressing alone turns nothing"); + // A small drag down turns the bone a little about the shoulder: the grabbed point follows. + run(&mut s, "bone.solve", json!({"bone": b1, "x": 175.0, "y": 105.0, "local": [local.x, local.y]})); + let a = bones(&mut s)[0]["angle"].as_f64().unwrap(); + assert!((a - 5.0f64.atan2(25.0).to_degrees()).abs() < 0.5, "{a}°"); + // The bone's end, by contrast, would have been pulled 75 px onto the pointer. + assert!(armature::grab_point(&arm, &els, &pose, anicraft_doc::BoneId(999), press).is_none()); +} diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index e8827631..f6d52817 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -3,7 +3,7 @@ use crate::{Session, format}; use anicraft_doc::actions::{FrameScript, Language}; -use anicraft_doc::{LayerKind, SymbolId, SymbolKind, sample}; +use anicraft_doc::{ElementKind, LayerKind, SymbolId, SymbolKind, sample}; use serde_json::{Value, json}; const AS3: &str = "import flash.events.MouseEvent;\r\n\tstop(); // “wait”\n"; @@ -145,14 +145,14 @@ fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() { 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); + assert!(out.html.contains("xyzzy-") && !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(); +var n:int = 1; switch (n) { }"})).unwrap(); assert_eq!(v["runs"], false); - assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"})); + assert_eq!(v["problems"][0], json!({"line": 2, "column": 16, "message": "`switch` statements 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_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 16: `switch` statements aren't supported yet"); assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]); 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); @@ -174,11 +174,88 @@ 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["steps"], 3); + assert_eq!(v["program"]["body"][1]["s"], "listen"); + assert_eq!(v["program"]["body"][1]["at"]["path"], "btn"); + assert_eq!(v["program"]["functions"][0]["name"], "go"); assert_eq!(v["notes"][0]["line"], 4); + // Names from other frames are listed; the text alone can't say whether they are there. + let v = s.execute("script.check", &json!({"text": "score += bonus(2);"})).unwrap(); + assert_eq!((v["runs"].as_bool(), v["uses"].clone()), (Some(true), json!([{"name": "score", "line": 1, "column": 1, "call": false}, {"name": "bonus", "line": 1, "column": 10, "call": true}]))); 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()); } + +#[test] +fn scripts_link_through_their_timeline_and_test_movie_plays_keys() { + let mut s = Session::new(sample::interactive()); + let layer = s.doc.timeline(0).layers[0].id.0; + // Frame 2 uses a variable and a function that no frame declares yet: it doesn't run. + let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void { hits++; trace(\"key \" + e.keyCode + \" \" + hits + \" \" + Math.floor(Math.random() * 1000)); }"})).unwrap(); + assert_eq!(v["runs"], false, "{v}"); + assert_eq!(v["problems"][0]["message"], "`hits` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)"); + let out = s.execute("control.test_movie", &json!({"frames": 5})).unwrap(); + assert!(out["output"][0]["line"].as_str().unwrap().starts_with("Frame script not run: Scene 1 › Actions, frame 2: line 3"), "{}", out["output"]); + // Declaring it on frame 1 links frame 2. + s.execute("script.set", &json!({"layer": layer, "frame": 0, "text": "var hits:int = 0;"})).unwrap(); + let list = s.execute("script.list", &json!({"text": false})).unwrap(); + assert!(list["frames"].as_array().unwrap().iter().all(|f| f["runs"] == true), "{list}"); + let play = |s: &mut Session, seed: u64| { + let v = s.execute("control.test_movie", &json!({"frames": 6, "seed": seed, "events": [{"tick": 3, "type": "key_down", "key": "LEFT"}, {"tick": 4, "type": "key", "key": "a"}, {"tick": 5, "type": "key_down", "key": 32}]})).unwrap(); + v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str().map(str::to_string)).filter(|l| l.starts_with("key ")).collect::>() + }; + let a = play(&mut s, 1); + assert_eq!(a.len(), 3, "{a:?}"); + assert!(a[0].starts_with("key 37 1 ") && a[1].starts_with("key 65 2 ") && a[2].starts_with("key 32 3 "), "{a:?}"); + assert_eq!(play(&mut s, 1), a, "the same seed plays the same"); + assert_ne!(play(&mut s, 2), a, "another seed draws other numbers"); + for bad in [json!({"tick": 1, "type": "key_down"}), json!({"tick": 1, "type": "key_down", "key": 0}), json!({"tick": 1, "type": "key_up", "key": "WIGGLE"})] { + assert!(s.execute("control.test_movie", &json!({"events": [bad]})).is_err()); + } +} + +/// Dynamic and input text fields (ADR 0066), end to end through commands: Text type, instance +/// names, the file format, and a headless Test Movie that types into a field. +#[test] +fn text_fields_are_made_named_saved_and_typed_into() { + if anicraft_text::Fonts::get().families().is_empty() { + return; // A computer without fonts: the player tests cover fields with a test layout. + } + let mut s = Session::default(); + let ok = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + ok(&mut s, "text.create", json!({"text": "0", "x": 20, "y": 20, "size": 20})); + assert!(s.execute("instance.set_name", &json!({"name": "score_txt"})).unwrap_err().to_string().contains("static text has no instance name")); + assert!(s.execute("text.field", &json!({"type": "dynamic", "lines": "password"})).unwrap_err().to_string().contains("only input text")); + ok(&mut s, "text.field", json!({"type": "dynamic", "width": 200, "border": true})); + ok(&mut s, "instance.set_name", json!({"name": "score_txt"})); + let field = |s: &Session, name: &str| s.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.name == name).cloned().unwrap(); + let ElementKind::Text(t) = &field(&s, "score_txt").kind else { panic!("text") }; + assert_eq!((t.kind(), t.box_width), (anicraft_doc::TextKind::Dynamic, 200.0)); + assert!(t.outline.bounds().min.x >= anicraft_doc::FIELD_GUTTER - 0.5, "the text sits inside the gutter"); + // An empty input field, with a script reading it when Enter is pressed. + ok(&mut s, "text.create", json!({"text": "", "type": "input", "x": 20, "y": 80, "size": 20})); + ok(&mut s, "text.field", json!({"width": 200, "height": 30, "max_chars": 5})); + ok(&mut s, "instance.set_name", json!({"name": "name_txt"})); + ok(&mut s, "script.set", json!({"frame": 0, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, k);\nfunction k(e:KeyboardEvent):void { if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hi \" + name_txt.text; trace(name_txt.length); } }"})); + // Saved and opened again, the fields are the same. + let dir = std::env::temp_dir().join(format!("anicraft-fields-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("fields.anicraft"); + ok(&mut s, "file.save", json!({"path": file.display().to_string()})); + let mut back = Session::default(); + ok(&mut back, "file.open", json!({"path": file.display().to_string()})); + assert_eq!(field(&back, "name_txt").kind, field(&s, "name_txt").kind); + std::fs::remove_dir_all(&dir).ok(); + // Headless Test Movie: click the input field, type past its limit, press Enter. + let v = ok(&mut back, "control.test_movie", json!({"frames": 3, "events": [{"tick": 1, "type": "click", "x": 40, "y": 92}, {"tick": 1, "type": "text", "text": "Adalovelace"}, {"tick": 2, "type": "key", "key": "ENTER"}]})); + let fields = v["state"]["fields"].as_array().unwrap(); + let text_of = |n: &str| fields.iter().find(|f| f["name"] == n).map(|f| f["text"].clone()).unwrap(); + assert_eq!(text_of("name_txt"), "Adalo", "at most 5 characters"); + assert_eq!(text_of("score_txt"), "Hi Adalo"); + assert!(v["output"].as_array().unwrap().iter().any(|l| l["line"] == "5"), "{}", v["output"]); + assert!(back.execute("control.test_movie", &json!({"events": [{"type": "text"}]})).is_err()); + // Plug-ins may set text types (document content, like the rest of text.*). + assert!(crate::cmds_plugin::plugin_may_call("text.field").is_ok()); +} diff --git a/crates/engine/src/tests_shape_bone.rs b/crates/engine/src/tests_shape_bone.rs new file mode 100644 index 00000000..564ee773 --- /dev/null +++ b/crates/engine/src/tests_shape_bone.rs @@ -0,0 +1,292 @@ +//! Shape armatures end to end (ADR 0071): bones drawn inside a shape, automatic binding, the +//! Bind tool's command, posing by angle and by IK, pose tweens, removal, undo, refusals, the +//! file format, analytic renders and plug-in policy. + +use super::*; +use anicraft_doc::{ColorEffect, Document, ElementKind, Paint, Rgba, Shape, Stage}; +use anicraft_geom::{Affine, Path, PathCmd}; +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}"), + } +} + +const TAIL: u64 = 10; + +/// A 400 × 300 stage, 20 frames, with a black tail 200 × 20 px lying along y = 150 from +/// x = 100 (anchors every 25 px along both edges, part of the layer's merged drawing). +fn tail() -> Session { + let mut d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..=8 { + p.line_to(Vec2::new(25.0 * i as f32, -10.0)); + } + for i in (0..=8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + let shape = Shape { merge: true, ..Shape::filled(p, Paint::Solid(Rgba::BLACK)) }; + let el = Arc::new(Element { id: ElementId(TAIL), name: String::new(), transform: Affine::translate(100.0, 150.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + 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![el]; + k + })]; + d.next_id = 100; + Session::new(d) +} + +/// [`tail`] with two bones along its middle: (100, 150) → (200, 150) → (300, 150). +fn rigged() -> (Session, u64, u64) { + let mut s = tail(); + let v = run(&mut s, "bone.add_in_shape", json!({"shape": TAIL, "head": [100, 150], "tail": [200, 150]})); + assert_eq!(v["created"], true); + let b1 = v["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add_in_shape", json!({"parent": b1, "tail": [300, 150]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn shape_at(s: &Session, frame: u32) -> (Affine, Arc, bool) { + let tl = s.doc.timeline(s.scene); + tl.layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == TAIL).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.transform, sh.path.clone(), sh.merge)), + _ => None, + }) + }) + .unwrap() +} + +/// The tail's anchors on the stage at `frame`. +fn points(s: &Session, frame: u32) -> Vec { + let (m, p, _) = shape_at(s, frame); + anicraft_doc::skin::anchors(&p).into_iter().map(|a| m.apply(a)).collect() +} + +fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 { + let (sn, c) = a.sin_cos(); + let d = p - j; + Vec2::new(j.x + d.x * c - d.y * sn, j.y + d.x * sn + d.y * c) +} + +fn black(s: &Session, frame: u32, x: u32, y: u32) -> bool { + render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()[0] < 0.1 +} + +#[test] +fn bones_inside_a_shape_move_it_to_an_armature_layer_as_drawn() { + let before = render_frame(&tail().doc, 0, 1.0).unwrap().data; + let drawn = points(&tail(), 0); + 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!(s.layer, arm.id, "the armature layer is active"); + assert!(tl.layers[1].keyframes[0].elements.is_empty(), "the shape left its layer"); + let (m, _, merge) = shape_at(&s, 0); + assert_eq!(m, Affine::translate(100.0, 150.0)); + assert!(!merge, "an armature's shape is an object: merge drawing leaves it"); + // The rest pose is the drawing, exactly. + assert_eq!(points(&s, 0), drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let v = run(&mut s, "bone.info", json!({"points": true})); + let a = &v["armatures"][0]; + assert_eq!(a["shape"], TAIL); + assert_eq!(a["roots"], json!([TAIL])); + let bones = a["bones"].as_array().unwrap(); + assert_eq!((bones[0]["id"].as_u64(), bones[1]["id"].as_u64()), (Some(b1), Some(b2))); + assert_eq!(bones[1]["parent_bone"], b1); + assert_eq!(bones[1]["head"], json!([200.0, 150.0]), "the chain joins end to start"); + // Every point is bound, its weights summing to 1. + let pts = a["points"].as_array().unwrap(); + assert_eq!(pts.len(), drawn.len()); + for p in pts { + let sum: f64 = p["bones"].as_array().unwrap().iter().map(|i| i[1].as_f64().unwrap()).sum(); + assert!((sum - 1.0).abs() < 1e-5, "{p}"); + } + let (n1, n2) = (bones[0]["points"].as_u64().unwrap(), bones[1]["points"].as_u64().unwrap()); + assert!(n1 > 0 && n2 > 0 && n1 + n2 >= drawn.len() as u64, "{n1} + {n2}"); +} + +#[test] +fn a_quarter_bend_swings_the_tail_and_tweens_through_the_middle() { + let (mut s, _, b2) = rigged(); + let drawn = points(&s, 0); + // Key the bend at frame 10 (the rest pose at 0 tweens into it). + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let joint = Vec2::new(200.0, 150.0); + let bent = points(&s, 10); + // The tip's corners (the 8th and 9th points) follow the second bone alone. + for i in [8, 9] { + assert!(bent[i].distance(turned(drawn[i], joint, std::f32::consts::FRAC_PI_2)) < 1e-3, "{i}: {:?}", bent[i]); + } + // The root half didn't move. + assert_eq!(bent[1], drawn[1]); + assert_eq!(bent[0], drawn[0]); + // Half way the tip has turned 45°. + let mid = points(&s, 5); + assert!(mid[8].distance(turned(drawn[8], joint, std::f32::consts::FRAC_PI_4)) < 1e-3, "{:?}", mid[8]); + // The render shows it: the tail now hangs down from x = 200, its old tip area is empty. + assert!(black(&s, 0, 280, 150) && !black(&s, 0, 200, 230)); + assert!(!black(&s, 10, 280, 150) && black(&s, 10, 200, 230)); +} + +#[test] +fn dragging_a_shape_bone_bends_it_by_ik_in_one_undo_step() { + let (mut s, _, b2) = rigged(); + let steps = s.history_len(); + s.begin_gesture("Pose Armature"); + for t in [[290.0, 120.0], [270.0, 90.0], [250.0, 60.0]] { + run(&mut s, "bone.solve", json!({"bone": b2, "x": t[0], "y": t[1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let v = run(&mut s, "bone.info", json!({})); + let tail = &v["armatures"][0]["bones"][1]["tail"]; + let end = Vec2::new(tail[0].as_f64().unwrap() as f32, tail[1].as_f64().unwrap() as f32); + assert!(end.distance(Vec2::new(250.0, 60.0)) < 0.5, "{end:?}"); + // The outline follows the bones; the file holds what shows. + let shown = points(&s, 0); + assert!(shown[8].distance(Vec2::new(250.0, 60.0)) < 11.0, "{:?}", shown[8]); + let k = &s.doc.timeline(0).layers[0].keyframes[0]; + let ElementKind::Shape(sh) = &k.elements[0].kind else { panic!("not a shape") }; + assert_eq!(anicraft_doc::skin::anchors(&sh.path).iter().map(|p| Affine::translate(100.0, 150.0).apply(*p)).collect::>(), shown); + s.undo().unwrap(); + assert_eq!(points(&s, 0), points(&rigged().0, 0), "undo puts the rest pose back"); +} + +#[test] +fn binding_points_by_hand() { + let (mut s, b1, b2) = rigged(); + let tip = 8usize; + // The tip follows only the first bone: bending the second leaves it. + let v = run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip, 9]})); + assert_eq!(v["changed"], 2); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90})); + let drawn = points(&tail(), 0); + let now = points(&s, 0); + assert_eq!(now[tip], drawn[tip], "bound to the bone that didn't turn"); + assert_ne!(now[7], drawn[7], "its neighbours bend"); + // Shared: half way between staying and turning. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "add"})); + let want = (drawn[tip] + turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) * 0.5; + assert!(points(&s, 0)[tip].distance(want) < 1e-3); + let info = run(&mut s, "bone.info", json!({"points": true})); + let p = &info["armatures"][0]["points"][tip]; + assert_eq!(p["manual"], true); + assert_eq!(p["bones"].as_array().unwrap().len(), 2); + // Removed from both: it stays where it was drawn. + run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip], "mode": "remove"})); + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "remove"})); + assert_eq!(points(&s, 0)[tip], drawn[tip]); + // Automatic again: it follows the second bone round. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "auto"})); + assert!(points(&s, 0)[tip].distance(turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) < 1e-3); + // Each bind is one undo step. + s.undo().unwrap(); + assert_eq!(points(&s, 0)[tip], drawn[tip]); +} + +#[test] +fn shape_bones_refuse_what_cant_be_done() { + let mut s = tail(); + let steps = s.history_len(); + for (p, want) in [ + (json!({"shape": TAIL, "head": [100, 50], "tail": [200, 50]}), "inside"), + (json!({"shape": TAIL, "head": [150, 150], "tail": [150.5, 150]}), "length"), + (json!({"shape": TAIL, "tail": [200, 150]}), "head"), + (json!({"shape": TAIL, "head": [150, 150]}), "tail"), + (json!({"shape": 999, "head": [150, 150], "tail": [200, 150]}), "no shape"), + (json!({"head": [150, 150], "tail": [200, 150]}), "shape"), + (json!({"parent": 999, "tail": [200, 150]}), "no bone"), + ] { + let e = s.execute("bone.add_in_shape", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(s.history_len(), steps, "refusals leave no undo steps"); + let (mut s, b1, _) = rigged(); + for (p, want) in [(json!({"bone": b1, "points": [9999]}), "below"), (json!({"bone": b1, "mode": "glue"}), "mode"), (json!({"bone": b1, "points": "all"}), "points"), (json!({"bone": 4242}), "no bone")] { + let e = s.execute("bone.bind", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + // The shape's outline is the armature's: artwork edits are refused on its layer. + s.select_only([ElementId(TAIL)]); + for (id, p) in [("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("armature"), "{id}: {e}"); + } + // Bones of symbol instances bind nothing; instances don't join a shape's armature. + let (mut inst, ib1, _) = crate::tests_bone::rigged(); + assert!(inst.execute("bone.bind", &json!({"bone": ib1})).unwrap_err().to_string().contains("instances")); + assert!(inst.execute("bone.add_in_shape", &json!({"parent": ib1, "tail": [0, 0]})).unwrap_err().to_string().contains("instances")); + let e = inst.execute("bone.add_in_shape", &json!({"shape": crate::tests_bone::ROOT, "head": [150, 100], "tail": [190, 100]})).unwrap_err().to_string(); + assert!(e.contains("shape"), "{e}"); +} + +#[test] +fn merged_drawing_leaves_the_armature_shape_alone() { + let (mut s, _, _) = rigged(); + let drawn = shape_at(&s, 0).1; + let other = s.doc.timeline(0).layers[1].id; + run(&mut s, "layer.select", json!({"layer": other.0})); + run(&mut s, "draw.rect", json!({"x": 150, "y": 100, "w": 60, "h": 100})); + assert_eq!(*shape_at(&s, 0).1, *drawn, "a shape drawn over it on another layer doesn't cut it"); +} + +#[test] +fn removing_shape_bones_rebinds_and_the_last_frees_the_shape_as_it_looks() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 30})); + 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(), 2, "no layer for freed instances: a shape's bones move none"); + let arm = tl.layers[0].armature.as_ref().unwrap(); + assert!(arm.skin.as_ref().unwrap().points.iter().all(|p| p.bones == vec![anicraft_doc::skin::Influence(anicraft_doc::BoneId(b1), 1.0)]), "every point follows the bone that's left"); + let shown = points(&s, 0); + run(&mut s, "bone.remove", json!({"bone": b1})); + let tl = s.doc.timeline(0); + assert!(tl.layers.iter().all(|l| l.kind != LayerKind::Armature)); + assert_eq!(points(&s, 0), shown, "the shape stays as it looked, now a drawing object"); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2); +} + +#[test] +fn shape_armatures_survive_a_file_round_trip_and_render_the_same() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.bind", json!({"bone": b1, "points": [3], "mode": "add"})); + run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -100, "max": 100})); + run(&mut s, "bone.pose", json!({"bone": b2, "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, "frame {f}"); + } + // The file stores the outline as drawn, so a keyframe's bent outline never drifts. + let skin = back.timeline(0).layers[0].armature.as_ref().unwrap().skin.clone().unwrap(); + assert_eq!(skin.rest.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(0.0, -10.0)))); + // New ids never collide with the bones' joint nodes. + let mut back = Session::new(back); + let v = run(&mut back, "bone.add_in_shape", json!({"parent": b2, "tail": [200, 280]})); + assert!(v["bone"].as_u64().unwrap() > b2); +} + +#[test] +fn plug_ins_may_rig_shapes() { + for id in ["bone.add_in_shape", "bone.bind"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index d3922655..686c8aef 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -308,7 +308,7 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop let mut k = Keyframe::new(1, 3); k.sound = Some(FrameSound::new(SoundId(id))); inner.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; - s.doc.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let mut k = Keyframe::new(1, 8); k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } })); let mut outer = Layer::new(LayerId(503), "puppet"); @@ -328,3 +328,28 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn sounds_on_a_button_s_frames_play_in_test_movie_and_stay_out_of_the_soundtrack() { + let dir = temp_dir("button"); + let wav = dir.join("click.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &source())).unwrap(); + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = run(&mut s, "file.import_to_library", json!({"path": wav.display().to_string()}))["sound"].as_u64().unwrap(); + // Inside the Play button, a click on its Over frame and another on its Down frame. + let button = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": button.0})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 1})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 2, "sync": "stream"})); + run(&mut s, "symbol.exit", json!({})); + // The button stands at (640, 400) on the menu. + let v = run(&mut s, "control.test_movie", json!({"frames": 6, "events": [{"tick": 2, "type": "move", "x": 640, "y": 400}, {"tick": 4, "type": "down", "x": 640, "y": 400}]})); + let heard: Vec<(u64, &str)> = v["sounds"].as_array().unwrap().iter().map(|x| (x["tick"].as_u64().unwrap(), x["sync"].as_str().unwrap())).collect(); + assert_eq!(heard, [(2, "event"), (4, "event")], "Over, then Down (a stream plays as an event): {v}"); + assert_eq!(v["sounds"][0]["name"], "click.wav"); + // Nothing on the timelines plays them: the exported soundtrack is silent. + let out = dir.join("silent.wav"); + run(&mut s, "file.export_audio", json!({"path": out.display().to_string(), "rate": 8000, "bits": 32, "confirm": true})); + let pcm = audio::decode(&std::fs::read(&out).unwrap()).unwrap(); + assert!(pcm.samples.iter().all(|x| *x == 0.0)); +} diff --git a/crates/engine/src/tests_warp.rs b/crates/engine/src/tests_warp.rs new file mode 100644 index 00000000..1a3aab39 --- /dev/null +++ b/crates/engine/src/tests_warp.rs @@ -0,0 +1,264 @@ +//! Asset Warp end to end (ADR 0079): meshes on a shape and a bitmap, pins added, moved and +//! removed, keyframed and tweened, undo, refusals, stale artwork, the file format, renders and +//! exports, and plug-in policy. + +use super::*; +use anicraft_doc::warp::PinId; +use anicraft_doc::{Document, ElementKind, Shape, Stage}; +use anicraft_geom::{Path, Vec2}; +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}"), + } +} + +fn err(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(), + } +} + +/// The shape of element `id` as it shows at `frame`. +fn shape_at(s: &Session, id: u64, frame: u32) -> Shape { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + }) + .unwrap_or_else(|| panic!("no shape {id} at frame {frame}")) +} + +/// A 400 × 300 stage, 20 frames, with a blue 200 × 80 drawing object at (100, 100) and a +/// 40 × 20 bitmap placed at (300, 230). Returns the session, the rectangle and the bitmap. +pub(crate) fn warped() -> (Session, u64, u64) { + let d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let mut s = Session::new(d); + let rect = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 80, "fill": "#3080ff", "object": true}))["element"].as_u64().unwrap(); + let bm = anicraft_doc::BitmapId(s.doc.alloc_id()); + let mut rgba = Vec::new(); + for y in 0..20u32 { + for x in 0..40u32 { + rgba.extend_from_slice(&[(x * 6) as u8, (y * 12) as u8, 128, 255]); + } + } + let png = anicraft_render::encode_png(40, 20, &rgba).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "ramp.png", png).unwrap())); + let bitmap = run(&mut s, "library.place", json!({"bitmap": bm.0, "x": 300, "y": 230}))["element"].as_u64().unwrap(); + run(&mut s, "timeline.insert_frame", json!({"frame": 19})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + (s, rect, bitmap) +} + +fn pin_add(s: &mut Session, el: u64, x: f32, y: f32) -> u64 { + run(s, "warp.pin_add", json!({"element": el, "x": x, "y": y}))["pin"].as_u64().unwrap() +} + +#[test] +fn pins_bend_a_shape_and_the_rest_pose_is_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + let before = render_frame(&s.doc, 0, 1.0).unwrap().data; + let v = run(&mut s, "warp.add", json!({"element": rect})); + assert_eq!((v["created"].as_bool(), v["resolution"].as_u64(), v["columns"].as_u64(), v["rows"].as_u64()), (Some(true), Some(12), Some(12), Some(5))); + let a = pin_add(&mut s, rect, 110.0, 140.0); + let b = pin_add(&mut s, rect, 200.0, 140.0); + let c = pin_add(&mut s, rect, 290.0, 140.0); + // Pins alone move nothing: the outline is the drawing, bit for bit, and so is the render. + let sh = shape_at(&s, rect, 0); + assert_eq!(*sh.path, *drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let info = run(&mut s, "warp.info", json!({"element": rect})); + assert_eq!((info["pins"].as_array().map(Vec::len), info["bent"].as_bool()), (Some(3), Some(false))); + // Dragging the right pin down bends the right end most. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": c, "x": 290, "y": 200})); + let w = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + // The rectangle's own space is centred on it. + let local = |x: f32, y: f32| Vec2::new(x - 200.0, y - 140.0); + let moved = |x: f32| w.map(local(x, 140.0)).distance(local(x, 140.0)); + assert!(moved(280.0) > 40.0 && moved(250.0) > moved(150.0) && moved(120.0) < 3.0, "{} {} {}", moved(280.0), moved(250.0), moved(120.0)); + assert!(w.pin(PinId(a)).is_some() && w.pin(PinId(b)).is_some()); + assert_ne!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + // Off the artwork there is nothing to pin; a pin can't go twice in one place. + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 10, "y": 10})).contains("on the artwork")); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 110, "y": 140})).contains("already")); +} + +#[test] +fn a_drag_is_one_undo_step_and_remove_restores_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + let at = |s: &Session| shape_at(s, rect, 0).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at)).unwrap(); + s.begin_gesture("Move Pin"); + for i in 1..=10 { + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 3})); + assert_eq!(at(&s).y, 3.0 * i as f32); + } + s.end_gesture(); + s.undo().unwrap(); + assert_eq!(at(&s), Vec2::new(90.0, 0.0), "the whole drag undoes at once"); + s.redo().unwrap(); + assert_eq!(at(&s).y, 30.0); + // Removing a pin: the artwork follows the pins that are left (one pin: it just moves). + run(&mut s, "warp.pin_remove", json!({"element": rect, "pin": p})); + assert!(shape_at(&s, rect, 0).live_warp().unwrap().at_rest()); + run(&mut s, "warp.remove", json!({"element": rect})); + let sh = shape_at(&s, rect, 0); + assert!(sh.warp.is_none() && *sh.path == *drawn); + assert!(err(&mut s, "warp.remove", json!({"element": rect})).contains("no warp")); +} + +#[test] +fn pin_poses_tween_between_keyframes_with_easing() { + let (mut s, rect, _) = warped(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + // A keyframe at frame 11 holding the same mesh, a classic tween, then the pose there. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.select", json!({"layer": lid})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({})); + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "x": 290, "y": 240, "frame": 10})); + let pin_y = |s: &Session, f: u32| shape_at(s, rect, f).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at.y)).unwrap(); + assert_eq!((pin_y(&s, 0), pin_y(&s, 10)), (0.0, 100.0)); + assert!((pin_y(&s, 5) - 50.0).abs() < 1e-3, "halfway: {}", pin_y(&s, 5)); + // The tweened outline is the mesh bent by the halfway pins (not a blend of two outlines). + let mid = shape_at(&s, rect, 5); + let mut want = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + if let Some(q) = want.pins.iter_mut().find(|q| q.id == PinId(p)) { + q.at.y = 50.0; + } + assert_eq!(*mid.path, *want.outline()); + // Easing applies to the pins. + run(&mut s, "timeline.set_easing", json!({"easing": "quad_in"})); + assert!(pin_y(&s, 5) < 40.0, "eased in: {}", pin_y(&s, 5)); + // A pin added later lands on both keyframes, where the artwork shows on each. + let late = pin_add(&mut s, rect, 200.0, 110.0); + for f in [0, 10] { + assert!(shape_at(&s, rect, f).live_warp().unwrap().pin(PinId(late)).is_some(), "frame {f}"); + } + // Moving a pin mid-tween keys the frame with what it shows. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": late, "dx": 0, "dy": -5, "frame": 4})); + assert!(s.timeline().layers[0].keyframe_starting_at(4).is_some()); +} + +#[test] +fn a_bitmap_bends_in_every_renderer_and_export() { + let (mut s, _, bmp) = warped(); + let before = render_frame(&s.doc, 0, 1.0).unwrap(); + pin_add(&mut s, bmp, 285.0, 230.0); + let p = pin_add(&mut s, bmp, 315.0, 230.0); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "pinned, not yet moved: exactly as drawn"); + run(&mut s, "warp.pin_move", json!({"element": bmp, "pin": p, "x": 315, "y": 270})); + let after = render_frame(&s.doc, 0, 1.0).unwrap(); + // The bent image covers pixels below where the image was. + let covered = |pm: &anicraft_render::Pixmap, x: u32, y: u32| pm.pixel(x, y).is_some_and(|c| c[2] > 0.45 && c[0] < 0.95); + assert!(!covered(&before, 318, 262) && covered(&after, 318, 262)); + let info = run(&mut s, "warp.info", json!({"element": bmp})); + assert_eq!((info["bitmap"].as_bool(), info["bent"].as_bool()), (Some(true), Some(true))); + // SVG bakes the bent image; the HTML page reports it. + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(svg.contains(" p); + // Older files (no warp) still read; a warped file read by this build keeps its shape. + let plain = crate::format::to_json(&warped().0.doc).unwrap(); + assert!(!plain.contains("\"warp\"")); + // Another tool changes the outline: the warp no longer shows, and the next pin move + // starts from the shape as it is, with its pins where they show (nothing jumps). + let edited = { + let l = Arc::make_mut(&mut t.doc.timeline_mut(0).layers[0]); + let k = Arc::make_mut(&mut l.keyframes[0]); + let e = k.elements.iter_mut().find(|e| e.id.0 == rect).unwrap(); + let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind else { panic!() }; + sh.path = Arc::new(sh.path.transformed(&anicraft_geom::Affine::translate(5.0, 0.0))); + sh.path.clone() + }; + assert!(shape_at(&t, rect, 0).live_warp().is_none()); + assert_eq!(*shape_at(&t, rect, 0).path, *edited); + run(&mut t, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 0})); + let sh = shape_at(&t, rect, 0); + assert!(sh.live_warp().is_some_and(|w| w.at_rest()) && *sh.path == *edited); +} + +#[test] +fn warp_refusals() { + let (mut s, rect, _) = warped(); + // Nothing selected and no element. + s.selection.clear(); + assert!(err(&mut s, "warp.add", json!({})).contains("select")); + assert!(err(&mut s, "warp.add", json!({"element": rect, "resolution": 1})).contains("resolution")); + assert!(err(&mut s, "warp.add", json!({"element": 999_999})).contains("no element")); + assert!(err(&mut s, "warp.pin_move", json!({"element": rect, "pin": 5, "x": 1, "y": 1})).contains("no warp")); + // Symbols and text aren't warped. + let sym = run(&mut s, "draw.ellipse", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Dot"})); + let inst = s.selection.on(s.layer).first().map(|e| e.0).unwrap_or(sym); + assert!(err(&mut s, "warp.add", json!({"element": inst})).contains("shapes and bitmaps")); + // A locked layer. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": lid})); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 150, "y": 140})).contains("locked")); +} + +#[test] +fn plug_ins_may_warp() { + assert!(crate::cmds_plugin::plugin_may_call("warp.pin_move").is_ok()); + assert!(crate::cmds_plugin::plugin_may_call("warp.add").is_ok()); +} + +#[test] +fn warp_measured() { + // A 1,200-anchor outline on a 48 × 48 mesh with 32 pins, bent: release numbers go in the ADR. + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)); + for i in 1..600 { + p.line_to(Vec2::new(i as f32, (i as f32 * 0.05).sin() * 20.0)); + } + for i in (0..600).rev() { + p.line_to(Vec2::new(i as f32, 200.0 + (i as f32 * 0.05).cos() * 20.0)); + } + p.close(); + let mut w = anicraft_doc::warp::Warp::new(Arc::new(p), 48); + w.pins = (0..32).map(|i| anicraft_doc::warp::Pin { id: PinId(i), rest: Vec2::new(i as f32 * 18.0, 100.0), at: Vec2::new(i as f32 * 18.0, 100.0 + (i % 5) as f32 * 9.0) }).collect(); + let t = std::time::Instant::now(); + let n = 20; + let mut cmds = 0; + for _ in 0..n { + cmds += w.outline().cmds.len(); + } + eprintln!("warp: bend 1,200 anchors on 48×48 with 32 pins: {:.3} ms per frame ({} commands)", t.elapsed().as_secs_f64() * 1000.0 / f64::from(n), cmds / n as usize); +} diff --git a/crates/engine/src/timeline_drop_tests.rs b/crates/engine/src/timeline_drop_tests.rs new file mode 100644 index 00000000..8e26b9de --- /dev/null +++ b/crates/engine/src/timeline_drop_tests.rs @@ -0,0 +1,163 @@ +//! SVG into the Library and drops on the timeline (ADR 0065): a drawing becomes one graphic +//! symbol; media dropped on a layer's frame land there, in one undo step, and layers that can't +//! take them refuse without changing anything. + +use super::*; +use serde_json::json; +use std::path::Path; + +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 temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-tldrop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a 40 × 20 one-rectangle SVG, a short WAV and a masked SVG in `dir`. +fn media(dir: &Path) -> (String, String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let s = |p: std::path::PathBuf| p.display().to_string(); + (s(png), s(svg), s(wav), s(masked)) +} + +#[test] +fn an_svg_imported_to_the_library_is_one_graphic_symbol_centred_on_its_registration_point() { + let dir = temp_dir("svgsym"); + let (_, svg, _, masked) = media(&dir); + let mut s = Session::default(); + let history = s.history_len(); + let v = run(&mut s, "file.import_to_library", json!({"path": svg})); + assert_eq!(s.history_len(), history + 1, "one undo step"); + assert_eq!((s.doc.library.len(), v["name"].as_str()), (1, Some("badge"))); + let sym = s.doc.library[0].clone(); + assert_eq!(sym.kind, anicraft_doc::SymbolKind::Graphic); + assert_eq!(sym.timeline.layers.len(), 1); + // The 40 × 20 drawing sits around the registration point. + let k = &sym.timeline.layers[0].keyframes[0]; + let b = k.elements.iter().fold(anicraft_geom::Rect::EMPTY, |r, e| match &e.kind { + anicraft_doc::ElementKind::Shape(sh) => r.union(&sh.path.bounds().transformed(&e.transform)), + _ => r, + }); + assert!(b.center().x.abs() < 0.01 && b.center().y.abs() < 0.01 && (b.width() - 40.0).abs() < 0.01, "{b:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty())), "nothing on the stage"); + // Again: a free name. A masked drawing keeps its mask layer inside the symbol. + assert_eq!(run(&mut s, "file.import_to_library", json!({"path": svg}))["name"], "badge 2"); + run(&mut s, "file.import_to_library", json!({"path": masked})); + let m = s.doc.library.last().unwrap(); + assert!(m.timeline.layers.iter().any(|l| l.kind == anicraft_doc::LayerKind::Mask) && m.timeline.layers.len() == 2, "{:?}", m.timeline.layers.iter().map(|l| (&l.name, l.kind)).collect::>()); + // Placed, it shows. + run(&mut s, "library.place", json!({"symbol": sym.id.0, "x": 100, "y": 100})); + assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty()); + let empty = dir.join("empty.svg"); + std::fs::write(&empty, r#""#).unwrap(); + let before = s.doc.clone(); + assert!(s.execute("file.import_to_library", &json!({"path": empty.display().to_string()})).is_err(), "a drawing with no shapes adds nothing"); + assert!(s.doc == before); +} + +/// A session whose one layer has a keyframe at 0, 12 frames long, holding a rectangle. +fn timeline_session() -> (Session, anicraft_doc::LayerId) { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_frame", json!({"count": 11})); + let layer = s.layer; + (s, layer) +} + +#[test] +fn an_image_dropped_on_a_layers_frame_goes_into_a_keyframe_there_in_one_step() { + let dir = temp_dir("tlimg"); + let (png, svg, _, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let above = run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg], "to": "timeline", "layer": layer.0, "frame": 5, "x": 200, "y": 100})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!((s.layer, s.frame, v["keyframe_made"].as_bool()), (layer, 5, Some(true)), "the playhead and layer go to the drop"); + let l = s.timeline().layer(layer).unwrap(); + let k = l.keyframe_at(5).unwrap(); + assert_eq!(k.start, 5, "a keyframe starting at the frame"); + assert_eq!(k.elements.len(), 3, "what the frame showed, the image and the drawing"); + assert_eq!(l.keyframe_at(0).unwrap().elements.len(), 1, "the frames before are untouched"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 200.0).abs() < 0.01 && (b.center().y - 100.0).abs() < 0.01, "{b:?}"); + } + assert!(s.timeline().layer(anicraft_doc::LayerId(above)).unwrap().keyframes.iter().all(|k| k.elements.is_empty()), "the layer active before the drop is untouched"); + run(&mut s, "edit.undo", json!({})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_starting_at(5).is_none() && s.doc.bitmaps.is_empty()); + // On a keyframe's first frame, no new keyframe: the image joins it. + let v = run(&mut s, "file.drop", json!({"paths": [media(&dir).0], "to": "timeline", "layer": layer.0, "frame": 0})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + assert_eq!(s.timeline().layer(layer).unwrap().keyframes.len(), 1); +} + +#[test] +fn a_sound_dropped_on_a_frame_goes_onto_the_keyframe_holding_it() { + let dir = temp_dir("tlsnd"); + let (_, _, wav, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let v = run(&mut s, "file.drop", json!({"path": wav, "to": "timeline", "layer": layer.0, "frame": 7})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + let l = s.timeline().layer(layer).unwrap(); + assert_eq!(l.keyframes.len(), 1, "no keyframe made for a sound"); + assert!(l.keyframes[0].sound.is_some(), "onto the keyframe the frame is in"); + // Past the layer's end, a keyframe is made there for it. + run(&mut s, "file.drop", json!({"path": media(&dir).2, "to": "timeline", "layer": layer.0, "frame": 30})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_at(30).is_some_and(|k| k.start == 30 && k.sound.is_some())); +} + +#[test] +fn drops_on_the_timeline_refuse_layers_that_cant_take_them_and_change_nothing() { + let dir = temp_dir("tlbad"); + let (png, _, wav, masked) = media(&dir); + let (mut s, layer) = timeline_session(); + let folder = run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap(); + let layers = s.timeline().layers.len(); + // A drawing with masks can't go on one layer: a graphic symbol holding it goes there. + run(&mut s, "file.drop", json!({"path": masked, "to": "timeline", "layer": layer.0, "frame": 2})); + assert_eq!(s.timeline().layers.len(), layers, "no layers added"); + let k = s.timeline().layer(layer).unwrap().keyframe_at(2).unwrap(); + assert!(k.elements.iter().any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { .. }))); + assert_eq!(s.doc.library.len(), 1); + let before = s.doc.clone(); + let wav2 = dir.join("beep2.wav"); + std::fs::copy(&wav, &wav2).unwrap(); + for p in [ + json!({"path": png.clone(), "to": "timeline", "layer": folder, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": u64::MAX, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0}), + json!({"path": png.clone(), "to": "timeline", "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": u64::MAX}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": -1}), + json!({"paths": [wav.clone(), wav2.display().to_string()], "to": "timeline", "layer": layer.0, "frame": 0}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "timeline", "layer": layer.0, "frame": 4}), + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + s.layer = layer; + run(&mut s, "layer.toggle_lock", json!({})); + let before = s.doc.clone(); + for f in [png, wav] { + let e = s.execute("file.drop", &json!({"path": f, "to": "timeline", "layer": layer.0, "frame": 1})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); + assert!(s.doc == before); + } +} diff --git a/crates/engine/src/timeline_key_tests.rs b/crates/engine/src/timeline_key_tests.rs new file mode 100644 index 00000000..32946f09 --- /dev/null +++ b/crates/engine/src/timeline_key_tests.rs @@ -0,0 +1,137 @@ +//! F5, F6 and F7 as the keys work in the editor (user reports #242 and #254). + +use super::*; +use anicraft_doc::{Keyframe, LayerId}; +use serde_json::json; +use std::sync::Arc; + +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 spans(s: &Session, layer: LayerId) -> Vec<(u32, u32)> { + s.timeline().layer(layer).unwrap().keyframes.iter().map(|k| (k.start, k.duration)).collect() +} + +/// A layer whose keyframes are exactly `keys` (start, duration). +fn layer_with(s: &mut Session, keys: &[(u32, u32)]) -> LayerId { + let id = LayerId(run(s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let l = s.layer_mut(Some(id)).unwrap(); + l.keyframes = keys.iter().map(|&(a, d)| Arc::new(Keyframe::new(a, d))).collect(); + id +} + +#[test] +fn f5_with_no_frame_selection_extends_every_layer_that_reaches_the_playhead() { + // The report's example: playhead at frame 5 (index 4). + let mut s = Session::default(); + let l1 = layer_with(&mut s, &[(0, 8)]); + let l2 = layer_with(&mut s, &[(0, 4)]); + let l3 = layer_with(&mut s, &[(0, 6)]); + let l4 = layer_with(&mut s, &[(0, 2), (2, 7)]); + // Content only after the playhead, and a gap under it: both move along. + let later = layer_with(&mut s, &[(6, 3)]); + let gap = layer_with(&mut s, &[(0, 2), (7, 2)]); + let first = s.timeline().layers.iter().find(|l| ![l1, l2, l3, l4, later, gap].contains(&l.id)).map(|l| l.id).unwrap(); + s.layer_mut(Some(first)).unwrap().keyframes = vec![Arc::new(Keyframe::new(0, 1))]; + s.layer = l2; + s.set_frame(4); + let v = run(&mut s, "timeline.insert_frame", json!({"all_layers": true})); + assert_eq!(spans(&s, l1), vec![(0, 9)], "frames 1–8: extended"); + assert_eq!(spans(&s, l2), vec![(0, 4)], "frames 1–4 end before the playhead: unchanged, even when active"); + assert_eq!(spans(&s, l3), vec![(0, 7)], "frames 1–6: extended"); + assert_eq!(spans(&s, l4), vec![(0, 2), (2, 8)], "frames 1–9: extended"); + assert_eq!(spans(&s, later), vec![(7, 3)], "a key after the playhead moves one frame later"); + assert_eq!(spans(&s, gap), vec![(0, 2), (8, 2)], "a gap under the playhead grows by one"); + assert_eq!(spans(&s, first), vec![(0, 1)]); + assert_eq!(v["layers"].as_array().unwrap().len(), 5); + assert_eq!(s.frame, 4, "without advance the playhead stays"); + // One undo step takes it back on every layer. + run(&mut s, "edit.undo", json!({})); + assert_eq!(spans(&s, l1), vec![(0, 8)]); + assert_eq!(spans(&s, l4), vec![(0, 2), (2, 7)]); + assert_eq!(spans(&s, gap), vec![(0, 2), (7, 2)]); +} + +#[test] +fn f5_past_every_layer_lengthens_the_active_one() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 3)]); + let b = layer_with(&mut s, &[(0, 5)]); + s.layer = a; + s.set_frame(9); + run(&mut s, "timeline.insert_frame", json!({"all_layers": true, "advance": true})); + assert_eq!(spans(&s, a), vec![(0, 10)], "extended up to the playhead"); + assert_eq!(spans(&s, b), vec![(0, 5)]); + assert_eq!(s.frame, 9, "the frame made is the playhead's own"); +} + +#[test] +fn f5_advance_moves_the_playhead_onto_the_new_frame() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + for want in 1..4 { + let v = run(&mut s, "timeline.insert_frame", json!({"layer": a.0, "advance": true})); + assert_eq!(s.frame, want); + assert_eq!(v["playhead"], json!(want)); + } + assert_eq!(spans(&s, a), vec![(0, 4)], "holding F5 walks along, one frame each"); +} + +#[test] +fn f6_on_a_keyframe_keys_the_next_frame_and_follows() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + for want in 1..4 { + run(&mut s, "timeline.insert_keyframe", json!({"advance": true})); + assert_eq!(s.frame, want, "F6 on a keyframe makes the next one and goes there"); + } + assert_eq!(spans(&s, a), vec![(0, 1), (1, 1), (2, 1), (3, 1)]); + assert_eq!(s.timeline().layer(a).unwrap().keyframes[3].elements.len(), 1, "a copy of the drawing"); + // Inside a span (not on its key) F6 keys the playhead's own frame. + run(&mut s, "timeline.insert_frame", json!({"layer": a.0, "frame": 3, "count": 3})); + s.set_frame(5); + run(&mut s, "timeline.insert_keyframe", json!({"advance": true})); + assert_eq!(s.frame, 5); + assert_eq!(spans(&s, a), vec![(0, 1), (1, 1), (2, 1), (3, 2), (5, 2)]); + // Without advance (scripts), the old behaviour: nothing new on a keyframe. + run(&mut s, "timeline.insert_keyframe", json!({})); + assert_eq!(s.frame, 5); + assert_eq!(spans(&s, a).len(), 5); +} + +#[test] +fn f7_on_a_keyframe_makes_a_blank_one_next_instead_of_clearing() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({"advance": true})); + assert_eq!(s.frame, 1); + let l = s.timeline().layer(a).unwrap(); + assert_eq!(l.keyframes[0].elements.len(), 1, "the drawing is kept"); + assert!(l.keyframes[1].elements.is_empty(), "a blank key on the next frame"); + // Across two layers it advances only when both are on a keyframe. + let b = layer_with(&mut s, &[(0, 4)]); + run(&mut s, "timeline.insert_blank_keyframe", json!({"layers": [a.0, b.0], "frame": 1, "advance": true})); + assert_eq!(s.frame, 1); + assert_eq!(spans(&s, b), vec![(0, 1), (1, 3)]); +} + +#[test] +fn advance_at_the_last_frame_stays_in_range() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(MAX_FRAME - 1, 2)]); + s.layer = a; + s.set_frame(MAX_FRAME); + assert!(s.execute("timeline.insert_frame", &json!({"advance": true})).is_err()); + s.layer_mut(Some(a)).unwrap().keyframes = vec![Arc::new(Keyframe::new(MAX_FRAME, 1))]; + let _ = s.execute("timeline.insert_keyframe", &json!({"advance": true})); + assert!(s.frame <= MAX_FRAME); +} diff --git a/crates/engine/src/view_tests.rs b/crates/engine/src/view_tests.rs new file mode 100644 index 00000000..7f12466f --- /dev/null +++ b/crates/engine/src/view_tests.rs @@ -0,0 +1,218 @@ +//! Rulers, grid and guides (ADR 0076) through the commands: guides per scene with undo, the +//! settings, persistence, and the snap engine's priorities at several zooms. + +use crate::Session; +use anicraft_doc::{Document, GuideAxis}; +use anicraft_geom::Vec2; +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}: {e}")) +} + +fn guides(s: &Session) -> Vec<(GuideAxis, f32)> { + s.guides().iter().map(|g| (g.axis, g.at)).collect() +} + +/// A blank document drawing raw shapes, with a 100 × 80 rectangle at the origin. +fn rect_session() -> Session { + let mut s = Session::new(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 snap_at(s: &mut Session, x: f32, y: f32, r: f32) -> Option<(Vec2, String)> { + let v = run(s, "draw.snap", json!({"x": x, "y": y, "snap": r})); + let sn = v.get("snapped").filter(|v| v.is_object())?; + let f = |k: &str| sn[k].as_f64().unwrap_or(f64::NAN) as f32; + Some((Vec2::new(f("x"), f("y")), sn["to"].as_str().unwrap_or("").to_string())) +} + +#[test] +fn guides_are_added_moved_deleted_and_cleared_with_undo() { + let mut s = Session::new(Document::default()); + let v = run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 120})); + assert_eq!(v["index"], 0); + run(&mut s, "view.guide_add", json!({"axis": "h", "at": 64.5})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 120.0), (GuideAxis::Horizontal, 64.5)]); + assert!(s.is_dirty(), "guides are part of the document"); + run(&mut s, "view.guide_move", json!({"index": 0, "at": 300})); + assert_eq!(guides(&s)[0], (GuideAxis::Vertical, 300.0)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(guides(&s)[0], (GuideAxis::Vertical, 120.0), "a move is one undo step"); + run(&mut s, "view.guide_delete", json!({"index": 0})); + assert_eq!(guides(&s), [(GuideAxis::Horizontal, 64.5)]); + // Locked guides can't be moved or deleted one by one; new ones can still come. + run(&mut s, "view.guides_lock", json!({})); + assert!(s.execute("view.guide_move", &json!({"index": 0, "at": 1})).is_err()); + assert!(s.execute("view.guide_delete", &json!({"index": 0})).is_err()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": -40})); + run(&mut s, "view.guides_lock", json!({"on": false})); + assert_eq!(run(&mut s, "view.guides_clear", json!({}))["cleared"], 2); + assert!(guides(&s).is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(guides(&s).len(), 2, "Clear Guides is undoable"); + // Bad input says why and changes nothing. + for (id, p) in [ + ("view.guide_add", json!({"axis": "diagonal", "at": 1})), + ("view.guide_add", json!({"axis": "vertical"})), + ("view.guide_add", json!({"axis": "vertical", "at": 1e9})), + ("view.guide_move", json!({"index": 9, "at": 1})), + ("view.guide_delete", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + assert_eq!(guides(&s).len(), 2); +} + +#[test] +fn guides_belong_to_their_scene() { + let mut s = Session::new(Document::default()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 10})); + run(&mut s, "scene.new", json!({})); + assert!(guides(&s).is_empty(), "a new scene has no guides"); + run(&mut s, "view.guide_add", json!({"axis": "horizontal", "at": 20})); + run(&mut s, "scene.select", json!({"scene": 0})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 10.0)]); + run(&mut s, "scene.duplicate", json!({})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 10.0)], "a duplicated scene keeps its guides"); +} + +#[test] +fn guides_and_grid_settings_are_saved_and_older_files_open() { + let mut s = Session::new(Document::default()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 33.25})); + run(&mut s, "view.grid_set", json!({"spacing_x": 16, "spacing_y": 24, "color": "#ff000080", "over_objects": true, "show": true})); + run(&mut s, "view.guides_set", json!({"color": "#00ff00"})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + assert_eq!(back.scenes[0].guides.len(), 1); + assert_eq!((back.aids.grid.spacing_x, back.aids.grid.spacing_y, back.aids.grid.over_objects), (16.0, 24.0, true)); + assert!((back.aids.grid.color.a - 128.0 / 255.0).abs() < 1e-3); + // Whether the grid shows is the editor's, not the file's. + assert!(!text.contains("show_grid")); + // A document without any of it writes none of it, and a file from before opens as before. + let plain = crate::format::to_json(&Document::default()).unwrap(); + assert!(!plain.contains("guides") && !plain.contains("aids"), "{plain}"); + let old = crate::format::from_json(&plain).unwrap(); + assert!(old.scenes[0].guides.is_empty() && old.aids.is_default()); +} + +#[test] +fn settings_are_checked_and_toggles_take_no_undo_step() { + let mut s = Session::new(Document::default()); + let before = s.state; + let v = run(&mut s, "view.rulers", json!({})); + assert_eq!(v["rulers"], true); + run(&mut s, "view.grid_show", json!({})); + run(&mut s, "view.grid_snap", json!({"on": true})); + run(&mut s, "view.snap_pixels", json!({})); + run(&mut s, "view.grid_set", json!({"accuracy": "always"})); + run(&mut s, "view.guides_set", json!({"accuracy": "close", "snap": false})); + assert_eq!(s.state, before, "showing and snapping change no document"); + assert!(s.undo_label().is_none()); + let a = run(&mut s, "view.aids", json!({})); + assert_eq!((a["grid"]["show"].clone(), a["grid"]["snap"].clone(), a["grid"]["accuracy"].clone()), (json!(true), json!(true), json!("always"))); + assert_eq!((a["guides"]["snap"].clone(), a["guides"]["accuracy"].clone(), a["snap_pixels"].clone()), (json!(false), json!("close"), json!(true))); + for p in [json!({"spacing": 0}), json!({"spacing_x": 5000}), json!({"accuracy": "sometimes"}), json!({"color": "teal"})] { + assert!(s.execute("view.grid_set", &p).is_err(), "{p}"); + } + assert!(s.execute("view.guides_set", &json!({"accuracy": "always"})).is_err(), "guides never always snap"); + assert_eq!(*s.doc.aids, anicraft_doc::Aids::default(), "nothing changed on a refusal"); + run(&mut s, "view.grid_set", json!({"spacing": 50})); + assert_eq!(s.undo_label(), Some("Edit Grid…")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.aids.grid.spacing_x, 20.0); +} + +#[test] +fn snapping_priorities_hold_at_every_zoom() { + for zoom in [0.5f32, 1.0, 2.0, 8.0] { + let r = 10.0 / zoom; + // Distances in screen pixels, so each case means the same at every zoom. + let d = |px: f32| px / zoom; + let mut s = rect_session(); + // A point beats a guide nearer still: the rectangle's corner (100, 0). + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 100.0 + d(4.0)})); + assert_eq!(snap_at(&mut s, 100.0 + d(3.0), d(2.0), r), Some((Vec2::new(100.0, 0.0), "point".into())), "zoom {zoom}"); + // Away from corners, the guide beats the rectangle's right edge (a line). + let (q, to) = snap_at(&mut s, 100.0 + d(2.0), 40.0, r).unwrap(); + assert_eq!(to, "guide", "zoom {zoom}"); + assert!((q.x - (100.0 + d(4.0))).abs() < 1e-3 && (q.y - 40.0).abs() < 1e-3, "zoom {zoom}: {q:?}"); + // Without guides snapping, the edge. + run(&mut s, "view.guides_snap", json!({"on": false})); + let (q, to) = snap_at(&mut s, 100.0 + d(2.0), 40.0, r).unwrap(); + assert_eq!((to.as_str(), q.x), ("line", 100.0), "zoom {zoom}"); + // The grid, where no artwork is near: 100-pixel lines. + run(&mut s, "view.grid_set", json!({"spacing": 100, "snap": true})); + assert_eq!(snap_at(&mut s, 300.0 + d(4.0), 300.0 - d(6.0), r), Some((Vec2::new(300.0, 300.0), "grid".into())), "zoom {zoom}"); + assert_eq!(snap_at(&mut s, 300.0 + d(12.0), 300.0 + d(12.0), r), None, "zoom {zoom}: beyond 10 screen pixels"); + // The artwork's points still beat the grid. + assert_eq!(snap_at(&mut s, 100.0 - d(3.0), 80.0 + d(3.0), r), Some((Vec2::new(100.0, 80.0), "point".into())), "zoom {zoom}"); + // Shift (no radius) snaps nothing. + assert_eq!(snap_at(&mut s, 300.0 + d(4.0), 300.0, 0.0), None); + } +} + +#[test] +fn guides_grid_and_pixels_snap_with_snap_to_objects_off() { + let mut s = rect_session(); + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + assert_eq!(snap_at(&mut s, 103.0, 1.0, 10.0), None, "nothing to snap to"); + run(&mut s, "view.snap_pixels", json!({"on": true})); + assert_eq!(snap_at(&mut s, 103.4, 1.6, 10.0), Some((Vec2::new(103.0, 2.0), "pixel".into())), "the corner isn't looked at, pixels are"); + // A raw line's end dragged near a grid crossing goes onto it. + run(&mut s, "draw.line", json!({"x0": 200, "y0": 200, "x1": 260, "y1": 200, "stroke": "#0000ff"})); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "view.grid_set", json!({"spacing": 50, "snap": true})); + let v = run(&mut s, "raw.move_point", json!({"x": 260, "y": 200, "to_x": 296, "to_y": 246, "snap": 10})); + assert_eq!((v["x"].as_f64(), v["y"].as_f64(), v["snapped"]["to"].as_str()), (Some(300.0), Some(250.0), Some("grid")), "{v}"); +} + +#[test] +fn a_moved_symbol_snaps_its_box_to_a_guide() { + let mut s = Session::new(Document::default()); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 40, "h": 40, "object": true})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 200})); + let b = s.selection_bounds(); + // Grabbed near its top-right corner and moved so that corner lands 6 pixels short of the + // guide. + let dx = 200.0 - 6.0 - b.max.x; + let v = run(&mut s, "element.translate", json!({"dx": dx, "dy": 0, "snap": 10, "from": [b.max.x + dx - 2.0, b.min.y + 3.0]})); + assert_eq!(v["snapped"]["to"], "guide", "{v}"); + assert!((s.selection_bounds().max.x - 200.0).abs() < 1e-3, "{:?}", s.selection_bounds()); +} + +#[test] +fn inside_a_symbol_guides_line_up_with_the_stage() { + let mut s = Session::new(Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 40, "h": 40, "object": true})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "element.set_transform", json!({"x": 150, "y": 90, "sx": 2, "sy": 2})); + run(&mut s, "symbol.edit", json!({})); + let v = s.edit_view().expect("open in place"); + assert!(v.in_place && (v.scale - 2.0).abs() < 1e-4, "{v:?}"); + run(&mut s, "view.guide_add", json!({"axis": "horizontal", "at": 130})); + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + // In the symbol's space, a point 2 stage pixels (1 symbol unit) off the guide. + let p = Vec2::new(5.0, (130.0 + 2.0 - v.origin.y) / v.scale); + let (q, to) = snap_at(&mut s, p.x, p.y, 10.0 / v.scale).expect("snaps"); + assert_eq!(to, "guide"); + assert!((v.origin.y + q.y * v.scale - 130.0).abs() < 1e-3, "lands on the guide as the stage shows it: {q:?}"); + assert_eq!(q.x, 5.0); +} + +#[test] +fn plug_ins_may_edit_guides_but_not_the_view() { + use crate::cmds_plugin::plugin_may_call; + for id in ["view.aids", "view.guide_add", "view.guide_move", "view.guide_delete", "view.guides_clear"] { + assert!(plugin_may_call(id).is_ok(), "{id}"); + } + for id in ["view.rulers", "view.grid_show", "view.grid_set", "view.guides_lock", "view.snap_pixels"] { + assert!(plugin_may_call(id).is_err(), "{id}"); + } +} diff --git a/crates/engine/src/web_tests.rs b/crates/engine/src/web_tests.rs index d496a0f5..2d04c05c 100644 --- a/crates/engine/src/web_tests.rs +++ b/crates/engine/src/web_tests.rs @@ -57,6 +57,8 @@ fn exports_come_back_as_files() { ("file.export_png", json!({"path": "frame.png"})), ("file.export_svg", json!({"path": "frame.svg"})), ("file.export_gif", json!({"path": "movie.gif", "to": 3})), + ("file.export_apng", json!({"path": "movie.png", "to": 3})), + ("file.export_webp", json!({"path": "movie.webp", "to": 3})), ("file.export_lottie", json!({"path": "movie.json"})), ("file.export_html", json!({"path": "movie.html"})), ("file.export_audio", json!({"path": "track.wav"})), @@ -67,12 +69,16 @@ fn exports_come_back_as_files() { s.execute("file.export_png_sequence", &json!({"dir": "frames", "to": 2})).unwrap(); let out = vfs::take_written(); let n = names(&out); - for want in ["frame.png", "frame.svg", "movie.gif", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { + for want in ["frame.png", "frame.svg", "movie.gif", "movie.png", "movie.webp", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { assert!(n.iter().any(|x| x == want), "{want} missing from {n:?}"); } assert!(out.iter().all(|(_, b)| !b.is_empty())); let png = &out.iter().find(|(p, _)| p == Path::new("frame.png")).unwrap().1; assert!(png.starts_with(b"\x89PNG")); + let apng = &out.iter().find(|(p, _)| p == Path::new("movie.png")).unwrap().1; + assert!(apng.starts_with(b"\x89PNG") && apng.windows(4).any(|w| w == b"acTL"), "an animated PNG"); + let webp = &out.iter().find(|(p, _)| p == Path::new("movie.webp")).unwrap().1; + assert!(webp.starts_with(b"RIFF") && webp.windows(4).any(|w| w == b"ANMF"), "an animated WebP"); let wav = &out.iter().find(|(p, _)| p == Path::new("track.wav")).unwrap().1; assert!(wav.starts_with(b"RIFF") && !n.iter().any(|x| x.ends_with(".tmp"))); let err = s.execute("file.export_video", &json!({"path": "movie.webm"})).unwrap_err().to_string(); diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index f24fc0e8..b94ff16f 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -29,17 +29,20 @@ fn corpus() -> PathBuf { /// The frames rendered for each package (frames count across scenes, from 0). const FRAMES: &[(&str, &[u32])] = &[ ("bitmaps", &[0]), + ("colour", &[0, 6, 12]), ("filters", &[0]), ("gradients", &[0]), ("guides", &[0, 6, 12]), ("interactive", &[0, 9]), ("masks", &[0]), + ("nineslice", &[0]), ("primitives", &[0]), ("scenes", &[0, 3, 7, 8, 10]), ("scripts", &[0, 4]), ("shapes", &[0]), ("symbols", &[0, 5]), ("text", &[0]), + ("textfields", &[0]), ("tweens", &[0, 6, 12]), ]; @@ -73,9 +76,27 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("symbols", 5, 130.0, 40.0, 0x457B9D), // The button's Up frame. ("symbols", 0, 82.0, 130.0, 0x2A9D8F), - // Brightness +60% and -50% of #6D597A. + // Brightness +60% and -50% of #6D597A; Advanced: red ×20 %, green +120, at 80 % over white. ("symbols", 0, 230.0, 130.0, 0xC5BDCA), ("symbols", 0, 260.0, 130.0, 0x372D3D), + ("symbols", 0, 290.0, 130.0, 0x44DA95), + // Colour effects on #2A9D8F (ADR 0056): None, Brightness +50 %, Tint 60 % #E9C46A, Advanced + // (red −100 % +255, green 50 %, blue −60), Alpha 25 % over white. + ("colour", 0, 30.0, 40.0, 0x2A9D8F), + ("colour", 0, 90.0, 40.0, 0x94CEC7), + ("colour", 0, 150.0, 40.0, 0x9DB479), + ("colour", 0, 210.0, 40.0, 0xD54F53), + ("colour", 0, 270.0, 40.0, 0xCAE6E3), + // Brightness −40 % around a 50 % red tint: both, exactly (not the stronger one alone). + ("colour", 0, 60.0, 110.0, 0x592F2B), + // Tint #264653 to Advanced: the ends, and halfway in the advanced space. + ("colour", 0, 160.0, 105.0, 0x264653), + ("colour", 6, 220.0, 105.0, 0x614771), + ("colour", 12, 280.0, 105.0, 0x944C8D), + // Brightness −100 % to +60 %: halfway is brightness −20 % (not the transforms' midpoint). + ("colour", 0, 160.0, 152.0, 0x000000), + ("colour", 6, 220.0, 152.0, 0x227E72), + ("colour", 12, 280.0, 152.0, 0xAAD8D2), ("tweens", 0, 20.0, 25.0, 0xF4A261), ("tweens", 12, 300.0, 25.0, 0xF4A261), // Masked stripes: inside the spot, and outside it. @@ -84,6 +105,14 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("masks", 0, 10.0, 22.0, 0xFFFFFF), ("masks", 0, 145.0, 10.0, 0xFFFFFF), ("masks", 0, 270.0, 70.0, 0xCB997E), + // 9-slice (ADR 0055): the stretched panel's top-left corner keeps its radius-10 curve (plain + // scaling would leave the background there), its middle is the panel, and the graphic inside + // it scales normally (a dot 2.8 times as wide). + ("nineslice", 0, 27.0, 113.0, 0x2A9D8F), + ("nineslice", 0, 137.0, 13.0, 0x2A9D8F), + ("nineslice", 0, 100.0, 125.0, 0x2A9D8F), + ("nineslice", 0, 151.0, 130.0, 0xE9C46A), + ("nineslice", 0, 21.0, 111.0, 0xF1FAEE), // Guide artwork never draws. ("guides", 0, 5.0, 5.0, 0xFFFFFF), ("guides", 0, 160.0, 60.0, 0xFFFFFF), @@ -98,6 +127,10 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("scripts", 4, 160.0, 90.0, 0xE76F51), ("scripts", 4, 240.0, 90.0, 0xF4F1EA), ("text", 0, 300.0, 80.0, 0xE9EDC9), + // Fields draw their box (white behind a border) with no fonts at all (ADR 0066). + ("text", 0, 290.0, 134.0, 0xFFFFFF), + ("textfields", 0, 100.0, 30.0, 0xFFFFFF), + ("textfields", 0, 300.0, 170.0, 0xF4F1EA), ]; fn import(case: &str) -> Document { @@ -190,7 +223,7 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format() 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")) { + for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text" | "textfields")) { 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(); @@ -252,3 +285,56 @@ fn every_package_opens_from_a_fla_with_the_same_golden_frames() { {}", failures.len(), failures.join(" ")); } + +/// #226: each package as a `.fla` opens as the same document through every way in: File › Open, +/// the command line and a document the system hands over (all `file.open`), Open Recent and the +/// start screen's list (`file.open_recent`), a drop anywhere on the window (routed to +/// `file.open`), an upper-case extension, and a file a web browser hands over (`vfs`). +#[test] +fn every_entry_point_opens_the_corpus_as_a_fla() { + use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-entry-points"); + std::fs::create_dir_all(&dir).unwrap(); + for (case, _) in FRAMES { + let mut s = Session::default(); + s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + let bytes = pack::pack(&pack::package(&corpus().join(case)), &pack::VARIANTS[0]); + let fla = dir.join(format!("{case}.fla")); + std::fs::write(&fla, &bytes).unwrap(); + let upper = dir.join(format!("{case} COPY.FLA")); + std::fs::write(&upper, &bytes).unwrap(); + let open = |path: &Path| { + let mut t = Session::default(); + t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + t + }; + for path in [&fla, &upper] { + let t = open(path); + assert!(t.doc == s.doc, "{}: opens differently from its folder", path.display()); + assert!(t.path.is_none(), "{case}: imported untitled, so Save never writes over the Animate file"); + } + // Open Recent reopens the Animate file it imported. + let mut t = open(&fla); + t.execute("file.new", &json!({})).unwrap(); + t.execute("file.open_recent", &json!({"index": 0, "confirm": true})).unwrap_or_else(|e| panic!("{case}: Open Recent: {e}")); + assert!(t.doc == s.doc, "{case}: Open Recent opens it the same"); + // A drop anywhere opens it. + for path in [&fla, &upper] { + assert_eq!(kind_of(path), DropKind::Document, "{}", path.display()); + for target in [DropTarget::Stage, DropTarget::Timeline, DropTarget::Library, DropTarget::Window] { + assert_eq!(route(kind_of(path), target), DropAction::Open, "{case} on {target:?}"); + } + } + // In a browser the file arrives in memory, on the thread that opens it (ADR 0036). + let (name, data, want) = (format!("{case}.fla"), bytes.clone(), s.doc.clone()); + std::thread::spawn(move || { + anicraft_engine::vfs::use_memory(); + anicraft_engine::vfs::put(Path::new(&name), data).unwrap(); + let mut w = Session::default(); + w.execute("file.open", &json!({"path": name})).unwrap_or_else(|e| panic!("{name} in a browser: {e}")); + assert!(w.doc == want, "{name}: opens differently in a browser"); + }) + .join() + .unwrap(); + } +} diff --git a/crates/geom/src/brush.rs b/crates/geom/src/brush.rs index a4fd2d3d..e0076942 100644 --- a/crates/geom/src/brush.rs +++ b/crates/geom/src/brush.rs @@ -77,10 +77,62 @@ pub fn size_factor(pressure: f32) -> f32 { MIN_PRESSURE_SIZE + (1.0 - MIN_PRESSURE_SIZE) * p } +/// How a stroke is shaped beyond its tip (ADR 0068): tapered ends, separate dabs and a ragged +/// edge. The default shapes nothing (ADR 0033's plain sweep). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Shaping { + /// The part of the stroke's length (`0..=0.5`) over which it swells from a point at its + /// start, and thins to a point at its end. + pub taper_start: f32, + pub taper_end: f32, + /// `0`: one continuous sweep. Otherwise the tip is stamped as separate dabs this far apart, + /// as a multiple of its size (`0.05..=10`). + pub spacing: f32, + /// How far the edge is worn away, as a part of the tip's size (`0..=0.5`): a chalk-like + /// ragged edge from a fixed noise pattern, so it is the same every time. + pub jitter: f32, +} + +/// Most dabs one stroke stamps (the spacing widens past it). +pub const MAX_DABS: usize = 20_000; +/// Thinnest a taper makes the tip, as a part of its size. +const TAPER_TIP: f32 = 0.05; + +impl Shaping { + /// The values clamped to their ranges (not a number reads as none). + pub fn sanitized(self) -> Shaping { + let c = |v: f32, hi: f32| if v.is_finite() { v.clamp(0.0, hi) } else { 0.0 }; + let spacing = c(self.spacing, 10.0); + Shaping { taper_start: c(self.taper_start, 0.5), taper_end: c(self.taper_end, 0.5), spacing: if spacing > 0.0 { spacing.max(0.05) } else { 0.0 }, jitter: c(self.jitter, 0.5) } + } + + /// The tapers' factor at fraction `u` of the stroke's length. + pub fn taper(&self, u: f32) -> f32 { + let ease = |x: f32| { + let x = x.clamp(0.0, 1.0); + x * (2.0 - x) + }; + let mut f: f32 = 1.0; + if self.taper_start > 1e-4 { + f = f.min(ease(u / self.taper_start)); + } + if self.taper_end > 1e-4 { + f = f.min(ease((1.0 - u) / self.taper_end)); + } + TAPER_TIP + (1.0 - TAPER_TIP) * f + } +} + /// The smoothed centre line: points with the tip's size factor at each. `smoothing` is the /// curve fit's tolerance (stage units); `flatness` how closely the points follow the fitted /// curves. One distinct sample gives one point (a dab). pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec2, f32)> { + centreline_shaped(samples, smoothing, flatness, &Shaping::default()) +} + +/// The centre line with the shaping's tapers applied to the size factors. +pub fn centreline_shaped(samples: &[Sample], smoothing: f32, flatness: f32, shaping: &Shaping) -> Vec<(Vec2, f32)> { + let shaping = shaping.sanitized(); let mut pts: Vec = Vec::with_capacity(samples.len().min(MAX_SAMPLES)); let mut press: Vec = Vec::with_capacity(pts.capacity()); for s in samples.iter().take(MAX_SAMPLES).filter(|s| s.at.is_finite()) { @@ -118,6 +170,8 @@ pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec acc.iter_mut().for_each(|a| *a /= total); acc }; + // A taper needs points along the line to follow it (a straight drag flattens to two). + let line = if shaping.taper_start > 0.0 || shaping.taper_end > 0.0 { subdivide(&line, 96) } else { line }; let (src, dst) = (along(&pts), along(&line)); let mut j = 0; line.iter() @@ -129,18 +183,108 @@ pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec let (s0, s1) = (src.get(j).copied().unwrap_or(0.0), src.get(j + 1).copied().unwrap_or(1.0)); let (f0, f1) = (press.get(j).copied().unwrap_or(1.0), press.get(j + 1).copied().or(press.get(j).copied()).unwrap_or(1.0)); let t = if s1 - s0 > 1e-9 { ((u - s0) / (s1 - s0)).clamp(0.0, 1.0) } else { 0.0 }; - (*p, f0 + (f1 - f0) * t) + (*p, (f0 + (f1 - f0) * t) * shaping.taper(u)) }) .collect() } +/// The polyline with no piece longer than a `n`th of its length (at most `n` points added). +fn subdivide(line: &[Vec2], n: usize) -> Vec { + let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.distance(*b) } else { 0.0 }).sum(); + let piece = total / n.max(1) as f32; + if !(piece.is_finite() && piece > 1e-6) { + return line.to_vec(); + } + let mut out = Vec::with_capacity(line.len() + n + 1); + out.extend(line.first().copied()); + for w in line.windows(2) { + let &[a, b] = w else { continue }; + let k = (a.distance(b) / piece).ceil().clamp(1.0, n as f32 + 1.0) as usize; + out.extend((1..=k).map(|i| a.lerp(b, i as f32 / k as f32))); + } + out +} + +/// The Paint Brush's line (ADR 0068): the smoothed centre line as an open path, and the tip's +/// size factor along it as `(fraction of length, factor)` at `max` (2..) evenly spaced places. +/// An empty path when the samples don't make a line (one point, or none finite). +pub fn centre_stroke(samples: &[Sample], shaping: &Shaping, smoothing: f32, flatness: f32, max: usize) -> (Path, Vec<(f32, f32)>) { + let line = centreline_shaped(samples, smoothing, flatness, shaping); + if line.len() < 2 { + return (Path::new(), Vec::new()); + } + let pts: Vec = line.iter().map(|(p, _)| *p).collect(); + let tol = if smoothing.is_finite() && smoothing > 0.01 { smoothing.min(flatness.max(0.05) * 4.0) } else { 0.05 }; + let path = fit_curve(&pts, tol, tol * 2.0, false); + let mut along = Vec::with_capacity(line.len()); + let mut d = 0.0; + for w in line.windows(2) { + if let [a, b] = w { + along.push(d); + d += a.0.distance(b.0); + } + } + along.push(d); + let total = d.max(1e-9); + let n = max.clamp(2, 1000); + let mut j = 0; + let profile = (0..n) + .map(|i| { + let u = i as f32 / (n - 1) as f32; + let at = u * total; + while j + 2 < along.len() && along.get(j + 1).is_some_and(|a| *a < at) { + j += 1; + } + let (a0, a1) = (along.get(j).copied().unwrap_or(0.0), along.get(j + 1).copied().unwrap_or(total)); + let (f0, f1) = (line.get(j).map_or(1.0, |l| l.1), line.get(j + 1).map_or(1.0, |l| l.1)); + let t = if a1 - a0 > 1e-9 { ((at - a0) / (a1 - a0)).clamp(0.0, 1.0) } else { 0.0 }; + (u, f0 + (f1 - f0) * t) + }) + .collect(); + (path, profile) +} + +/// Dabs every `step` stage units along a centre line (the first point always), with the size +/// factor where each falls. At most [`MAX_DABS`]: a longer line spaces them wider. +pub fn dabs(line: &[(Vec2, f32)], step: f32) -> Vec<(Vec2, f32)> { + let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.0.distance(b.0) } else { 0.0 }).sum(); + let mut out: Vec<(Vec2, f32)> = line.first().copied().into_iter().collect(); + if !(step.is_finite() && step > 1e-3) { + return out; + } + let step = step.max(total / MAX_DABS as f32); + let mut next = step; + let mut walked = 0.0; + for w in line.windows(2) { + let &[(a, fa), (b, fb)] = w else { continue }; + let l = a.distance(b); + while next <= walked + l && out.len() < MAX_DABS { + let t = if l > 1e-9 { (next - walked) / l } else { 0.0 }; + out.push((a.lerp(b, t), fa + (fb - fa) * t)); + next += step; + } + walked += l; + } + out +} + /// The filled outline of a brush stroke: closed loops (even-odd), or an empty path when there /// is nothing to paint (no finite samples, a zero-size tip, or a stroke too large to resolve). /// `smoothing` is the centre line's curve-fit tolerance and `tolerance` the outline's (both in /// stage units). pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> Path { + outline_shaped(samples, tip, &Shaping::default(), smoothing, tolerance) +} + +/// The outline with tapers, dabs or a ragged edge (ADR 0068). +pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothing: f32, tolerance: f32) -> Path { + let shaping = shaping.sanitized(); let tol = if tolerance.is_finite() && tolerance > 1e-3 { tolerance } else { 0.25 }; - let line = centreline(samples, smoothing, tol * 0.25); + let mut line = centreline_shaped(samples, smoothing, tol * 0.25, &shaping); + let dabbed = shaping.spacing > 0.0 && line.len() > 1; + if dabbed { + line = dabs(&line, shaping.spacing * tip.size); + } let m = tip.to_stage(); let Some(inv) = m.inverse().filter(|i| i.is_finite()) else { return Path::new() }; if line.is_empty() || !(tip.size.is_finite() && tip.size > 0.0) { @@ -164,6 +308,8 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> TipShape::Round => 1.0 / 6.0, TipShape::Square => 1.0 / 8.0, }; + // A ragged edge needs cells finer than its grain. + let fine: f64 = if shaping.jitter > 0.0 { f64::min(fine, 1.0 / 14.0) } else { fine }; let mut c: f64 = (fmin / 2.5).min(fine); for _ in 0..4 { let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0); @@ -180,6 +326,10 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> } let (w, h) = (w as usize, h as usize); let mut field = vec![OUTSIDE as f32; w * h]; + // How deep the ragged edge wears in, in cells (the tip's radius is 1, its size 2); the + // field inside reaches that much deeper, so the wear never opens holes in the middle. + let wear = f64::from(shaping.jitter) * 2.0 / c; + let top = 1.0 + MARGIN + wear; // Nothing thinner than a cell, so no part slips between the samples. let pts: Vec<(P, f64)> = thin(&q, c * 0.5).into_iter().map(|(p, f)| (p, f.max(c))).collect(); let mut stamp = |a: P, ra: f64, b: P, rb: f64| { @@ -198,7 +348,7 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> TipShape::Round => round_dist((px, py), a, ra, b, rb), TipShape::Square => square_dist((px, py), a, ra, b, rb), }; - let v = (0.5 - d / c).clamp(OUTSIDE, 1.0 + MARGIN) as f32; + let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32; if let Some(cell) = field.get_mut(y * w + x) && v > *cell { @@ -209,6 +359,7 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> }; match pts.as_slice() { [(p, f)] => stamp(*p, *f, *p, *f), + _ if dabbed => pts.iter().for_each(|(p, f)| stamp(*p, *f, *p, *f)), _ => { for pair in pts.windows(2) { let &[(a, ra), (b, rb)] = pair else { continue }; @@ -222,6 +373,18 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> } } } + if wear > 0.0 { + // Wear the edge by a fixed noise pattern in tip space (so the grain stays put however + // the stroke runs): the field is a distance, so lowering it by `wear × n` moves the + // edge in by that much. + for (i, v) in field.iter_mut().enumerate() { + if *v <= OUTSIDE as f32 { + continue; + } + let (x, y) = ((i % w) as f64, (i / w) as f64); + *v -= (wear * grain((origin.0 + (x + 0.5) * c, origin.1 + (y + 0.5) * c))) as f32; + } + } let to_stage = |p: Vec2| m.apply(Vec2::new((origin.0 + f64::from(p.x) * c) as f32, (origin.1 + f64::from(p.y) * c) as f32)); // A corner is a turn of 60° over the window either side. Round tips: two cells (their // tightest curve is 2.5 cells, too gentle to count). Square tips: four, so a corner the @@ -262,6 +425,32 @@ fn lerp(a: P, b: P, t: f64) -> P { (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) } +/// Smooth value noise in `0..1` from a fixed integer hash: two octaves, 0.5 and 0.2 tip units +/// across. The same point always gives the same value, on every platform. +fn grain(p: P) -> f64 { + fn hash(x: i64, y: i64) -> f64 { + // SplitMix64's finaliser over the lattice point. + let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 11) as f64 / (1u64 << 53) as f64 + } + // Each octave reads its own lattice rows (`layer` shifts them far apart), so the two + // octaves are independent. + fn octave(p: P, size: f64, layer: i64) -> f64 { + let (u, v) = (p.0 / size, p.1 / size); + let (x0, y0) = (u.floor(), v.floor()); + let s = |t: f64| t * t * (3.0 - 2.0 * t); + let (sx, sy) = (s(u - x0), s(v - y0)); + let (xi, yi) = (x0.clamp(-1e15, 1e15) as i64, (y0.clamp(-1e15, 1e15) as i64).wrapping_add(layer << 52)); + let top = hash(xi, yi) + (hash(xi + 1, yi) - hash(xi, yi)) * sx; + let bottom = hash(xi, yi + 1) + (hash(xi + 1, yi + 1) - hash(xi, yi + 1)) * sx; + top + (bottom - top) * sy + } + (octave(p, 0.5, 0) * 2.0 + octave(p, 0.2, 1)) / 3.0 +} + /// Drops points closer than `gap` to the last kept one (the last point always stays). fn thin(q: &[(P, f64)], gap: f64) -> Vec<(P, f64)> { let mut out: Vec<(P, f64)> = Vec::with_capacity(q.len()); @@ -429,8 +618,80 @@ mod tests { } } + fn loops(p: &Path) -> usize { + p.cmds.iter().filter(|c| matches!(c, PathCmd::MoveTo(_))).count() + } + + #[test] + fn tapers_come_to_points_and_keep_the_middle() { + let s = line(Vec2::ZERO, Vec2::new(300.0, 0.0), 60, |_| 1.0); + let sh = Shaping { taper_start: 0.3, taper_end: 0.3, ..Shaping::default() }; + let p = outline_shaped(&s, &Tip::round(20.0), &sh, 1.0, 0.1); + let inside = |x: f32, y: f32| p.contains(Vec2::new(x, y), &Affine::IDENTITY, FillRule::EvenOdd); + assert!(inside(150.0, 9.0), "full width in the middle: {:?} {}", p.bounds(), loops(&p)); + assert!(inside(5.0, 0.0) && !inside(5.0, 3.0), "pointed at the start"); + assert!(!inside(295.0, 3.0), "pointed at the end"); + // Area: less than the plain stroke, more than its middle part alone. + let plain = area(&outline(&s, &Tip::round(20.0), 1.0, 0.1)); + let a = area(&p); + assert!(a < plain * 0.85 && a > 0.4 * 300.0 * 20.0, "{a} vs {plain}"); + assert!((sh.taper(0.5) - 1.0).abs() < 1e-6 && sh.taper(0.0) < 0.06 && sh.taper(1.0) < 0.06); + } + + #[test] + fn spacing_stamps_separate_dabs() { + let s = line(Vec2::ZERO, Vec2::new(200.0, 0.0), 40, |_| 1.0); + // Dabs two sizes apart: 200 / 20 + 1 = 11 separate dots of the tip's area. + let sh = Shaping { spacing: 2.0, ..Shaping::default() }; + let p = outline_shaped(&s, &Tip::round(10.0), &sh, 0.5, 0.1); + assert_eq!(loops(&p), 11); + let want = 11.0 * std::f32::consts::PI * 25.0; + assert!((area(&p) - want).abs() / want < 0.02, "{} vs {want}", area(&p)); + // Closer than the tip's size, they join into one stroke. + let joined = outline_shaped(&s, &Tip::round(10.0), &Shaping { spacing: 0.5, ..Shaping::default() }, 0.5, 0.1); + assert_eq!(loops(&joined), 1); + // A dab budget: a huge stroke at the smallest spacing still stamps a bounded number. + let long = dabs(&[(Vec2::ZERO, 1.0), (Vec2::new(1e6, 0.0), 1.0)], 0.01); + assert!(long.len() <= MAX_DABS); + } + + #[test] + fn a_ragged_edge_wears_in_and_is_the_same_every_time() { + let s = line(Vec2::ZERO, Vec2::new(300.0, 40.0), 60, |t| 0.6 + 0.4 * t); + let sh = Shaping { jitter: 0.2, ..Shaping::default() }; + let tip = Tip::round(24.0); + let p = outline_shaped(&s, &tip, &sh, 1.0, 0.2); + let plain = outline(&s, &tip, 1.0, 0.2); + let (a, b) = (area(&p), area(&plain)); + // It wears in by up to a fifth of the size on each side: within the plain stroke, + // never less than what is left after the deepest wear. + assert!(a < b * 0.97 && a > b * 0.55, "{a} vs {b}"); + assert!(p.bounds().width() <= plain.bounds().width() + 0.5); + assert!(p.anchors().len() > plain.anchors().len() * 2, "ragged: {} vs {}", p.anchors().len(), plain.anchors().len()); + assert_eq!(p, outline_shaped(&s, &tip, &sh, 1.0, 0.2), "deterministic"); + } + + #[test] + fn the_paint_brush_line_has_a_profile() { + let s = line(Vec2::ZERO, Vec2::new(200.0, 0.0), 40, |t| t); + let (path, prof) = centre_stroke(&s, &Shaping::default(), 1.0, 0.1, 16); + assert!(!path.is_empty() && prof.len() == 16); + assert_eq!(prof.first().map(|p| p.0), Some(0.0)); + assert_eq!(prof.last().map(|p| p.0), Some(1.0)); + // Pressure from 0 to 1: factors from the floor to full. + assert!(prof.first().is_some_and(|p| (p.1 - MIN_PRESSURE_SIZE).abs() < 0.03)); + assert!(prof.last().is_some_and(|p| p.1 > 0.97)); + assert!(prof.windows(2).all(|w| w[1].1 >= w[0].1 - 1e-4), "rising"); + let b = path.bounds(); + assert!((b.width() - 200.0).abs() < 1.0 && b.height() < 1.0); + assert!(centre_stroke(&s[..1], &Shaping::default(), 1.0, 0.1, 16).0.is_empty(), "a dab is no line"); + } + #[test] fn hostile_input_is_empty_or_bounded() { + let wild = Shaping { taper_start: f32::NAN, taper_end: 1e9, spacing: -3.0, jitter: f32::INFINITY }; + assert_eq!(wild.sanitized(), Shaping { taper_start: 0.0, taper_end: 0.5, spacing: 0.0, jitter: 0.0 }); + let _ = outline_shaped(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(5.0), &Shaping { spacing: 1e-9, jitter: 0.5, ..wild }, 1.0, 1.0); assert!(outline(&[], &Tip::round(10.0), 1.0, 1.0).is_empty()); let nan = [Sample { at: Vec2::new(f32::NAN, 0.0), pressure: f32::NAN }]; assert!(outline(&nan, &Tip::round(10.0), 1.0, 1.0).is_empty()); diff --git a/crates/geom/src/envelope.rs b/crates/geom/src/envelope.rs new file mode 100644 index 00000000..1ab79870 --- /dev/null +++ b/crates/geom/src/envelope.rs @@ -0,0 +1,256 @@ +//! Envelope (ADR 0080): bending outlines by a bicubic Bézier patch, as Animate's Modify › +//! Transform › Envelope does. +//! +//! The patch has 4 × 4 control points over a rest rectangle. A point at `(u, v)` of the +//! rectangle (0 to 1 across and down) goes to `Σ Bᵢ(u) Bⱼ(v) Pᵢⱼ`, the Bernstein polynomials of +//! degree 3. At rest the control points are evenly spaced (a third of the way apart), and the +//! map is exactly the identity (Bernstein polynomials reproduce linear functions). +//! +//! The image of a cubic under the patch is a curve of degree 9, so it is approximated: each +//! segment is cut in halves until the cubic through its mapped control points is within the +//! tolerance of the true image at its quarter points. A straight segment that stays straight (any +//! affine part of the patch) stays one line. + +use crate::{Path, PathCmd, Rect, Vec2}; + +/// Most times a segment is halved. +const MAX_DEPTH: u32 = 10; +/// Most commands a bent path may have; beyond it [`warp`] declines. +pub const MAX_COMMANDS: usize = 200_000; + +/// The patch's control points, row by row from the top-left (`points[4 * row + column]`). +pub type Mesh = [Vec2; 16]; + +/// The mesh that leaves everything where it is: control points evenly over `rest`. +pub fn rest_mesh(rest: &Rect) -> Mesh { + let mut m = [Vec2::ZERO; 16]; + for (k, p) in m.iter_mut().enumerate() { + let (i, j) = ((k % 4) as f32, (k / 4) as f32); + *p = Vec2::new(rest.min.x + rest.width() * i / 3.0, rest.min.y + rest.height() * j / 3.0); + } + m +} + +/// The indices of the boundary handles, clockwise from the top-left corner: corners and the two +/// tangent points of each side (the inner four follow them, [`coons_interior`]). +pub const BOUNDARY: [usize; 12] = [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4]; +/// The corners, clockwise from the top-left. +pub const CORNERS: [usize; 4] = [0, 3, 15, 12]; + +/// Sets the four inner control points from the boundary, as a bicubic Coons patch does: the +/// sides bend the inside smoothly, and a rest boundary gives the rest mesh. +pub fn coons_interior(m: &mut Mesh) { + let p = |r: usize, c: usize| m[4 * r + c]; + let blend = |a: Vec2, b: Vec2, c: Vec2, d: Vec2, e: Vec2, f: Vec2, g: Vec2, h: Vec2| (a * -4.0 + (b + c) * 6.0 - (d + e) * 2.0 + (f + g) * 3.0 - h) * (1.0 / 9.0); + let p11 = blend(p(0, 0), p(0, 1), p(1, 0), p(0, 3), p(3, 0), p(3, 1), p(1, 3), p(3, 3)); + let p12 = blend(p(0, 3), p(0, 2), p(1, 3), p(0, 0), p(3, 3), p(3, 2), p(1, 0), p(3, 0)); + let p21 = blend(p(3, 0), p(3, 1), p(2, 0), p(3, 3), p(0, 0), p(0, 1), p(2, 3), p(0, 3)); + let p22 = blend(p(3, 3), p(3, 2), p(2, 3), p(3, 0), p(0, 3), p(0, 2), p(2, 0), p(0, 0)); + m[5] = p11; + m[6] = p12; + m[9] = p21; + m[10] = p22; +} + +fn bernstein(t: f64) -> [f64; 4] { + let u = 1.0 - t; + [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t] +} + +/// Where the patch puts `p` (a point of the rest rectangle's plane; outside it, the patch's +/// polynomial carries on). +pub fn map(mesh: &Mesh, rest: &Rect, p: Vec2) -> Vec2 { + let (w, h) = (f64::from(rest.width()), f64::from(rest.height())); + if !(w > 1e-9 && h > 1e-9) { + return p; + } + let u = (f64::from(p.x) - f64::from(rest.min.x)) / w; + let v = (f64::from(p.y) - f64::from(rest.min.y)) / h; + let (bu, bv) = (bernstein(u), bernstein(v)); + let (mut x, mut y) = (0.0f64, 0.0f64); + for (k, q) in mesh.iter().enumerate() { + let wgt = bu[k % 4] * bv[k / 4]; + x += wgt * f64::from(q.x); + y += wgt * f64::from(q.y); + } + Vec2::new(x as f32, y as f32) +} + +fn cubic_at(c: &[Vec2; 4], t: f32) -> Vec2 { + let u = 1.0 - t; + c[0] * (u * u * u) + c[1] * (3.0 * u * u * t) + c[2] * (3.0 * u * t * t) + c[3] * (t * t * t) +} + +fn split(c: &[Vec2; 4]) -> ([Vec2; 4], [Vec2; 4]) { + let (ab, bc, cd) = (c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5)); + let (abc, bcd) = (ab.lerp(bc, 0.5), bc.lerp(cd, 0.5)); + let m = abc.lerp(bcd, 0.5); + ([c[0], ab, abc, m], [m, bcd, cd, c[3]]) +} + +/// Whether every mesh point is finite and the rest rectangle has an area. +pub fn valid(mesh: &Mesh, rest: &Rect) -> bool { + mesh.iter().all(|p| p.x.is_finite() && p.y.is_finite()) && rest.width() > 1e-6 && rest.height() > 1e-6 && rest.min.x.is_finite() && rest.min.y.is_finite() && rest.max.x.is_finite() && rest.max.y.is_finite() +} + +/// `path` bent by the patch (both in the same space), within `tol`. `None` when the bent path +/// would be too large ([`MAX_COMMANDS`]) or the mesh isn't valid. +pub fn warp(path: &Path, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + if !valid(mesh, rest) { + return None; + } + let tol = if tol.is_finite() { tol.max(1e-4) } else { 0.05 }; + let mut out = Path::new(); + let (mut start, mut cur) = (Vec2::ZERO, Vec2::ZERO); + let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]; + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + out.move_to(map(mesh, rest, p)); + start = p; + cur = p; + } + PathCmd::LineTo(p) => { + segment(&mut out, &line(cur, p), true, mesh, rest, tol, 0); + cur = p; + } + PathCmd::QuadTo(q, p) => { + segment(&mut out, &[cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + segment(&mut out, &[cur, a, b, p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::Close => { + // The closing edge bends too: when it no longer is straight, draw it, then + // close on the start. + if cur != start && !stays_straight(&line(cur, start), mesh, rest, tol) { + segment(&mut out, &line(cur, start), true, mesh, rest, tol, 0); + } + out.close(); + cur = start; + } + } + if out.cmds.len() > MAX_COMMANDS { + return None; + } + } + Some(out) +} + +/// Whether the line `c` (as a cubic) stays straight: its image's quarter points are on the +/// chord between its mapped ends, evenly. +fn stays_straight(c: &[Vec2; 4], mesh: &Mesh, rest: &Rect, tol: f32) -> bool { + let (a, b) = (map(mesh, rest, c[0]), map(mesh, rest, c[3])); + [0.25f32, 0.5, 0.75].iter().all(|&t| map(mesh, rest, cubic_at(c, t)).distance(a.lerp(b, t)) <= tol) +} + +/// One segment (as a cubic, `straight` when it is a line), bent and appended. +fn segment(out: &mut Path, c: &[Vec2; 4], straight: bool, mesh: &Mesh, rest: &Rect, tol: f32, depth: u32) { + let m = [map(mesh, rest, c[0]), map(mesh, rest, c[1]), map(mesh, rest, c[2]), map(mesh, rest, c[3])]; + let err = [0.25f32, 0.5, 0.75].iter().map(|&t| map(mesh, rest, cubic_at(c, t)).distance(cubic_at(&m, t))).fold(0.0f32, f32::max); + if straight && stays_straight(c, mesh, rest, tol) { + out.line_to(m[3]); + return; + } + if err <= tol || depth >= MAX_DEPTH || out.cmds.len() > MAX_COMMANDS { + out.cubic_to(m[1], m[2], m[3]); + return; + } + let (a, b) = split(c); + segment(out, &a, false, mesh, rest, tol, depth + 1); + segment(out, &b, false, mesh, rest, tol, depth + 1); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Affine; + + fn rest() -> Rect { + Rect::new(10.0, 20.0, 110.0, 70.0) + } + + /// At rest the map is the identity, and a bent path is the path itself, command for command. + #[test] + fn identity_at_rest() { + let r = rest(); + let m = rest_mesh(&r); + for p in [Vec2::new(10.0, 20.0), Vec2::new(60.0, 45.0), Vec2::new(110.0, 70.0), Vec2::new(-30.0, 200.0)] { + assert!(map(&m, &r, p).distance(p) < 1e-3, "{p:?}"); + } + let mut path = Path::rounded_rect(10.0, 20.0, 100.0, 50.0, 12.0); + path.cmds.extend(Path::star(60.0, 45.0, 20.0, 8.0, 5).cmds); + let bent = warp(&path, &m, &r, 0.01).expect("bends"); + assert_eq!(bent.cmds.len(), path.cmds.len(), "nothing is subdivided at rest"); + for (a, b) in bent.cmds.iter().zip(&path.cmds) { + assert_eq!(std::mem::discriminant(a), std::mem::discriminant(b), "lines stay lines"); + } + let (fa, fb) = (bent.flatten(&Affine::IDENTITY, 0.01), path.flatten(&Affine::IDENTITY, 0.01)); + for (pa, pb) in fa.iter().zip(&fb) { + for (x, y) in pa.points.iter().zip(&pb.points) { + assert!(x.distance(*y) < 1e-3); + } + } + } + + /// A rest boundary gives the rest interior; moving every point by the same affine map + /// moves the path by it, lines staying lines. + #[test] + fn coons_and_affine_meshes() { + let r = rest(); + let mut m = rest_mesh(&r); + let want = m; + m[5] = Vec2::ZERO; + m[10] = Vec2::new(1e3, 1e3); + coons_interior(&mut m); + for (a, b) in m.iter().zip(&want) { + assert!(a.distance(*b) < 1e-3); + } + let xf = Affine::translate(5.0, -3.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.5, 0.75)); + let moved: Mesh = want.map(|p| xf.apply(p)); + let path = Path::rect(20.0, 30.0, 40.0, 20.0); + let bent = warp(&path, &moved, &r, 0.01).expect("bends"); + assert!(bent.cmds.iter().all(|c| !matches!(c, PathCmd::CubicTo(..))), "an affine envelope keeps lines straight"); + let pts = bent.flatten(&Affine::IDENTITY, 0.01); + for (p, q) in pts[0].points.iter().zip(path.flatten(&xf, 0.01)[0].points.iter()) { + assert!(p.distance(*q) < 1e-2, "{p:?} vs {q:?}"); + } + } + + /// A bulged top side bends a straight top edge into a curve through the bulge, within the + /// tolerance of the exact image everywhere. + #[test] + fn bending_is_within_tolerance() { + let r = rest(); + let mut m = rest_mesh(&r); + m[1].y -= 30.0; + m[2].y -= 30.0; + coons_interior(&mut m); + let path = Path::rect(10.0, 20.0, 100.0, 50.0); + let tol = 0.05; + let bent = warp(&path, &m, &r, tol).expect("bends"); + assert!(bent.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..)))); + // The top edge's middle rose by ¾ of the handles' lift (B₁ + B₂ at ½). + let top = map(&m, &r, Vec2::new(60.0, 20.0)); + assert!((top.y - (20.0 - 22.5)).abs() < 1e-3, "{top:?}"); + // Every point of the exact image of the top edge is near the bent outline. + let poly = &bent.flatten(&Affine::IDENTITY, 0.005)[0].points; + for i in 0..=50 { + let exact = map(&m, &r, Vec2::new(10.0 + 2.0 * i as f32, 20.0)); + let d = poly.windows(2).map(|w| crate::segment_distance(exact, w[0], w[1])).fold(f32::MAX, f32::min); + assert!(d < tol * 2.0, "{i}: {d}"); + } + } + + #[test] + fn invalid_meshes_decline() { + let r = rest(); + let mut m = rest_mesh(&r); + m[3].x = f32::NAN; + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &m, &r, 0.1).is_none()); + let flat = Rect::new(0.0, 0.0, 10.0, 0.0); + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &rest_mesh(&flat), &flat, 0.1).is_none()); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e0b75dd1..9f740d0b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -8,9 +8,12 @@ mod affine; pub mod brush; pub mod clip; pub mod edit; +pub mod envelope; pub mod morph; pub mod planar; +pub mod pressure; pub mod raw; +pub mod slice; mod fit; mod path; pub mod svg; @@ -19,7 +22,7 @@ pub mod walk; pub use affine::{Affine, Decomposed}; pub use fit::fit_curve; -pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance}; +pub use path::{FillRule, POLYSTAR_MAX_SIDES, Path, PathCmd, Polyline, polystar_corners, segment_distance, star_inner_radius}; use serde::{Deserialize, Serialize}; use std::ops::{Add, Mul, Neg, Sub}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5c29dd2f..c1813a49 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -203,6 +203,36 @@ const MAX_SEGMENTS_PER_CURVE: usize = 1024; /// Bézier circle constant. const KAPPA: f32 = 0.552_284_8; +/// Most corners a PolyStar has on each side of its outline (sides or points). +pub const POLYSTAR_MAX_SIDES: u32 = 256; + +/// The inner radius of a star of `points` points for a point size from 0 to 1 (ADR 0080): at 1 +/// the inner corners lie on the edges of the polygon through the tips (the star is that polygon), +/// at 0 they meet in the centre (needle points), and in between the depth is proportional. Out +/// of range or not a number, the point size is clamped (or 0.5). +pub fn star_inner_radius(outer: f32, points: u32, point_size: f32) -> f32 { + let n = points.clamp(3, POLYSTAR_MAX_SIDES) as f32; + let size = if point_size.is_finite() { point_size.clamp(0.0, 1.0) } else { 0.5 }; + outer * size * (std::f32::consts::PI / n).cos() +} + +/// The corners of [`Path::polystar`], in order (clockwise on screen, y down), the first straight +/// up: `sides` of them for a polygon, `2 × sides` (tip, inner, tip, …) for a star. `sides` is +/// clamped to 3..=[`POLYSTAR_MAX_SIDES`]. +pub fn polystar_corners(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Vec { + let n = sides.clamp(3, POLYSTAR_MAX_SIDES) as usize; + let inner = star_inner_radius(radius, sides, point_size); + let steps = if star { n * 2 } else { n }; + (0..steps) + .map(|i| { + let r = if star && i % 2 == 1 { inner } else { radius }; + // f64 so the corners of a big polygon stay where they belong. + let a = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::TAU / steps as f64; + Vec2::new(cx + r * a.cos() as f32, cy + r * a.sin() as f32) + }) + .collect() +} + impl Path { pub fn new() -> Self { Self::default() @@ -274,6 +304,22 @@ impl Path { p } + /// The PolyStar tool's outline (ADR 0080): a regular polygon of `sides` corners, or a star of + /// `sides` points whose inner corners are at [`star_inner_radius`] for `point_size`, centred + /// at `(cx, cy)` with the first corner straight up. + pub fn polystar(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Path { + let mut p = Path::new(); + for (i, v) in polystar_corners(cx, cy, radius, sides, star, point_size).into_iter().enumerate() { + if i == 0 { + p.move_to(v); + } else { + p.line_to(v); + } + } + p.close(); + p + } + /// Star (or polygon when `inner == outer`) with `points` tips, first tip pointing up. pub fn star(cx: f32, cy: f32, outer: f32, inner: f32, points: u32) -> Path { let n = points.clamp(3, 256) as usize; @@ -499,6 +545,71 @@ pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { mod tests { use super::*; + /// Shoelace area of a polygon. + fn poly_area(pts: &[Vec2]) -> f64 { + let n = pts.len(); + (0..n).map(|i| { + let (a, b) = (pts[i], pts[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + } + + /// ADR 0080: a regular polygon's corners are on its circle, its first straight up, and its + /// area is n/2 · r² · sin(2π/n). + #[test] + fn polystar_polygon_is_regular() { + for n in [3u32, 4, 5, 6, 8, 12, 32] { + let r = 50.0; + let pts = polystar_corners(10.0, -20.0, r, n, false, 0.3); + assert_eq!(pts.len(), n as usize); + assert!((pts[0].x - 10.0).abs() < 1e-4 && (pts[0].y - (-20.0 - r)).abs() < 1e-4, "first corner straight up: {:?}", pts[0]); + for p in &pts { + assert!(((*p - Vec2::new(10.0, -20.0)).length() - r).abs() < 1e-3); + } + let want = f64::from(n) / 2.0 * f64::from(r * r) * (std::f64::consts::TAU / f64::from(n)).sin(); + let got = poly_area(&pts); + assert!((got.abs() - want).abs() < want * 1e-5, "n {n}: {got} vs {want}"); + // Clockwise on screen (y down): positive shoelace area. + assert!(got > 0.0); + // The path is the same polygon. + let path = Path::polystar(10.0, -20.0, r, n, false, 0.3); + assert_eq!(path.cmds.len(), n as usize + 1); + } + } + + /// ADR 0080: a star's inner corners are at r · size · cos(π/n): at 1 they lie on the + /// polygon's edges (the star covers exactly the polygon), at 0 in the centre, and its area + /// is n · r · r_in · sin(π/n). + #[test] + fn polystar_star_point_size() { + let r = 80.0f32; + for n in [3u32, 5, 7, 32] { + let half = std::f64::consts::PI / f64::from(n); + for size in [0.0f32, 0.25, 0.5, 1.0] { + let pts = polystar_corners(0.0, 0.0, r, n, true, size); + assert_eq!(pts.len(), 2 * n as usize); + let inner = f64::from(r) * f64::from(size) * half.cos(); + assert!((f64::from(star_inner_radius(r, n, size)) - inner).abs() < 1e-3); + for (i, p) in pts.iter().enumerate() { + let want = if i % 2 == 0 { f64::from(r) } else { inner }; + assert!((f64::from(p.length()) - want).abs() < 1e-3, "n {n} size {size} corner {i}"); + } + let want = f64::from(n) * f64::from(r) * inner * half.sin(); + assert!((poly_area(&pts) - want).abs() <= want * 1e-4 + 1e-3, "n {n} size {size}"); + } + // Point size 1: the area of the polygon through the tips. + let full = poly_area(&polystar_corners(0.0, 0.0, r, n, true, 1.0)); + let poly = poly_area(&polystar_corners(0.0, 0.0, r, n, false, 1.0)); + assert!((full - poly).abs() < poly * 1e-5); + } + // Out of range and not a number: clamped, or the default. + assert_eq!(star_inner_radius(10.0, 5, 3.0), star_inner_radius(10.0, 5, 1.0)); + assert_eq!(star_inner_radius(10.0, 5, -1.0), 0.0); + assert_eq!(star_inner_radius(10.0, 5, f32::NAN), star_inner_radius(10.0, 5, 0.5)); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, 0, false, 0.5).len(), 3); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, u32::MAX, false, 0.5).len(), POLYSTAR_MAX_SIDES as usize); + } + #[test] fn flatten_rect_is_closed_polygon() { let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); diff --git a/crates/geom/src/planar.rs b/crates/geom/src/planar.rs index d21de9d1..b52c3e6e 100644 --- a/crates/geom/src/planar.rs +++ b/crates/geom/src/planar.rs @@ -75,6 +75,33 @@ pub fn merge_cut(items: &[Item], cutter: &Path) -> Option { merge_with(items, Some(cutter)) } +/// The area `paths` cover together (each filled by its own rule), as one path of loops that +/// don't overlap: even-odd and non-zero fill it alike. Empty when they cover nothing; `None` +/// when there is too much to merge at once. +pub fn union(paths: &[(&Path, FillRule)]) -> Option { + let items: Vec = paths.iter().map(|&(path, fill_rule)| Item { path, fill: Some(0), fill_rule, stroke: None }).collect(); + let merged = merge(&items)?; + Some(join(merged.fills.into_iter().map(|p| p.path))) +} + +/// The part of `subject` (filled by `rule`) inside `region` (filled even-odd, such as a +/// [`union`]): a boolean intersection, exact to [`SNAP`], as one path of loops that don't +/// overlap (ADR 0080: the Brush's Paint Selection and Paint Inside). Empty when they don't +/// overlap; `None` when there is too much to merge at once. +pub fn intersect(subject: &Path, rule: FillRule, region: &Path) -> Option { + let merged = merge_cut(&[Item { path: subject, fill: Some(0), fill_rule: rule, stroke: None }], region)?; + Some(join(merged.fills.into_iter().filter(|p| p.inside).map(|p| p.path))) +} + +/// Pieces' paths, one after another. +fn join(pieces: impl Iterator) -> Path { + let mut out = Path::new(); + for p in pieces { + out.cmds.extend(p.cmds); + } + out +} + /// The item number the cutter's segments carry. const CUTTER: usize = usize::MAX; diff --git a/crates/geom/src/planar_tests.rs b/crates/geom/src/planar_tests.rs index 6ee8526e..a951c2ba 100644 --- a/crates/geom/src/planar_tests.rs +++ b/crates/geom/src/planar_tests.rs @@ -330,3 +330,43 @@ fn a_cutter_over_a_curve_cuts_exact_pieces() { assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}"); assert_eq!(m.fills.len(), 2); } + +// ----- union and intersection (ADR 0080) -------------------------------------------------------- + +/// Two overlapping squares: the union covers 10² + 10² − 5·5, and the even-odd area of the +/// joined path agrees (no overlapping loops). +#[test] +fn union_of_overlapping_squares() { + let (a, b) = (rect(0.0, 0.0, 10.0, 10.0), rect(5.0, 5.0, 10.0, 10.0)); + let u = union(&[(&a, FillRule::NonZero), (&b, FillRule::NonZero)]).expect("merges"); + assert!((area(&u) - 175.0).abs() < 0.05, "{}", area(&u)); + assert!(u.contains(Vec2::new(12.0, 12.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(u.contains(Vec2::new(7.0, 7.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the overlap is covered once"); + assert!(!u.contains(Vec2::new(12.0, 2.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(union(&[]).expect("nothing to merge").is_empty()); +} + +/// A bar across a square keeps only the part inside it; a disc inside a square with a hole +/// loses the hole. +#[test] +fn intersect_clips_to_the_region() { + let bar = rect(-20.0, 4.0, 60.0, 2.0); + let square = rect(0.0, 0.0, 10.0, 10.0); + let clipped = intersect(&bar, FillRule::NonZero, &square).expect("merges"); + assert!((area(&clipped) - 20.0).abs() < 0.05, "{}", area(&clipped)); + // Nothing in common. + let far = rect(100.0, 100.0, 5.0, 5.0); + assert!(intersect(&far, FillRule::NonZero, &square).expect("merges").is_empty()); + // A ring (square with a square hole, even-odd) clipping a square that covers it all. + let mut ring = rect(0.0, 0.0, 30.0, 30.0); + ring.cmds.extend(rect(10.0, 10.0, 10.0, 10.0).cmds); + let cover = rect(-5.0, -5.0, 40.0, 40.0); + let inside = intersect(&cover, FillRule::NonZero, &ring).expect("merges"); + assert!((area(&inside) - 800.0).abs() < 0.1, "{}", area(&inside)); + assert!(!inside.contains(Vec2::new(15.0, 15.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the hole stays empty"); + // A circle's quarter: exact to the curve. + let disc = Path::ellipse(0.0, 0.0, 10.0, 10.0); + let quarter = intersect(&disc, FillRule::NonZero, &rect(0.0, 0.0, 20.0, 20.0)).expect("merges"); + let want = std::f32::consts::PI * 100.0 / 4.0; + assert!((area(&quarter) - want).abs() < want * 0.002, "{} vs {want}", area(&quarter)); +} diff --git a/crates/geom/src/pressure.rs b/crates/geom/src/pressure.rs new file mode 100644 index 00000000..a31a315a --- /dev/null +++ b/crates/geom/src/pressure.rs @@ -0,0 +1,273 @@ +//! Pressure curves (ADR 0068): how pen pressure maps to the brush's size (and, optionally, the +//! paint's opacity). +//! +//! A curve is a few points `(input, output)` in `0..=1`, sorted by input, with one at input 0 +//! and one at input 1. Between them it follows a monotone cubic (Fritsch–Carlson): smooth, +//! through every point, never overshooting a neighbour, so the output stays in `0..=1` and a +//! rising curve never dips. It is `Copy` (a fixed array), so tool options holding it stay cheap. + +use serde::{Deserialize, Serialize}; + +/// Most points one curve keeps. +pub const MAX_CURVE_POINTS: usize = 8; +/// Points closer than this in input are one point (the last given wins). +const MERGE: f32 = 0.02; + +/// A pressure curve. Build one with [`PressureCurve::new`] (sanitizing) or a preset. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "Vec<[f32; 2]>", into = "Vec<[f32; 2]>")] +pub struct PressureCurve { + n: u8, + pts: [[f32; 2]; MAX_CURVE_POINTS], +} + +/// The built-in curves: `(key, label)`. +pub const CURVE_PRESETS: [(&str, &str); 3] = [("linear", "Linear"), ("soft", "Soft"), ("firm", "Firm")]; + +impl Default for PressureCurve { + fn default() -> Self { + PressureCurve::LINEAR + } +} + +const fn fixed(a: [[f32; 2]; 3], n: u8) -> PressureCurve { + let mut pts = [[0.0; 2]; MAX_CURVE_POINTS]; + pts[0] = a[0]; + pts[1] = a[1]; + pts[2] = a[2]; + PressureCurve { n, pts } +} + +impl PressureCurve { + /// Output equals input. + pub const LINEAR: PressureCurve = fixed([[0.0, 0.0], [1.0, 1.0], [0.0, 0.0]], 2); + /// A light touch already paints wide (for a stiff pen or a light hand). + pub const SOFT: PressureCurve = fixed([[0.0, 0.0], [0.3, 0.6], [1.0, 1.0]], 3); + /// It takes a firm press to paint wide (for a soft pen or a heavy hand). + pub const FIRM: PressureCurve = fixed([[0.0, 0.0], [0.6, 0.3], [1.0, 1.0]], 3); + + /// A curve from untrusted points: non-finite ones dropped, clamped to `0..=1`, sorted, + /// merged when closer than 0.02 in input, at most [`MAX_CURVE_POINTS`], and given ends at + /// input 0 and 1 (holding the nearest point's output). No points: linear. + pub fn new(points: &[[f32; 2]]) -> PressureCurve { + let mut v: Vec<[f32; 2]> = points.iter().take(MAX_CURVE_POINTS * 8).filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0)]).collect(); + if v.is_empty() { + return PressureCurve::LINEAR; + } + v.sort_by(|a, b| a[0].total_cmp(&b[0])); + let mut out: Vec<[f32; 2]> = Vec::with_capacity(v.len() + 2); + for p in v { + match out.last_mut() { + Some(last) if p[0] - last[0] < MERGE => last[1] = p[1], + _ => out.push(p), + } + } + // Ends at 0 and 1: snap a point that is nearly there, else add one. + if let Some(first) = out.first_mut() { + if first[0] < MERGE { + first[0] = 0.0; + } else { + let y = first[1]; + out.insert(0, [0.0, y]); + } + } + if let Some(last) = out.last_mut() { + if last[0] > 1.0 - MERGE { + last[0] = 1.0; + } else { + let y = last[1]; + out.push([1.0, y]); + } + } + // Keep the ends and the first interior points that fit. + if out.len() > MAX_CURVE_POINTS + && let Some(end) = out.last().copied() + { + out.truncate(MAX_CURVE_POINTS - 1); + out.push(end); + } + let mut pts = [[0.0; 2]; MAX_CURVE_POINTS]; + for (slot, p) in pts.iter_mut().zip(&out) { + *slot = *p; + } + PressureCurve { n: out.len().min(MAX_CURVE_POINTS) as u8, pts } + } + + /// A built-in curve by key (`linear`, `soft`, `firm`). + pub fn preset(key: &str) -> Option { + match key { + "linear" => Some(PressureCurve::LINEAR), + "soft" => Some(PressureCurve::SOFT), + "firm" => Some(PressureCurve::FIRM), + _ => None, + } + } + + /// The built-in curve this is, if any. + pub fn preset_key(&self) -> Option<&'static str> { + CURVE_PRESETS.iter().map(|(k, _)| *k).find(|k| PressureCurve::preset(k).is_some_and(|c| c == *self)) + } + + pub fn points(&self) -> &[[f32; 2]] { + self.pts.get(..usize::from(self.n)).unwrap_or(&[]) + } + + /// The same curve with point `i` moved to `to` (the end points move only up and down) or, + /// with `i` past the end, a point added at `to`. + pub fn with_point(&self, i: usize, to: [f32; 2]) -> PressureCurve { + let mut v = self.points().to_vec(); + let last = v.len().saturating_sub(1); + match v.get_mut(i) { + Some(p) if i == 0 => p[1] = to[1], + Some(p) if i == last => p[1] = to[1], + // An interior point stays between its neighbours. + Some(p) => *p = to, + None => v.push(to), + } + PressureCurve::new(&v) + } + + /// Without interior point `i` (the ends stay). + pub fn without_point(&self, i: usize) -> PressureCurve { + let v: Vec<[f32; 2]> = self.points().iter().enumerate().filter(|(j, _)| *j != i || *j == 0 || *j + 1 == usize::from(self.n)).map(|(_, p)| *p).collect(); + PressureCurve::new(&v) + } + + /// The output at `pressure` (clamped to `0..=1`; not a number reads as full pressure). + pub fn map(&self, pressure: f32) -> f32 { + let x = if pressure.is_finite() { pressure.clamp(0.0, 1.0) } else { 1.0 }; + let p = self.points(); + let n = p.len(); + let (Some(first), Some(last)) = (p.first(), p.last()) else { return x }; + if n == 1 || x <= first[0] { + return first[1]; + } + if x >= last[0] { + return last[1]; + } + // Secant slopes, then Fritsch–Carlson tangents. + let sec = |i: usize| -> f32 { + match (p.get(i), p.get(i + 1)) { + (Some(a), Some(b)) if b[0] - a[0] > 1e-9 => (b[1] - a[1]) / (b[0] - a[0]), + _ => 0.0, + } + }; + let tangent = |i: usize| -> f32 { + if i == 0 { + return sec(0); + } + if i + 1 >= n { + return sec(n.saturating_sub(2)); + } + let (d0, d1) = (sec(i - 1), sec(i)); + if d0 * d1 <= 0.0 { + return 0.0; + } + // The weighted harmonic mean of the secants (Fritsch–Butland): monotone as it is. + let h = |j: usize| match (p.get(j), p.get(j + 1)) { + (Some(a), Some(b)) => (b[0] - a[0]).max(1e-6), + _ => 1e-6, + }; + let (h0, h1) = (h(i - 1), h(i)); + 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) + }; + let k = p.windows(2).position(|w| matches!(w, [a, b] if x >= a[0] && x <= b[0])).unwrap_or(0); + let (Some(a), Some(b)) = (p.get(k), p.get(k + 1)) else { return x }; + let h = b[0] - a[0]; + if h <= 1e-9 { + return b[1]; + } + let d = sec(k); + let (mut m0, mut m1) = (tangent(k), tangent(k + 1)); + // Keep the piece monotone where the data is (Fritsch–Carlson's limit). + if d == 0.0 { + m0 = 0.0; + m1 = 0.0; + } else { + let (al, be) = (m0 / d, m1 / d); + let s = al * al + be * be; + if s > 9.0 { + let t = 3.0 / s.sqrt(); + m0 = t * al * d; + m1 = t * be * d; + } + if al < 0.0 { + m0 = 0.0; + } + if be < 0.0 { + m1 = 0.0; + } + } + let t = (x - a[0]) / h; + let (t2, t3) = (t * t, t * t * t); + let y = (2.0 * t3 - 3.0 * t2 + 1.0) * a[1] + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * b[1] + (t3 - t2) * h * m1; + y.clamp(0.0, 1.0) + } +} + +impl From> for PressureCurve { + fn from(v: Vec<[f32; 2]>) -> PressureCurve { + PressureCurve::new(&v) + } +} + +impl From for Vec<[f32; 2]> { + fn from(c: PressureCurve) -> Vec<[f32; 2]> { + c.points().to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_map_as_named() { + for x in [0.0, 0.1, 0.25, 0.5, 0.8, 1.0] { + assert!((PressureCurve::LINEAR.map(x) - x).abs() < 1e-5, "linear at {x}"); + } + // Soft paints wider than linear at a light touch, firm narrower; all meet at the ends. + for x in [0.1, 0.3, 0.5, 0.7, 0.9] { + assert!(PressureCurve::SOFT.map(x) > x + 0.02 && PressureCurve::FIRM.map(x) < x - 0.02, "{x}"); + } + for c in [PressureCurve::SOFT, PressureCurve::FIRM] { + assert_eq!((c.map(0.0), c.map(1.0)), (0.0, 1.0)); + assert!((c.map(0.3) - c.points()[1][1]).abs() < 1e-5 || (c.map(0.6) - c.points()[1][1]).abs() < 1e-5, "passes through its point"); + } + assert_eq!(PressureCurve::preset("soft").and_then(|c| c.preset_key()), Some("soft")); + assert_eq!(PressureCurve::new(&[[0.0, 0.2], [1.0, 0.9]]).preset_key(), None); + } + + #[test] + fn rising_curves_never_dip_or_overshoot() { + let c = PressureCurve::new(&[[0.0, 0.0], [0.1, 0.9], [0.15, 0.92], [1.0, 1.0]]); + let mut prev = -1.0; + for i in 0..=1000 { + let y = c.map(i as f32 / 1000.0); + assert!(y >= prev - 1e-6 && (0.0..=1.0).contains(&y), "at {i}: {y} after {prev}"); + prev = y; + } + } + + #[test] + fn untrusted_points_are_sanitized() { + let c = PressureCurve::new(&[[f32::NAN, 0.0], [0.5, 2.0], [0.51, 0.4], [-3.0, 0.1]]); + // (-3, 0.1) clamps to (0, 0.1); 0.5 and 0.51 merge (the last wins); an end at 1 holds. + assert_eq!(c.points(), &[[0.0, 0.1], [0.5, 0.4], [1.0, 0.4]]); + assert_eq!(PressureCurve::new(&[]), PressureCurve::LINEAR); + let many: Vec<[f32; 2]> = (0..100).map(|i| [i as f32 / 99.0, 0.5]).collect(); + let c = PressureCurve::new(&many); + assert!(c.points().len() <= MAX_CURVE_POINTS && c.points().last() == Some(&[1.0, 0.5])); + assert_eq!(c.map(f32::NAN), 0.5); + // Moving the end points only moves them up and down; adding and removing. + let c = PressureCurve::LINEAR.with_point(0, [0.7, 0.2]); + assert_eq!(c.points(), &[[0.0, 0.2], [1.0, 1.0]]); + let c = c.with_point(9, [0.5, 0.9]); + assert_eq!(c.points().len(), 3); + assert_eq!(c.without_point(1).points().len(), 2); + assert_eq!(c.without_point(0).points().len(), 3, "ends stay"); + // A file's curve round-trips. + let json = serde_json::to_string(&PressureCurve::SOFT).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), PressureCurve::SOFT); + } +} diff --git a/crates/geom/src/slice.rs b/crates/geom/src/slice.rs new file mode 100644 index 00000000..357e32bb --- /dev/null +++ b/crates/geom/src/slice.rs @@ -0,0 +1,428 @@ +//! 9-slice scaling (ADR 0055): a box cut by four guides into corners, edges and a centre, scaled +//! so the corners keep their size, the edges stretch one way and the centre both ways. +//! +//! The map is separable: each axis is three linear pieces ([`Axis`]). Within one of the nine +//! cells it is affine, so a Bézier piece that stays in one cell maps exactly by mapping its +//! control points. [`slice_path`] cuts every segment where it crosses a guide (de Casteljau at the +//! exact crossing parameters) and maps each piece with its cell's affine; at a guide both cells +//! agree, so the result stays connected. + +use crate::{Affine, Path, PathCmd, Vec2}; + +/// One axis of a 9-slice map: the source stops `[lo, a, b, hi]` (the box's edges and the two +/// guides) and where they land. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axis { + from: [f32; 4], + to: [f32; 4], +} + +impl Axis { + /// The axis of a box `lo..hi` with guides at `a` and `b`, scaled by `k` (at least 0) about the + /// origin: the box lands where plain scaling puts it (`k·lo..k·hi`), the parts outside the + /// guides keep their size and the centre takes the rest. When the rest would be negative the + /// two outer parts share what there is, in proportion, and the centre closes. + /// + /// Guides outside the box are clamped into it (and `b` to at least `a`). `None` for an empty + /// box, a negative scale or anything not finite. + pub fn new(lo: f32, a: f32, b: f32, hi: f32, k: f32) -> Option { + if ![lo, a, b, hi, k].iter().all(|v| v.is_finite()) || hi <= lo || k < 0.0 { + return None; + } + let a = a.clamp(lo, hi); + let b = b.clamp(a, hi); + let (near, far) = (a - lo, hi - b); + let (tlo, thi) = (k * lo, k * hi); + let room = thi - tlo; + let edges = near + far; + let (near, far) = if edges > room && edges > 0.0 { (near * room / edges, far * room / edges) } else { (near, far) }; + let to = [tlo, tlo + near, thi - far, thi]; + to.iter().all(|v| v.is_finite()).then_some(Axis { from: [lo, a, b, hi], to }) + } + + /// The identity map on `lo..hi` (what an unscaled axis is). + pub fn identity(lo: f32, hi: f32) -> Axis { + Axis { from: [lo, lo, hi, hi], to: [lo, lo, hi, hi] } + } + + /// The two guides, in source space. + pub fn guides(&self) -> [f32; 2] { + [self.from[1], self.from[2]] + } + + /// Which piece `v` is in: 0 before the first guide, 1 between them, 2 after the second. + pub fn piece(&self, v: f32) -> usize { + if v < self.from[1] { + 0 + } else if v <= self.from[2] { + 1 + } else { + 2 + } + } + + /// Piece `i` as `v ↦ scale · v + offset`. The outer pieces carry on past the box's edges + /// with their own slope; a piece of no width has the slope of plain scaling (nothing lies in + /// it but its edge, which maps right either way). + pub fn linear(&self, i: usize) -> (f32, f32) { + let i = i.min(2); + let (f0, f1) = (self.from[i], self.from[i + 1]); + let (t0, t1) = (self.to[i], self.to[i + 1]); + let whole = (self.to[3] - self.to[0]) / (self.from[3] - self.from[0]).max(f32::MIN_POSITIVE); + let scale = if f1 - f0 > 1e-6 { (t1 - t0) / (f1 - f0) } else { whole }; + // Anchored where the piece starts (the outer ones at their guide, so they meet the centre). + let (anchor, at) = if i == 0 { (f1, t1) } else { (f0, t0) }; + (scale, at - scale * anchor) + } + + /// Where `v` lands. + pub fn map(&self, v: f32) -> f32 { + let (s, o) = self.linear(self.piece(v)); + s * v + o + } +} + +/// A whole 9-slice map: the horizontal and the vertical axis. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Slice9 { + pub x: Axis, + pub y: Axis, +} + +impl Slice9 { + pub fn map(&self, p: Vec2) -> Vec2 { + Vec2::new(self.x.map(p.x), self.y.map(p.y)) + } + + /// The affine map of the cell `(ix, iy)`. + pub fn cell(&self, ix: usize, iy: usize) -> Affine { + let (sx, ox) = self.x.linear(ix); + let (sy, oy) = self.y.linear(iy); + Affine { m: [sx, 0.0, 0.0, sy, ox, oy] } + } + + /// The cell a point is in. + fn cell_of(&self, p: Vec2) -> Affine { + self.cell(self.x.piece(p.x), self.y.piece(p.y)) + } +} + +/// Largest number of commands [`slice_path`] writes (a path that would grow past it is mapped +/// point by point instead, which is exact for straight edges and close for curves). +pub const MAX_SLICED_CMDS: usize = 4_000_000; + +/// `path` placed by `pre` (its own space to the box's) and then sliced by `map`: every segment cut +/// where it crosses a guide, each piece mapped by its cell's affine. Straight edges stay straight +/// within a cell, curves stay curves, fill areas stay closed (an implied closing line is drawn +/// out, since it may cross a guide). +pub fn slice_path(path: &Path, pre: &Affine, map: &Slice9) -> Path { + if path.cmds.len().saturating_mul(4) > MAX_SLICED_CMDS { + return path.transformed(pre).transformed_by(|p| map.map(p)); + } + let gx = map.x.guides(); + let gy = map.y.guides(); + let mut out = Vec::with_capacity(path.cmds.len() + 8); + let mut cur = Vec2::ZERO; + let mut start = Vec2::ZERO; + let mut ts: Vec = Vec::with_capacity(16); + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + let p = pre.apply(p); + out.push(PathCmd::MoveTo(map.map(p))); + cur = p; + start = p; + } + PathCmd::LineTo(p) => { + let p = pre.apply(p); + pieces(&[cur, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::QuadTo(a, p) => { + let (a, p) = (pre.apply(a), pre.apply(p)); + pieces(&[cur, a, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + let (a, b, p) = (pre.apply(a), pre.apply(b), pre.apply(p)); + pieces(&[cur, a, b, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::Close => { + if cur != start { + pieces(&[cur, start], &gx, &gy, map, &mut ts, &mut out); + } + out.push(PathCmd::Close); + cur = start; + } + } + } + Path { cmds: out } +} + +/// Writes segment `ctrl` (2, 3 or 4 control points: a line, a quadratic or a cubic) as its pieces +/// between guide crossings, each mapped by its cell. +fn pieces(ctrl: &[Vec2], gx: &[f32; 2], gy: &[f32; 2], map: &Slice9, ts: &mut Vec, out: &mut Vec) { + ts.clear(); + let xs: Vec = ctrl.iter().map(|p| p.x).collect(); + let ys: Vec = ctrl.iter().map(|p| p.y).collect(); + for g in gx { + crossings(&xs, *g, ts); + } + for g in gy { + crossings(&ys, *g, ts); + } + ts.sort_by(f32::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut t0 = 0.0; + for &t1 in ts.iter().chain(std::iter::once(&1.0)) { + if t1 - t0 < 1e-6 { + continue; + } + let part = sub(ctrl, t0, t1); + let mid = eval(ctrl, (t0 + t1) * 0.5); + let m = map.cell_of(mid); + push(&part, &m, out); + t0 = t1; + } +} + +fn push(part: &[Vec2], m: &Affine, out: &mut Vec) { + match *part { + [_, p] => out.push(PathCmd::LineTo(m.apply(p))), + [_, a, p] => out.push(PathCmd::QuadTo(m.apply(a), m.apply(p))), + [_, a, b, p] => out.push(PathCmd::CubicTo(m.apply(a), m.apply(b), m.apply(p))), + _ => {} + } +} + +/// The point at `t` (de Casteljau). +fn eval(ctrl: &[Vec2], t: f32) -> Vec2 { + let mut p = [Vec2::ZERO; 4]; + let n = ctrl.len().min(4); + p[..n].copy_from_slice(&ctrl[..n]); + for k in (1..n).rev() { + for i in 0..k { + p[i] = p[i].lerp(p[i + 1], t); + } + } + p[0] +} + +/// The piece of the curve between `t0` and `t1`, as control points of the same degree. +fn sub(ctrl: &[Vec2], t0: f32, t1: f32) -> Vec { + // Split at t1, keep the first part; then split that at t0 / t1, keep the second. + let first = split(ctrl, t1).0; + if t0 <= 0.0 { + return first; + } + let u = if t1 > 1e-12 { t0 / t1 } else { 0.0 }; + split(&first, u).1 +} + +/// De Casteljau split at `t`: the two halves. +fn split(ctrl: &[Vec2], t: f32) -> (Vec, Vec) { + // Each level is one point shorter: the first and last points of every level are the halves'. + let n = ctrl.len().min(4); + let mut work = [Vec2::ZERO; 4]; + work[..n].copy_from_slice(&ctrl[..n]); + let mut left = Vec::with_capacity(n); + let mut right = Vec::with_capacity(n); + for k in (0..n).rev() { + left.push(work[0]); + right.push(work[k]); + for i in 0..k { + work[i] = work[i].lerp(work[i + 1], t); + } + } + right.reverse(); + (left, right) +} + +/// Adds every `t` in (0, 1) where the 1-D Bézier `c` (2 to 4 coefficients) equals `v`: the curve +/// is cut where its derivative is zero into monotone runs, and each run that crosses `v` is +/// bisected. Exact to `f32`, at most three crossings per guide. +fn crossings(c: &[f32], v: f32, ts: &mut Vec) { + let f = |t: f32| bez1(c, t) - v; + let mut stops = [0.0f32; 4]; + let mut n = 0; + stops[n] = 0.0; + n += 1; + if let [x0, x1, x2, x3] = *c { + // Derivative (a quadratic) in power form: A t² + B t + C. + let (q0, q1, q2) = (3.0 * (x1 - x0), 3.0 * (x2 - x1), 3.0 * (x3 - x2)); + let (a, b, cc) = (q0 - 2.0 * q1 + q2, 2.0 * (q1 - q0), q0); + let mut roots = [f32::NAN; 2]; + if a.abs() > 1e-12 { + let disc = b * b - 4.0 * a * cc; + if disc >= 0.0 { + let s = disc.sqrt(); + roots = [(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)]; + } + } else if b.abs() > 1e-12 { + roots[0] = -cc / b; + } + roots.sort_by(f32::total_cmp); + for r in roots { + if r > 0.0 && r < 1.0 && n < 3 { + stops[n] = r; + n += 1; + } + } + } else if let [x0, x1, x2] = *c { + let den = x0 - 2.0 * x1 + x2; + if den.abs() > 1e-12 { + let r = (x0 - x1) / den; + if r > 0.0 && r < 1.0 { + stops[n] = r; + n += 1; + } + } + } + stops[n] = 1.0; + n += 1; + for w in stops[..n].windows(2) { + let (mut lo, mut hi) = (w[0], w[1]); + let (flo, fhi) = (f(lo), f(hi)); + if !(flo.is_finite() && fhi.is_finite()) || flo == 0.0 || fhi == 0.0 || (flo > 0.0) == (fhi > 0.0) { + continue; + } + let rising = fhi > flo; + for _ in 0..40 { + let mid = 0.5 * (lo + hi); + if (f(mid) > 0.0) == rising { + hi = mid; + } else { + lo = mid; + } + } + let t = 0.5 * (lo + hi); + if t > 1e-6 && t < 1.0 - 1e-6 { + ts.push(t); + } + } +} + +fn bez1(c: &[f32], t: f32) -> f32 { + let u = 1.0 - t; + match *c { + [a, b] => u * a + t * b, + [a, b, d] => u * u * a + 2.0 * u * t * b + t * t * d, + [a, b, d, e] => u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * d + t * t * t * e, + _ => 0.0, + } +} + +impl Path { + /// Every point mapped by `f` (any map, not only an affine one). + pub fn transformed_by(&self, f: impl Fn(Vec2) -> Vec2) -> Path { + Path { + cmds: self + .cmds + .iter() + .map(|c| match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(f(p)), + PathCmd::LineTo(p) => PathCmd::LineTo(f(p)), + PathCmd::QuadTo(a, p) => PathCmd::QuadTo(f(a), f(p)), + PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(f(a), f(b), f(p)), + PathCmd::Close => PathCmd::Close, + }) + .collect(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + + #[test] + fn an_axis_keeps_its_ends_and_gives_the_centre_the_rest() { + // A 100-wide box, 10 and 10 outside the guides, scaled 3x: 300 wide, 280 in the centre. + let ax = Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(); + assert!(close(ax.map(0.0), 0.0)); + assert!(close(ax.map(10.0), 10.0)); + assert!(close(ax.map(90.0), 290.0)); + assert!(close(ax.map(100.0), 300.0)); + assert!(close(ax.map(50.0), 150.0), "the centre scales by 280 / 80"); + // About the origin, as plain scaling: a box from -50 lands on -150..150. + let ax = Axis::new(-50.0, -40.0, 40.0, 50.0, 3.0).unwrap(); + assert!(close(ax.map(-50.0), -150.0) && close(ax.map(-40.0), -140.0) && close(ax.map(50.0), 150.0)); + } + + #[test] + fn no_spare_space_shares_what_there_is_and_closes_the_centre() { + // Corners 10 + 30 = 40 of a 100 box, scaled to 20: they shrink to 5 and 15. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.2).unwrap(); + assert!(close(ax.map(10.0), 5.0) && close(ax.map(70.0), 5.0) && close(ax.map(100.0), 20.0)); + // Exactly no spare space: the centre is a line. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.4).unwrap(); + assert!(close(ax.map(10.0), 10.0) && close(ax.map(70.0), 10.0) && close(ax.map(100.0), 40.0)); + // Zero scale: everything at the origin. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.0).unwrap(); + assert!(close(ax.map(0.0), 0.0) && close(ax.map(100.0), 0.0)); + // Guides outside or crossed are clamped; bad numbers give nothing. + let ax = Axis::new(0.0, -20.0, 140.0, 100.0, 2.0).unwrap(); + assert!(close(ax.map(50.0), 100.0)); + assert!(Axis::new(0.0, 10.0, 90.0, 0.0, 2.0).is_none()); + assert!(Axis::new(0.0, 10.0, 90.0, 100.0, -1.0).is_none()); + assert!(Axis::new(0.0, f32::NAN, 90.0, 100.0, 1.0).is_none()); + } + + #[test] + fn a_line_across_the_guides_is_cut_there() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::new(0.0, 10.0, 30.0, 40.0, 1.0).unwrap() }; + let p = slice_path(&Path::line(Vec2::new(0.0, 20.0), Vec2::new(100.0, 20.0)), &Affine::IDENTITY, &map); + let pts: Vec = p + .cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(pts.len(), 4); + for (got, want) in pts.iter().zip([0.0, 10.0, 290.0, 300.0]) { + assert!(close(got.x, want) && close(got.y, 20.0), "{got:?} vs {want}"); + } + } + + #[test] + fn a_closing_line_is_drawn_out_so_it_bends_at_the_guides() { + // A triangle whose closing edge runs diagonally across the left guide. + let p = Path { cmds: vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 40.0)), PathCmd::Close] }; + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::identity(0.0, 40.0) }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + assert_eq!(s.cmds.last(), Some(&PathCmd::Close)); + // Every vertex of the result is the map of a point on the source outline. + assert!(s.cmds.len() > p.cmds.len() + 2); + } + + #[test] + fn curves_are_cut_at_exact_crossings_and_stay_on_the_mapped_curve() { + let c = [Vec2::new(0.0, 0.0), Vec2::new(30.0, 60.0), Vec2::new(70.0, -20.0), Vec2::new(100.0, 40.0)]; + let p = Path { cmds: vec![PathCmd::MoveTo(c[0]), PathCmd::CubicTo(c[1], c[2], c[3])] }; + let map = Slice9 { x: Axis::new(0.0, 25.0, 75.0, 100.0, 2.5).unwrap(), y: Axis::new(-20.0, 0.0, 20.0, 60.0, 1.5).unwrap() }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + // Sample the source curve; each sample's image must lie on the sliced path (within + // flattening tolerance): the piecewise-affine image of a Bézier is the pieces' Béziers. + let flat: Vec = s.flatten(&Affine::IDENTITY, 0.01).into_iter().flat_map(|l| l.points).collect(); + for i in 0..=50 { + let q = map.map(eval(&c, i as f32 / 50.0)); + let d = flat.windows(2).map(|w| crate::segment_distance(q, w[0], w[1])).fold(f32::INFINITY, f32::min); + assert!(d < 0.1, "sample {i}: {d}"); + } + } + + #[test] + fn the_pre_transform_places_the_path_first() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 2.0).unwrap(), y: Axis::identity(0.0, 10.0) }; + let s = slice_path(&Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), &Affine::translate(90.0, 0.0), &map); + assert_eq!(s.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(190.0, 0.0)))); + assert!(matches!(s.cmds.last(), Some(PathCmd::LineTo(p)) if close(p.x, 200.0))); + } +} diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 9a0a5325..925b51b6 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -21,5 +21,9 @@ rayon.workspace = true web-time.workspace = true thiserror.workspace = true +[dev-dependencies] +# The shaders' types, to keep them free of what a backend leaves undefined (wgpu's own naga). +naga.workspace = true + [lints] workspace = true diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index 14c54690..770e4d19 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -13,7 +13,7 @@ //! (512 px tiles drawn in parallel, as the render service does, until finished); and how far //! the GPU-binned picture is from the oracle's. -use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; +use anicraft_doc::{Bitmap, BitmapId, ColorEffect, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; use anicraft_geom::{FillRule, Path}; use anicraft_gpu::{Binning, GpuRenderer, compare_premul8}; use anicraft_geom::Affine; @@ -54,7 +54,7 @@ fn composited() -> Document { 0 | 1 => { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { - Arc::make_mut(e).color.alpha = 0.6; + Arc::make_mut(e).color = ColorEffect::Alpha(0.6); } } } @@ -87,7 +87,7 @@ fn bitmap_layer(id: u64, n: u32, bitmaps: &[Arc], frames: u32) -> Arc Document { let mut layer = bitmap_layer(91_000, 0, std::slice::from_ref(&sky), frames); let l = Arc::make_mut(&mut layer); let fill = Paint::Bitmap { bitmap: sky.id, repeat: true, matrix: Affine::scale(5.0, 5.0) }; - let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero }; + let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, warp: None }; if let Some(k) = l.keyframes.first_mut() { Arc::make_mut(k).elements.push(Arc::new(Element { id: ElementId(91_001), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); } @@ -172,7 +172,7 @@ fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { let color = if is_past { past } else { future }; let mut part = evaluate(doc, f); for item in &mut part.items { - item.color = item.color.concat(&ColorEffect { alpha, tint: color, tint_amount: 0.8 }); + item.color = item.color.concat(&ColorTransform::alpha(alpha).concat(&ColorTransform::tint(color, 0.8))); if mode == Onion::Outlines && item.masks.is_none() { item.outline = Some(color.with_alpha(alpha)); } diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 490c48e2..7ccd8bb2 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -78,7 +78,8 @@ const IMAGE: u32 = 4; /// Op header flag: the fill is drawn inside the current clip. pub const CLIPPED: u32 = 1; -/// Op header flag: the op is clip artwork (its coverage joins the current level's union). +/// Op header flag: the op is clip artwork (its coverage joins the current level's union; in a +/// soft mask its paint composites into the level's colour). pub const ART: u32 = 2; /// An entry whose first word has this bit is a control entry, not a fill. @@ -89,11 +90,23 @@ pub const OPEN: u32 = CTRL | 1; pub const CLOSE: u32 = CTRL | 2; /// The clip coverage starts at 1 (a new clip's chain follows). pub const MASK_RESET: u32 = CTRL | 3; -/// One level of the clip chain starts: its union of artwork coverage starts at 0. +/// `[LEVEL_BEGIN, mask mode, 0, 0]`: one level of the clip chain starts: its union of artwork +/// coverage starts at 0, or for a soft mask ([`mask_code`]) its artwork's colour starts +/// transparent. pub const LEVEL_BEGIN: u32 = CTRL | 4; -/// The level ends: the clip coverage is multiplied by its union. +/// The level ends: the clip coverage is multiplied by its union (or by the soft mask's +/// opacity or luminance, ADR 0070). pub const LEVEL_END: u32 = CTRL | 5; +/// Mask modes as the shader numbers them (`fine.wgsl` › `LEVEL_END`). +pub fn mask_code(m: anicraft_doc::MaskMode) -> u32 { + match m { + anicraft_doc::MaskMode::Coverage => 0, + anicraft_doc::MaskMode::Alpha => 1, + anicraft_doc::MaskMode::Luminance => 2, + } +} + /// Blend modes as the shader numbers them (`fine.wgsl` › `blend`). pub fn blend_code(m: BlendMode) -> u32 { match m { @@ -252,7 +265,16 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_ let mut images: Vec> = Vec::new(); let ramps_at = (PAINT_VEC4S * ops.len()) as u32; // Where each layer shown by a fill goes, after the tables (the tables' size is known first). - let table_len: usize = ops.iter().filter(|f| matches!(f.shader, Shader::Linear { .. } | Shader::Radial { .. }) && f.layer.is_none()).count() * RAMP; + // Gradients' ramps, and each bitmap's colour transform (two entries). + let table_len: usize = ops + .iter() + .filter(|f| f.layer.is_none()) + .map(|f| match &f.shader { + Shader::Linear { .. } | Shader::Radial { .. } => RAMP, + Shader::Bitmap { pixels, .. } if pixels.width > 0 && pixels.height > 0 => 2, + _ => 0, + }) + .sum(); let mut layer_at: Vec> = vec![None; scene.layers.len()]; let mut cursor = PAINT_VEC4S * ops.len() + table_len; for f in &ops { @@ -282,15 +304,17 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_ (_, Some((at, b))) => (IMAGE, [[u(at), u(b.width() as u32), u(b.height() as u32), 0.0], [u(b.x0 as u32), u(b.y0 as u32), 0.0, 0.0], [0.0; 4], [0.0; 4]]), (_, None) if f.layer.is_some() => (SOLID, [[0.0; 4]; 4]), (Shader::Solid(c), _) => (SOLID, [*c, [0.0; 4], [0.0; 4], [0.0; 4]]), - (Shader::Linear { inv, start, dir, lut }, _) => { + // A gradient's first vec4 holds what its colour slot doesn't need: the spread + // (0 pad, 1 reflect, 2 repeat) and a radial gradient's focal point (ADR 0074). + (Shader::Linear { inv, start, dir, spread, lut }, _) => { ramps.extend_from_slice(&lut[..]); let m = inv.m; - (LINEAR, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]]) + (LINEAR, [[spread_code(*spread), 0.0, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]]) } - (Shader::Radial { inv, center, inv_radius, lut }, _) => { + (Shader::Radial { inv, center, inv_radius, focal, spread, lut }, _) => { ramps.extend_from_slice(&lut[..]); let m = inv.m; - (RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) + (RADIAL, [[spread_code(*spread), *focal, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) } // The oracle's sample of a bitmap (crates/render/src/paint.rs › sample). (Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => { @@ -306,9 +330,12 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_ None => return Err(NeedsFull::Bitmaps), }; let m = inv.m; - let (k, alpha, tint, keep) = colour_effect(fx); + // The colour transform (ADR 0056) rides in the ramp table: multiplies, then + // offsets, sanitized as the oracle applies them. + let fx = fx.sanitized(); + ramps.extend_from_slice(&[fx.mul, fx.add]); // Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing). - (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]]) + (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], 0.0, 0.0], [0.0; 4]]) } } // `prepare_scene` never hands these over; draw nothing rather than guess. @@ -441,28 +468,6 @@ fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> List Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work } } -/// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as -/// [`anicraft_doc::ColorEffect::apply`] then `premultiply`'s sanitizing: `(tint amount, alpha, -/// tint, kept channels)`. Each straight channel `c` becomes `c + (tint − c)·k`, alpha `a·alpha`, -/// clamped to `0..=1`. A NaN the oracle would carry into a channel (and its sanitizing turn -/// into 0) is a channel left out of `kept` (bit per channel, red first) instead. -fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) { - let k = fx.tint_amount.clamp(0.0, 1.0); - let alpha = fx.alpha.clamp(0.0, 1.0); - let t = [fx.tint.r, fx.tint.g, fx.tint.b]; - let mut keep = 0u32; - let mut tint = [0.0f32; 3]; - for (i, (&v, out)) in t.iter().zip(tint.iter_mut()).enumerate() { - if v.is_finite() && k.is_finite() { - keep |= 1 << i; - *out = v; - } - } - // A NaN opacity makes every channel 0 (premultiplied by a sanitized alpha of 0). - let alpha = if alpha.is_finite() { alpha } else { 0.0 }; - (if k.is_finite() { k } else { 0.0 }, alpha, tint, keep) -} - /// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group /// entries they need. fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], t: &Tables) -> RowOut { @@ -550,7 +555,8 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } out.push([MASK_RESET, 0, 0, 0]); for &l in chain { - out.push([LEVEL_BEGIN, 0, 0, 0]); + let mode = t.scene.clips.get(l as usize).map_or(0, |c| mask_code(c.mode)); + out.push([LEVEL_BEGIN, mode, 0, 0]); out.extend_from_slice(level(l)); out.push([LEVEL_END, 0, 0, 0]); } @@ -969,3 +975,12 @@ fn avg_clamp(u0: f32, u1: f32) -> f32 { pub(crate) fn solid_of(b: &Binned, op: usize) -> anicraft_render::paint::Premul { b.paints.get(PAINT_VEC4S * op).copied().unwrap_or([0.0; 4]) } + +/// How `fine.wgsl` reads a gradient's spread. +fn spread_code(s: anicraft_doc::Spread) -> f32 { + match s { + anicraft_doc::Spread::Pad => 0.0, + anicraft_doc::Spread::Reflect => 1.0, + anicraft_doc::Spread::Repeat => 2.0, + } +} diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 374e5b20..d57b638c 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -10,7 +10,8 @@ // pixel centre to its nearest segment (crates/render/src/hairline.rs). // // Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band -// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels +// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage (a soft +// mask's, ADR 0070, composites its paint and gives its opacity or luminance), levels // multiply into the clip coverage that clipped fills are scaled by; a group pushes the colour // so far and continues on transparent, and its close blends it into the colour below at the // group's alpha, in its blend mode (the W3C separable formulas, as the oracle's `blend`). @@ -156,21 +157,26 @@ fn finite(v: f32) -> bool { return (bitcast(v) & 0x7f800000u) != 0x7f800000u; } +// Rust's `rem_euclid` for i32 and `n` >= 1, without `%` on a negative operand: naga writes +// WGSL's `%` as GLSL's, which leaves negative operands undefined, so on the GL backend +// (llvmpipe in the FreeBSD VM) the texel left of or above a repeating bitmap's edge, -1, came +// out wrong. The unsigned remainder is defined everywhere. +fn wrap(i: i32, n: i32) -> i32 { + let r = i32(u32(abs(i)) % u32(n)); + return select(r, select(n - r, 0, r == 0), i < 0); +} + // One bitmap tap at integer (x, y) (wrapped when repeating, then clamped to the edges as // `Pixels::at` does), through the colour effect, premultiplied. -fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, fx: vec4, tint: vec4) -> vec4 { +// The colour transform (ColorTransform::apply): each straight channel `c·mul + add`, clamped. +fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, mul: vec4, add: vec4) -> vec4 { var q = vec2(x, y); if repeat { - q = ((q % size) + size) % size; + q = vec2(wrap(q.x, size.x), wrap(q.y, size.y)); } q = clamp(q, vec2(0), size - vec2(1)); - let c = texel(slot, q); - let keep = bitcast(tint.w); - let k = fx.z; - var rgb = clamp(c.rgb + (tint.rgb - c.rgb) * k, vec3(0.0), vec3(1.0)); - rgb = select(vec3(0.0), rgb, vec3((keep & 1u) != 0u, (keep & 2u) != 0u, (keep & 4u) != 0u)); - let a = clamp(c.a * fx.w, 0.0, 1.0); - return vec4(rgb * a, a); + let c = clamp(texel(slot, q) * mul + add, vec4(0.0), vec4(1.0)); + return vec4(c.rgb * c.a, c.a); } // Rust's `rem_euclid` for f32. @@ -181,11 +187,12 @@ fn rem_euclid(u: f32, n: f32) -> f32 { // The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the // pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1). -fn bitmap(base: u32, p: vec2) -> vec4 { +fn bitmap(base: u32, ramp: u32, p: vec2) -> vec4 { let h0 = paints[base]; let m = paints[base + 1u]; let n = paints[base + 2u]; - let tint = paints[base + 3u]; + let mul = paints[ramp]; + let add = paints[ramp + 1u]; let slot = bitcast(h0.x); let flags = bitcast(h0.y); let repeat = (flags & 1u) != 0u; @@ -205,7 +212,7 @@ fn bitmap(base: u32, p: vec2) -> vec4 { return vec4(0.0); } if nearest { - return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint); + return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, mul, add); } let fx_ = u - 0.5; let fy_ = v - 0.5; @@ -215,10 +222,10 @@ fn bitmap(base: u32, p: vec2) -> vec4 { let ty = fy_ - y0; let xi = i32(x0); let yi = i32(y0); - let a = tap(slot, xi, yi, size, repeat, n, tint); - let b = tap(slot, xi + 1, yi, size, repeat, n, tint); - let c = tap(slot, xi, yi + 1, size, repeat, n, tint); - let d = tap(slot, xi + 1, yi + 1, size, repeat, n, tint); + let a = tap(slot, xi, yi, size, repeat, mul, add); + let b = tap(slot, xi + 1, yi, size, repeat, mul, add); + let c = tap(slot, xi, yi + 1, size, repeat, mul, add); + let d = tap(slot, xi + 1, yi + 1, size, repeat, mul, add); let top = a + (b - a) * tx; let bottom = c + (d - c) * tx; return top + (bottom - top) * ty; @@ -245,7 +252,7 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2, x: u32, y: u32) -> vec4, x: u32, y: u32) -> vec4(m.x * p.x + m.z * p.y + n.x, m.y * p.x + m.w * p.y + n.y); + // Spread and focal point (crates/render/src/paint.rs › Spread::apply, focal_t). + let o = paints[base]; var t: f32; if kind == 1u { t = dot(q - n.zw, g.xy); } else { - t = length(q - n.zw) * g.z; + let u = (q - n.zw) * g.z; + let f = o.y; + if f == 0.0 { + t = length(u); + } else { + let d = vec2(u.x - f, u.y); + let a = 1.0 - f * f; + let fd = f * d.x; + t = (fd + sqrt(max(fd * fd + a * dot(d, d), 0.0))) / a; + } + } + let spread = u32(o.x + 0.5); + if spread == 2u { + t = t - floor(t); + if t >= 1.0 { + t = 0.0; + } + } else if spread == 1u { + let m = t - 2.0 * floor(t * 0.5); + if m > 1.0 { + t = 2.0 - m; + } else { + t = m; + } } t = clamp(t, 0.0, 1.0); let i = u32(t * 255.0 + 0.5) & 255u; @@ -353,6 +385,10 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { var depth = 0u; var mask = 1.0; var level = 0.0; + // A soft mask's level (ADR 0070): its mode (0 coverage, 1 alpha, 2 luminance) and its + // artwork's colour so far. + var level_mode = 0u; + var level_colour = vec4(0.0); let start = index[tile * 2u]; let count = index[tile * 2u + 1u]; for (var i = 0u; i < count; i++) { @@ -374,8 +410,20 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } } case MASK_RESET: { mask = 1.0; } - case LEVEL_BEGIN: { level = 0.0; } - case LEVEL_END: { mask *= level; } + case LEVEL_BEGIN: { + level = 0.0; + level_mode = index[e + 1u]; + level_colour = vec4(0.0); + } + case LEVEL_END: { + // The oracle's MaskMode::reveal: opacity, or luminance (sRGB coefficients). + if level_mode == 1u { + level = level_colour.a; + } else if level_mode == 2u { + level = dot(level_colour.rgb, vec3(0.2125, 0.7154, 0.0721)); + } + mask *= clamp(level, 0.0, 1.0); + } default: {} } continue; @@ -409,6 +457,14 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } let flags = index[h + 3u]; if (flags & ART) != 0u { + if level_mode != 0u { + // Soft mask artwork composites as drawn (the oracle's `composite`). + if cov > 1e-4 { + let s = shade(op, index[h], index[h + 2u], centre, x, y); + level_colour = s * cov + level_colour * (1.0 - s.a * cov); + } + continue; + } let k = clamp(cov, 0.0, 1.0); level = level + k - level * k; continue; diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index bb8aa9ad..c1d0d1bb 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -426,7 +426,7 @@ impl GpuRenderer { /// symbol within the parity target. Catches drivers that build the pipelines but compute /// garbage. fn self_test(&self) -> Result<(), GpuError> { - use anicraft_doc::{ColorEffect, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; + use anicraft_doc::{ColorTransform, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; use anicraft_geom::{Affine, FillRule, Path}; let item = |path: Path, fill: Paint| DisplayItem { path: Arc::new(path), @@ -434,7 +434,7 @@ impl GpuRenderer { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -444,6 +444,7 @@ impl GpuRenderer { group: None, image: None, smooth: true, + warp: None, }; let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c)); let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) }); @@ -452,7 +453,7 @@ impl GpuRenderer { blurred.group = Some(0); let filters = Arc::from(vec![Filter::Blur { blur_x: 3.0, blur_y: 2.0, quality: 2 }, Filter::AdjustColor { brightness: 10.0, contrast: 0.0, saturation: -50.0, hue: 30.0 }]); let groups = vec![Group { parent: None, alpha: 1.0, blend: anicraft_doc::BlendMode::Normal, filters, clip: None }]; - let dl = DisplayList { items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) }; let (oracle, _) = anicraft_render::render(&dl, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; let oracle = oracle.to_premul_rgba8(); @@ -473,7 +474,7 @@ impl GpuRenderer { check("through a texture", &self.read_texture(&t)?)?; // Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that // comes back wrong, only the binning stays on the CPU here. - let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; + let plain = DisplayList { clip_modes: Vec::new(), items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) { Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 214cd49c..ffccfec0 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of}; -use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample}; +use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, MaskMode, Paint, Rgba, Stroke, sample}; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_render::{paint::Premul, render}; use std::sync::OnceLock; @@ -22,7 +22,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -32,11 +32,12 @@ fn item(path: Path, fill: Paint) -> DisplayItem { group: None, image: None, smooth: true, + warp: None, } } fn list(items: Vec) -> DisplayList { - DisplayList { items, ..Default::default() } + DisplayList { clip_modes: Vec::new(), items, ..Default::default() } } fn view(w: u32, h: u32, bg: Option) -> View { @@ -89,10 +90,30 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { star.fill_rule = FillRule::EvenOdd; out.push(("star", list(vec![star]), view(80, 80, Some(Rgba::WHITE)))); // Gradients under rotation and scale. - let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]) }); + let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]))); lin.transform = Affine::translate(70.0, 10.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.2, 0.8)); - let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::Radial { center: Vec2::new(60.0, 90.0), radius: 50.0, stops: stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]) }); + let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::radial(Vec2::new(60.0, 90.0), 50.0, stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]))); out.push(("gradients", list(vec![lin, rad]), view(180, 130, Some(Rgba::new(0.9, 0.9, 0.85, 1.0))))); + // Gradient options (ADR 0074): reflect and repeat, linear light, a focal point on a turned + // ellipse that repeats. + let three = stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]); + let mut refl = Paint::linear(Vec2::new(20.0, 0.0), Vec2::new(50.0, 0.0), three.clone()); + if let Paint::Linear { spread, linear_rgb, .. } = &mut refl { + *spread = anicraft_doc::Spread::Reflect; + *linear_rgb = true; + } + let mut rep = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(14.0, 9.0), three.clone()); + if let Paint::Linear { spread, .. } = &mut rep { + *spread = anicraft_doc::Spread::Repeat; + } + let mut foc = Paint::radial(Vec2::ZERO, 1.0, three).with_frame(&Affine::translate(140.0, 60.0).mul(&Affine::rotate(0.6)).mul(&Affine::scale(40.0, 20.0)), None); + if let Paint::Radial { focal, spread, .. } = &mut foc { + *focal = 0.6; + *spread = anicraft_doc::Spread::Repeat; + } + let mut rep_item = item(Path::rect(0.0, 60.0, 90.0, 50.0), rep); + rep_item.transform = Affine::translate(5.0, 0.0); + out.push(("gradient options", list(vec![item(Path::rect(0.0, 0.0, 90.0, 55.0), refl), rep_item, item(Path::ellipse(140.0, 60.0, 60.0, 50.0), foc)]), view(210, 120, Some(Rgba::WHITE)))); // 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; @@ -125,7 +146,7 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { 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 }; + huge.color = ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::hex(0x4cd07d), 0.7)); out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE)))); out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE)))); out.extend(composited_scenes()); @@ -166,10 +187,11 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let red = Rgba::new(0.9, 0.1, 0.1, 1.0); let blue = Rgba::new(0.1, 0.2, 0.9, 0.6); let green = Rgba::new(0.2, 0.7, 0.3, 0.8); - let grad = || Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(120.0, 40.0), stops: stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]) }; + let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)])); let mut out = Vec::new(); // A mask: a gradient seen through a circle, an unclipped shape over it, and one under it. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))], clip_parents: vec![None], groups: Vec::new(), @@ -191,10 +213,11 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { } let mut items = stripes; items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]); - out.push(("nested masks", DisplayList { items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); + out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); // Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles // and the render bands; a top-level shape between two groups. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0), in_group(item(Path::ellipse(55.0, 40.0, 35.0, 30.0), grad()), 0), @@ -221,9 +244,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g)); items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g)); } - out.push(("blend modes", DisplayList { items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); + out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); // Masks inside groups and groups inside masks, with a blend mode, on transparent. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0), in_group(item(Path::ellipse(70.0, 40.0, 30.0, 30.0), Paint::Solid(blue)), 0), @@ -239,6 +263,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { // Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides // what it clips), a group whose parent is later (top-level), a clip index past the list. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0), mask(Path::rect(0.0, 0.0, 30.0, 30.0), 0), @@ -250,6 +275,39 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { groups: vec![group(Some(1), 0.5, BlendMode::Normal), group(Some(1), 0.5, BlendMode::Difference)], }; out.push(("malformed links", dl, view(50, 50, Some(Rgba::WHITE)))); + // Soft masks (ADR 0070): an alpha gradient fading a shape out, a luminance mask with a + // stroke and overlapping faded art, and a soft mask inside a coverage one. + let fade = Paint::linear(Vec2::new(10.0, 0.0), Vec2::new(110.0, 0.0), stops(&[(0.0, Rgba::new(1.0, 1.0, 1.0, 0.0)), (1.0, Rgba::new(0.2, 0.9, 0.4, 1.0))])); + let soft_art = |path: Path, paint: Paint, clip: u32| { + let mut m = item(path, paint); + m.masks = Some(clip); + m + }; + let mut ring = soft_art(Path::ellipse(60.0, 50.0, 30.0, 26.0), Paint::Solid(Rgba::new(0.5, 0.5, 0.5, 0.7)), 1); + ring.stroke = Some(Stroke::new(Rgba::WHITE, 6.0)); + let mut faded = soft_art(Path::rect(50.0, 10.0, 60.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.2, 0.1, 1.0)), 1); + faded.color = ColorTransform::alpha(0.6); + let mut inner = soft_art(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(1.0, 1.0, 1.0, 0.5)), 3); + inner.clip = Some(2); + let mut dl = DisplayList { + items: vec![ + item(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(0.95, 0.9, 0.8, 1.0))), + clipped(item(Path::rect(0.0, 0.0, 120.0, 50.0), grad()), 0), + soft_art(Path::rect(10.0, 0.0, 100.0, 60.0), fade, 0), + clipped(item(Path::rect(0.0, 30.0, 120.0, 70.0), Paint::Solid(red)), 1), + ring, + faded, + clipped(item(Path::star(60.0, 60.0, 40.0, 15.0, 5), Paint::Solid(blue)), 3), + mask(Path::rect(20.0, 40.0, 50.0, 60.0), 2), + inner, + ], + clip_parents: vec![None, None, None, Some(2)], + ..Default::default() + }; + dl.set_clip_mode(0, MaskMode::Alpha); + dl.set_clip_mode(1, MaskMode::Luminance); + dl.set_clip_mode(3, MaskMode::Alpha); + out.push(("soft masks", dl, view(120, 100, Some(Rgba::WHITE)))); out } @@ -266,6 +324,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let mut c = bg; let mut stack: Vec = Vec::new(); let (mut mask, mut level) = (1.0f32, 0.0f32); + let (mut level_mode, mut level_colour) = (0u32, [0.0f32; 4]); for i in 0..count { let e = b.entries_at as usize + (start + i) * 4; let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); @@ -287,10 +346,13 @@ fn emulate(b: &Binned, v: &View) -> Vec { } bn::LEVEL_BEGIN => { level = 0.0; + level_mode = b.index[e + 1]; + level_colour = [0.0; 4]; continue; } bn::LEVEL_END => { - mask *= level; + let mode = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance][level_mode as usize]; + mask *= if mode.is_soft() { mode.reveal(level_colour) } else { level }; continue; } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), @@ -298,7 +360,37 @@ fn emulate(b: &Binned, v: &View) -> Vec { let hd = op * 4; let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly); let flags = b.op_heads[hd + 3]; + let shade = || match b.op_heads[hd] { + 0 => solid_of(b, op), + kind => { + let base = op * PAINT_VEC4S; + let (m, nn, g) = (b.paints[base + 1], b.paints[base + 2], b.paints[base + 3]); + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]); + let d = q - Vec2::new(nn[2], nn[3]); + // As fine.wgsl: spread code and focal point in the first vec4. + let o = b.paints[base]; + let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { anicraft_render::paint::focal_t(d * g[2], o[1]) }; + let t = match o[0] as u32 { + 1 => anicraft_doc::Spread::Reflect.apply(t), + 2 => anicraft_doc::Spread::Repeat.apply(t), + _ => t, + }; + let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; + b.paints[b.op_heads[hd + 2] as usize + i] + } + }; if flags & bn::ART != 0 { + if level_mode != 0 { + if cov > 1e-4 { + let s = shade(); + let sa = s[3] * cov; + for k in 0..4 { + level_colour[k] = s[k] * cov + level_colour[k] * (1.0 - sa); + } + } + continue; + } let k = cov.clamp(0.0, 1.0); level = level + k - level * k; continue; @@ -309,19 +401,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { if cov <= 1e-4 { continue; } - let s = match b.op_heads[hd] { - 0 => solid_of(b, op), - kind => { - let base = op * PAINT_VEC4S; - let (m, nn, g) = (b.paints[base + 1], b.paints[base + 2], b.paints[base + 3]); - let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); - let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]); - let d = q - Vec2::new(nn[2], nn[3]); - let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] }; - let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; - b.paints[b.op_heads[hd + 2] as usize + i] - } - }; + let s = shade(); let sa = s[3] * cov; for k in 0..4 { c[k] = s[k] * cov + c[k] * (1.0 - sa); @@ -448,7 +528,7 @@ fn composited_sample() -> anicraft_doc::Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { let e = Arc::make_mut(e); - e.color.alpha = if i == 0 { 0.6 } else { 0.5 }; + e.color = e.color.with_alpha(if i == 0 { 0.6 } else { 0.5 }); if let ElementKind::Symbol { blend, .. } = &mut e.kind && i == 0 { @@ -465,6 +545,27 @@ fn composited_sample() -> anicraft_doc::Document { doc } +/// A rounded panel with 9-slice guides, placed stretched, scaled up and turned. +fn nine_slice_sample() -> anicraft_doc::Document { + use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; + let mut d = anicraft_doc::Document { stage: anicraft_doc::Stage { width: 320, height: 200, ..Default::default() }, ..Default::default() }; + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 60.0, 30.0, 8.0), Paint::Solid(Rgba::hex(0x2a9d8f))); + shape.stroke = Some(Stroke::new(Rgba::hex(0x264653), 2.0)); + let el = |id, transform, kind| std::sync::Arc::new(Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind }); + let mut k = Keyframe::new(0, 1); + k.elements.push(el(2, Affine::IDENTITY, ElementKind::Shape(shape))); + let mut l = Layer::new(LayerId(3), "art"); + l.keyframes = vec![std::sync::Arc::new(k)]; + d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); + let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }); + let mut k = Keyframe::new(0, 1); + k.elements.push(inst(5, Affine::translate(10.0, 10.0).mul(&Affine::scale(4.5, 1.2)))); + k.elements.push(inst(6, Affine::translate(30.0, 70.0).mul(&Affine::scale(2.0, 3.5)))); + k.elements.push(inst(7, Affine::translate(220.0, 90.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(1.5, 2.5)))); + std::sync::Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![std::sync::Arc::new(k)]; + d +} + #[test] fn binned_coverage_matches_the_oracle_on_the_cpu() { let mut all = scenes(); @@ -480,6 +581,10 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { for (f, s) in [(0u32, 0.4f32), (30, 0.6)] { all.push(("composited sample", anicraft_doc::evaluate(&comp, f), View::stage(&comp, s))); } + // A 9-sliced instance (ADR 0055) reaches the stage through evaluation: cut outlines, strokes + // at their own width. + let nine = nine_slice_sample(); + all.push(("9-slice", anicraft_doc::evaluate(&nine, 0), View::stage(&nine, 0.7))); for (name, dl, v) in all { let (scene, _) = prepare_scene(&dl, &v).unwrap(); let b = binning::bin(&scene, v.width, v.height).unwrap(); @@ -544,6 +649,7 @@ fn binning_shapes_the_scene_into_tiles() { // A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In // the middle tile the mask has no artwork, so the clipped fill is left out there. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0), clipped(item(Path::rect(0.0, 0.0, 40.0, 16.0), Paint::Solid(Rgba::BLACK)), 0), @@ -572,6 +678,7 @@ fn binning_shapes_the_scene_into_tiles() { #[test] fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let deep = |n: usize| DisplayList { + clip_modes: Vec::new(), items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)], clip_parents: Vec::new(), groups: (0..n).map(|i| group(i.checked_sub(1).map(|p| p as u32), 0.9, BlendMode::Normal)).collect(), @@ -583,7 +690,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let masks = |n: usize| { let mut items: Vec = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect(); items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)); - DisplayList { items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } + DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } }; assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok()); assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips)); @@ -623,6 +730,39 @@ fn degenerate_geometry_bins_without_trouble() { // ----- the real GPU ---------------------------------------------------------------------------- +/// The shaders, as `pipelines` and the stage build them. +const SHADERS: [(&str, &str); 4] = [ + ("fine.wgsl", include_str!("fine.wgsl")), + ("bin.wgsl", include_str!("bin.wgsl")), + ("scan.wgsl", include_str!("scan.wgsl")), + ("filters.wgsl", include_str!("filters.wgsl")), +]; + +#[test] +fn shaders_take_no_signed_remainder() { + // naga writes WGSL's `%` on integers as GLSL's, which is undefined when an operand is + // negative: on the GL backend (llvmpipe in the FreeBSD VM) a repeating bitmap's wrap, + // `((q % size) + size) % size` at q = -1, picked the wrong texel at its edges (bitmap + // repeated: max 79). Unsigned remainders and float ones (written as `a - b * trunc(a / b)`) + // are defined on every backend. + for (name, src) in SHADERS { + let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()) + .validate(&module) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); + let functions = module.functions.iter().map(|(h, f)| (f, &info[h])); + let entries = module.entry_points.iter().enumerate().map(|(i, e)| (&e.function, info.get_entry_point(i))); + for (f, fi) in functions.chain(entries) { + for (h, e) in f.expressions.iter() { + if let naga::Expression::Binary { op: naga::BinaryOperator::Modulo, left, .. } = *e { + let kind = fi[left].ty.inner_with(&module.types).scalar_kind(); + assert_ne!(kind, Some(naga::ScalarKind::Sint), "{name}: `%` on a signed integer in {:?} ({h:?})", f.name); + } + } + } + } +} + /// One device for all tests: the graphics card, or else the software adapter (CI runners have /// lavapipe or WARP); `None` (with the reasons printed) when there is neither. /// `ANICRAFT_TEST_GPU=software` tests on the software adapter even where there is a card. @@ -720,8 +860,8 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { }) .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); - it.color.alpha = 0.5; - DisplayList { items: vec![it], clip_parents: Vec::new(), groups } + it.color = ColorTransform::alpha(0.5); + DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters)))); @@ -782,20 +922,24 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { ("bitmap magnified, mirrored", list(vec![bitmap_item(Path::rect(0.0, 0.0, 64.0, 48.0), &c, false, Affine { m: [-1.7, 0.0, 0.0, 1.6, 66.0, -1.3] })]), view(64, 48, white)), ("one-pixel bitmap", list(vec![bitmap_item(Path::rect(5.5, 5.5, 20.0, 20.0), &b, true, Affine::scale(7.0, 7.0))]), view(32, 32, white)), ]; - // Colour effects: tint and alpha per tap, and a NaN tint (sanitized to 0 as the oracle does). + // Colour effects: tint and alpha per tap, and a NaN multiplier (a channel of 0, as the oracle + // draws it). let mut tinted = bitmap_item(Path::rect(0.0, 0.0, 60.0, 40.0), &c, true, Affine::scale(0.7, 0.9)); - tinted.color = ColorEffect { alpha: 0.6, tint: Rgba::new(0.2, 0.9, 0.1, 1.0), tint_amount: 0.4 }; + tinted.color = ColorTransform::alpha(0.6).concat(&ColorTransform::tint(Rgba::new(0.2, 0.9, 0.1, 1.0), 0.4)); let mut nan = bitmap_item(Path::rect(30.0, 10.0, 30.0, 30.0), &a, false, Affine::scale(2.0, 2.0)); - nan.color = ColorEffect { alpha: 1.0, tint: Rgba::new(f32::NAN, 0.5, 0.5, 1.0), tint_amount: 0.3 }; - out.push(("bitmap colour effects", list(vec![tinted, nan]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); + nan.color = ColorTransform { mul: [f32::NAN, 0.7, 0.7, 1.0], add: [0.0, 0.15, 0.15, 0.0] }; + // Advanced (ADR 0056): a negative multiplier, offsets and an alpha offset. + let mut advanced = bitmap_item(Path::rect(4.0, 20.0, 40.0, 26.0), &a, true, Affine::scale(1.3, 1.1)); + advanced.color = ColorTransform { mul: [-1.0, 0.5, 0.2, 0.6], add: [1.0, 0.1, 0.4, 0.2] }; + out.push(("bitmap colour effects", list(vec![tinted, nan, advanced]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); // A short (malformed) buffer: transparent past its end; an empty image draws nothing. let short = Arc::new(anicraft_doc::Pixels { width: 4, height: 4, rgba: vec![200; 20] }); let empty = Arc::new(anicraft_doc::Pixels { width: 0, height: 3, rgba: Vec::new() }); out.push(("malformed bitmaps", list(vec![bitmap_item(Path::rect(0.0, 0.0, 30.0, 30.0), &short, false, Affine::scale(7.0, 7.0)), bitmap_item(Path::rect(10.0, 0.0, 10.0, 30.0), &empty, true, Affine::IDENTITY)]), view(32, 32, white))); // Inside a mask and a faded group, over a gradient. - let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(80.0, 60.0), stops: stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]) }); + let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]))); let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); - let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); @@ -803,6 +947,16 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0)); hard_tiled.smooth = false; out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white))); + // Warped (ADR 0079): bent by three pins, folded a little, faded; the oracle's prepared image. + use anicraft_doc::warp::{Pin, PinId, Warp}; + let pin = |id: u64, rest: (f32, f32), at: (f32, f32)| Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) }; + let mut warp = Warp::new(Arc::new(Path::rect(0.0, 0.0, 40.0, 30.0)), 8); + warp.pins = vec![pin(1, (2.0, 15.0), (6.0, 20.0)), pin(2, (20.0, 15.0), (24.0, 14.0)), pin(3, (38.0, 15.0), (52.0, 40.0))]; + let mut bent = bitmap_item(warp.outline().as_ref().clone(), &c, false, Affine::IDENTITY); + bent.warp = warp.mesh().map(Arc::new); + bent.transform = Affine::scale(1.4, 1.4); + bent.color = ColorTransform::alpha(0.8); + out.push(("warped bitmap", list(vec![bent]), view(90, 72, white))); out } @@ -873,12 +1027,12 @@ fn symbol_items(g: u32) -> Vec { #[test] fn gpu_matches_the_oracle_on_every_filter() { let Some(g) = gpu() else { return }; - let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(70.0, 0.0), stops: stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))]) }); + let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(70.0, 0.0), stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))]))); let mut worst: f64 = 0.0; for (name, f) in filters_to_test() { let mut items = vec![backdrop.clone()]; items.extend(symbol_items(0)); - let dl = DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; + let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; // At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface. for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] { let d = assert_parity(g, name, &dl, &v); @@ -903,7 +1057,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { (grp.alpha, grp.blend) = (0.7, BlendMode::Multiply); let mut items = vec![bg.clone()]; items.extend(symbol_items(0)); - scenes.push(("filters in a row, faded and multiplied", DisplayList { items, clip_parents: Vec::new(), groups: vec![grp] })); + scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); // A filtered symbol inside a filtered symbol, inside a faded one. let mut outer = filtered_group(vec![shadow.clone()]); outer.parent = Some(0); @@ -911,22 +1065,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { inner.parent = Some(1); let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)]; items.extend(symbol_items(2)); - scenes.push(("nested filtered symbols", DisplayList { items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); + scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); // Masked from outside (after filtering) and inside (before). let mut clipped_grp = filtered_group(vec![glow.clone()]); clipped_grp.clip = Some(0); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0)); - scenes.push(("masked after filtering", DisplayList { items, clip_parents: vec![None], groups: vec![clipped_grp] })); + scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0)); - scenes.push(("masked inside the symbol", DisplayList { items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); + scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); // A bitmap inside a filtered symbol. let px = pixels(9, 7, 4); let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)]; - scenes.push(("filtered bitmap", DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); + scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); for (name, dl) in scenes { for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] { let d = assert_parity(g, name, &dl, &v); @@ -957,7 +1111,7 @@ fn filtered_sample() -> anicraft_doc::Document { } } } - let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero }; + let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero, warp: None }; let sky = anicraft_doc::Element { id: ElementId(9_100), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }; let frames = doc.frame_count(); let mut k = anicraft_doc::Keyframe::new(0, frames); diff --git a/crates/guide/Cargo.toml b/crates/guide/Cargo.toml new file mode 100644 index 00000000..c7b99d53 --- /dev/null +++ b/crates/guide/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "anicraft-guide" +description = "AniCraft L0: the user guide (docs/guide) as a static HTML book, with its link checks" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +# CommonMark with GFM tables (MIT; ADR 0069). Default features off: no command-line binary. +pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } + +[lints] +workspace = true diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs new file mode 100644 index 00000000..f525299f --- /dev/null +++ b/crates/guide/src/lib.rs @@ -0,0 +1,389 @@ +//! AniCraft's user guide as a book (layer L0; ADR 0069). +//! +//! The chapters are Markdown in `docs/guide/`, readable on GitHub as they are. This crate builds +//! them into the bundled book: every page and picture is compiled in, so Help › User Guide works +//! offline, and [`site`] turns them into static HTML pages with one stylesheet, a chapter list +//! and previous / next links. Links between chapters are written to `.md` files and become +//! `.html` links; headings get GitHub's anchor ids, so `timeline.md#onion-skin` works in both +//! places. +//! +//! [`check`] is the book's proof-reader: every internal link and picture resolves, every anchor +//! names a heading, every page is reachable from the contents page and has one title, nothing +//! links outside the book, and there is no raw HTML. Its test keeps the committed guide honest; +//! the generated command and shortcut references are checked for freshness by the app's own +//! tests (`src/guide_reference_tests.rs`), which know the menus and keys. +//! +//! Rendering escapes raw HTML in the Markdown instead of passing it through, so a page can never +//! carry markup or script of its own. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::path::Path; + +/// One chapter: its file under `docs/guide/` and its Markdown. +#[derive(Clone, Copy, Debug)] +pub struct Page { + pub file: &'static str, + pub markdown: &'static str, +} + +macro_rules! page { + ($f:literal) => { + Page { file: $f, markdown: include_str!(concat!("../../../docs/guide/", $f)) } + }; +} + +macro_rules! image { + ($f:literal) => { + ($f, include_bytes!(concat!("../../../docs/guide/", $f)).as_slice()) + }; +} + +/// The book in reading order. The contents page comes first; the generated references last. +pub const PAGES: &[Page] = &[ + page!("index.md"), + page!("getting-started.md"), + page!("workspace.md"), + page!("drawing.md"), + page!("symbols-and-library.md"), + page!("timeline.md"), + page!("tweens.md"), + page!("masks-guides-camera-bones.md"), + page!("text.md"), + page!("images-and-sound.md"), + page!("interactivity.md"), + page!("exporting-and-publish.md"), + page!("opening-animate-files.md"), + page!("preferences-shortcuts-accessibility.md"), + page!("plugins.md"), + page!("working-headless.md"), + page!("troubleshooting-and-faq.md"), + page!("coming-from-animate.md"), + page!("reference/commands.md"), + page!("reference/shortcuts.md"), +]; + +/// The book's pictures (screenshots from `scripts/guide-shots.sh`), by their path in the book. +pub const IMAGES: &[(&str, &[u8])] = &[ + image!("images/workspace.png"), + image!("images/start-screen.png"), + image!("images/library.png"), + image!("images/onion-skin.png"), + image!("images/motion-editor.png"), + image!("images/test-movie.png"), + image!("images/publish-settings.png"), + image!("images/preferences.png"), +]; + +const STYLE: &str = include_str!("style.css"); +const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// The stylesheet's path in the built book. +pub const STYLESHEET: &str = "style.css"; + +/// One file of the built book: its path (with `/`) and contents. +#[derive(Clone, Debug, PartialEq)] +pub struct SiteFile { + pub path: String, + pub bytes: Vec, +} + +/// The page a chapter becomes: `reference/commands.md` → `reference/commands.html`. +pub fn html_path(md: &str) -> String { + match md.strip_suffix(".md") { + Some(stem) => format!("{stem}.html"), + None => md.to_string(), + } +} + +/// The parser options the book is written for: CommonMark with GFM tables and strikethrough. +fn options() -> Options { + Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH +} + +/// A link target inside the book (not `https:`, `mailto:` or another scheme). +fn is_relative(url: &str) -> bool { + !url.contains(':') && !url.starts_with('/') && !url.starts_with('\\') +} + +/// `foo.md#bar` → `foo.html#bar`; other links stay as they are. +fn rewrite_link(url: &str) -> String { + if !is_relative(url) { + return url.to_string(); + } + match url.split_once('#') { + Some((path, anchor)) if path.ends_with(".md") => format!("{}#{anchor}", html_path(path)), + None if url.ends_with(".md") => html_path(url), + _ => url.to_string(), + } +} + +/// GitHub's heading anchor: lower case, spaces to `-`, letters, digits, `-` and `_` kept. +pub fn slug(heading: &str) -> String { + heading + .trim() + .chars() + .flat_map(char::to_lowercase) + .filter_map(|c| match c { + ' ' => Some('-'), + c if c.is_alphanumeric() || c == '-' || c == '_' => Some(c), + _ => None, + }) + .collect() +} + +/// A page's events, with heading ids (GitHub's, numbered on repeats), `.md` links pointing at +/// pages, and raw HTML turned into visible text. +fn events(markdown: &str) -> Vec> { + let mut out: Vec = Parser::new_ext(markdown, options()) + .map(|e| match e { + Event::Html(h) | Event::InlineHtml(h) => Event::Text(h), + Event::Start(Tag::Link { link_type, dest_url, title, id }) => Event::Start(Tag::Link { link_type, dest_url: CowStr::from(rewrite_link(&dest_url)), title, id }), + Event::Start(Tag::Image { link_type, dest_url, title, id }) => Event::Start(Tag::Image { link_type, dest_url: CowStr::from(rewrite_link(&dest_url)), title, id }), + other => other, + }) + .collect(); + let mut seen: BTreeMap = BTreeMap::new(); + let mut i = 0; + while i < out.len() { + if let Some(Event::Start(Tag::Heading { .. })) = out.get(i) { + let text = heading_text(out.get(i + 1..).unwrap_or_default()); + let id = unique_slug(&mut seen, &text); + if let Some(Event::Start(Tag::Heading { id: slot, .. })) = out.get_mut(i) { + *slot = Some(CowStr::from(id)); + } + } + i += 1; + } + out +} + +/// The text of a heading whose start event came just before `rest`. +fn heading_text(rest: &[Event]) -> String { + let mut s = String::new(); + for e in rest { + match e { + Event::End(TagEnd::Heading(_)) => break, + Event::Text(t) | Event::Code(t) => s.push_str(t), + _ => {} + } + } + s +} + +fn unique_slug(seen: &mut BTreeMap, text: &str) -> String { + let base = slug(text); + let n = seen.entry(base.clone()).or_insert(0); + let id = if *n == 0 { base } else { format!("{base}-{n}") }; + *n += 1; + id +} + +/// A page's title: its first level-one heading. +pub fn title(markdown: &str) -> String { + let mut parser = Parser::new_ext(markdown, options()); + while let Some(e) = parser.next() { + if let Event::Start(Tag::Heading { level: pulldown_cmark::HeadingLevel::H1, .. }) = e { + let rest: Vec = parser.by_ref().take_while(|e| !matches!(e, Event::End(TagEnd::Heading(_)))).collect(); + return heading_text(&rest); + } + } + String::new() +} + +fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +/// `../` once per folder the page is in, to reach the book's root. +fn root_prefix(file: &str) -> String { + "../".repeat(file.matches('/').count()) +} + +/// A chapter as a complete HTML page, with the chapter list and previous / next links. +pub fn render_page(pages: &[Page], at: usize) -> String { + let Some(page) = pages.get(at) else { return String::new() }; + let root = root_prefix(page.file); + let mut body = String::new(); + pulldown_cmark::html::push_html(&mut body, events(page.markdown).into_iter()); + let title = title(page.markdown); + let mut toc = String::new(); + for (i, p) in pages.iter().enumerate() { + let current = if i == at { " aria-current=\"page\"" } else { "" }; + toc.push_str(&format!("
  • {}
  • \n", html_path(p.file), escape(&self::title(p.markdown)))); + } + let link = |p: Option<&Page>, rel: &str, word: &str| { + p.map_or_else(String::new, |p| format!("{word}: {}", html_path(p.file), escape(&self::title(p.markdown)))) + }; + let prev = link(at.checked_sub(1).and_then(|i| pages.get(i)), "prev", "Previous"); + let next = link(pages.get(at + 1), "next", "Next"); + format!( + "\n\n\n\n\n\ + {t} · AniCraft User Guide\n\n\n\n\ + Skip to the chapter\n\ +
    AniCraft User Guide {VERSION}
    \n\ +
    \n\n\ +
    \n{body}\n
    \n
    \n\ +
    AniCraft {VERSION} · MIT OR Apache-2.0 · AniCraft is not affiliated with or endorsed by Adobe.
    \n\n\n", + t = escape(&title), + ) +} + +/// The whole book: one HTML page per chapter, the stylesheet and the pictures. +pub fn site() -> Vec { + let mut out: Vec = (0..PAGES.len()).filter_map(|i| PAGES.get(i).map(|p| SiteFile { path: html_path(p.file), bytes: render_page(PAGES, i).into_bytes() })).collect(); + out.push(SiteFile { path: STYLESHEET.to_string(), bytes: STYLE.as_bytes().to_vec() }); + out.extend(IMAGES.iter().map(|(path, bytes)| SiteFile { path: (*path).to_string(), bytes: bytes.to_vec() })); + out +} + +/// Writes the book into a folder (made if needed); the number of files written. The paths are +/// the book's own (checked by [`check`]), never input. +pub fn write_site(dir: &Path) -> std::io::Result { + let files = site(); + for f in &files { + let path = f.path.split('/').fold(dir.to_path_buf(), |p, part| p.join(part)); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&path, &f.bytes)?; + } + Ok(files.len()) +} + +/// `rel` (a link written in `from`) as a path from the book's root, or `None` when it climbs +/// out of the book. +fn resolve(from: &str, rel: &str) -> Option { + let mut parts: Vec<&str> = from.split('/').collect(); + parts.pop(); + for part in rel.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop()?; + } + p => parts.push(p), + } + } + Some(parts.join("/")) +} + +/// What a page links to and which anchors it offers. +struct Scan { + links: Vec, + images: Vec, + anchors: BTreeSet, + titles: usize, + raw_html: usize, +} + +fn scan(markdown: &str) -> Scan { + let mut s = Scan { links: Vec::new(), images: Vec::new(), anchors: BTreeSet::new(), titles: 0, raw_html: 0 }; + let raw: Vec = Parser::new_ext(markdown, options()).collect(); + for e in &raw { + match e { + Event::Start(Tag::Link { dest_url, .. }) => s.links.push(dest_url.to_string()), + Event::Start(Tag::Image { dest_url, .. }) => s.images.push(dest_url.to_string()), + Event::Start(Tag::Heading { level: pulldown_cmark::HeadingLevel::H1, .. }) => s.titles += 1, + Event::Html(_) | Event::InlineHtml(_) => s.raw_html += 1, + _ => {} + } + } + for e in events(markdown) { + if let Event::Start(Tag::Heading { id: Some(id), .. }) = e { + s.anchors.insert(id.to_string()); + } + } + s +} + +/// Everything wrong with a book: broken links, pictures or anchors, links out of the book, pages +/// the contents page can't reach, pages without exactly one title, raw HTML and unused +/// pictures. Empty when the book is sound. `pages[0]` is the contents page. +pub fn check(pages: &[Page], images: &[&str]) -> Vec { + let mut problems = Vec::new(); + let scans: BTreeMap<&str, Scan> = pages.iter().map(|p| (p.file, scan(p.markdown))).collect(); + let mut used_images = BTreeSet::new(); + let mut edges: BTreeMap<&str, Vec> = BTreeMap::new(); + for (file, s) in &scans { + if s.titles != 1 { + problems.push(format!("{file}: has {} level-one headings; a page has exactly one, its title", s.titles)); + } + if s.raw_html > 0 { + problems.push(format!("{file}: has raw HTML; the book is plain Markdown")); + } + for url in &s.links { + if !is_relative(url) { + if !url.starts_with("https://") { + problems.push(format!("{file}: link {url} is neither in the book nor https")); + } + continue; + } + let (path, anchor) = url.split_once('#').map_or((url.as_str(), None), |(p, a)| (p, Some(a))); + let target = if path.is_empty() { Some((*file).to_string()) } else { resolve(file, path) }; + let Some(target) = target else { + problems.push(format!("{file}: link {url} leaves the book")); + continue; + }; + match scans.get(target.as_str()) { + Some(t) => { + if let Some(a) = anchor + && !t.anchors.contains(a) + { + problems.push(format!("{file}: link {url}: {target} has no heading #{a}")); + } + edges.entry(file).or_default().push(target); + } + None if images.contains(&target.as_str()) => { + used_images.insert(target); + } + None => problems.push(format!("{file}: link {url}: {target} is not a page of the book")), + } + } + for url in &s.images { + match resolve(file, url).filter(|t| is_relative(url) && images.contains(&t.as_str())) { + Some(t) => { + used_images.insert(t); + } + None => problems.push(format!("{file}: picture {url} is not one of the book's pictures")), + } + } + } + for image in images { + if !used_images.contains(*image) { + problems.push(format!("{image}: no page shows it")); + } + } + // Every page reachable from the contents page. + if let Some(first) = pages.first() { + let mut reached = BTreeSet::from([first.file.to_string()]); + let mut queue = VecDeque::from([first.file.to_string()]); + while let Some(at) = queue.pop_front() { + for next in edges.get(at.as_str()).into_iter().flatten() { + if reached.insert(next.clone()) { + queue.push_back(next.clone()); + } + } + } + for p in pages { + if !reached.contains(p.file) { + problems.push(format!("{}: can't be reached from {}", p.file, first.file)); + } + } + } + problems +} + +#[cfg(test)] +mod tests; diff --git a/crates/guide/src/style.css b/crates/guide/src/style.css new file mode 100644 index 00000000..c6f81595 --- /dev/null +++ b/crates/guide/src/style.css @@ -0,0 +1,59 @@ +/* AniCraft User Guide (ADR 0069). The editor's graphite palette when the system is dark, a + light reading page otherwise; Inter for prose and JetBrains Mono for keys, ids and code, as in + the app (docs/ui-guidelines.md), with the system's fonts when they aren't installed. */ +:root { + --bg: #fbfbfc; --panel: #f1f1f4; --text: #1b1b1f; --muted: #55555e; --line: #d8d8de; + --accent: #2e66f0; --code-bg: #ececf1; + --prose: Inter, "Segoe UI", system-ui, -apple-system, sans-serif; + --mono: "JetBrains Mono", ui-monospace, "Cascadia Mono", Menlo, Consolas, monospace; +} +@media (prefers-color-scheme: dark) { + :root { --bg: #1b1b1f; --panel: #222227; --text: #eeeef0; --muted: #a8a8b2; --line: #34343c; + --accent: #6f97ff; --code-bg: #2a2a31; } +} +* { box-sizing: border-box; } +html { font-size: 16px; } +body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--prose); line-height: 1.6; } +a { color: var(--accent); } +a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.skip { position: absolute; left: -999px; } +.skip:focus { left: 8px; top: 8px; background: var(--panel); padding: 4px 8px; } +header.top { padding: 10px 20px; border-bottom: 1px solid var(--line); background: var(--panel); font-weight: 600; } +header.top a { color: var(--text); text-decoration: none; } +header.top .version { color: var(--muted); font-family: var(--mono); font-weight: 400; font-size: 0.85rem; margin-left: 6px; } +.layout { display: flex; max-width: 1200px; margin: 0 auto; } +nav.toc { flex: 0 0 260px; padding: 16px 12px; border-right: 1px solid var(--line); font-size: 0.92rem; position: sticky; top: 0; align-self: flex-start; max-height: 100vh; overflow-y: auto; } +nav.toc ol { margin: 0; padding-left: 1.4em; } +nav.toc li { margin: 2px 0; } +nav.toc a { color: var(--text); text-decoration: none; } +nav.toc a:hover { text-decoration: underline; } +nav.toc a[aria-current="page"] { color: var(--accent); font-weight: 600; } +main { flex: 1; min-width: 0; padding: 8px 40px 40px; max-width: 860px; } +h1, h2, h3 { line-height: 1.25; } +h1 { font-size: 2rem; margin-top: 0.8em; } +h2 { font-size: 1.4rem; margin-top: 1.8em; padding-bottom: 4px; border-bottom: 1px solid var(--line); } +h3 { font-size: 1.12rem; margin-top: 1.4em; } +code, kbd, pre { font-family: var(--mono); font-size: 0.88em; } +code { background: var(--code-bg); padding: 1px 5px; border-radius: 3px; } +pre { background: var(--code-bg); padding: 12px 14px; overflow-x: auto; border-radius: 4px; } +pre code { background: none; padding: 0; } +table { border-collapse: collapse; margin: 1em 0; display: block; overflow-x: auto; } +th, td { border: 1px solid var(--line); padding: 5px 9px; text-align: left; vertical-align: top; } +th { background: var(--panel); } +img { max-width: 100%; height: auto; border: 1px solid var(--line); border-radius: 4px; } +blockquote { margin: 1em 0; padding: 4px 16px; border-left: 3px solid var(--accent); background: var(--panel); } +nav.pager { display: flex; justify-content: space-between; gap: 16px; margin-top: 3em; padding-top: 12px; border-top: 1px solid var(--line); } +nav.pager a[rel="next"] { margin-left: auto; text-align: right; } +footer { text-align: center; color: var(--muted); font-size: 0.85rem; padding: 20px; border-top: 1px solid var(--line); } +@media (max-width: 800px) { + .layout { display: block; } + nav.toc { position: static; max-height: none; border-right: 0; border-bottom: 1px solid var(--line); } + main { padding: 8px 18px 30px; } +} +@media (forced-colors: active) { + nav.toc a[aria-current="page"] { text-decoration: underline; } +} +@media print { + nav.toc, nav.pager, header.top, .skip { display: none; } + main { max-width: none; } +} diff --git a/crates/guide/src/tests.rs b/crates/guide/src/tests.rs new file mode 100644 index 00000000..3a969a95 --- /dev/null +++ b/crates/guide/src/tests.rs @@ -0,0 +1,116 @@ +use super::*; + +fn guide_dir() -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/guide") +} + +/// Files under `dir` with this extension, as paths from `dir` with `/`. +fn files(dir: &Path, ext: &str, prefix: &str, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("docs/guide exists").flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let path = entry.path(); + if path.is_dir() { + files(&path, ext, &format!("{prefix}{name}/"), out); + } else if name.ends_with(ext) { + out.push(format!("{prefix}{name}")); + } + } +} + +fn image_paths() -> Vec<&'static str> { + IMAGES.iter().map(|(p, _)| *p).collect() +} + +#[test] +fn the_guide_has_no_broken_links_and_every_page_is_reachable() { + let problems = check(PAGES, &image_paths()); + assert!(problems.is_empty(), "the user guide has problems:\n{}", problems.join("\n")); +} + +#[test] +fn every_chapter_and_picture_in_docs_guide_is_in_the_book() { + let mut md = Vec::new(); + files(&guide_dir(), ".md", "", &mut md); + let mut book: Vec = PAGES.iter().map(|p| p.file.to_string()).collect(); + md.sort(); + book.sort(); + assert_eq!(md, book, "docs/guide and PAGES must list the same chapters"); + let mut png = Vec::new(); + files(&guide_dir(), ".png", "", &mut png); + let mut pictures: Vec = image_paths().into_iter().map(str::to_string).collect(); + png.sort(); + pictures.sort(); + assert_eq!(png, pictures, "docs/guide and IMAGES must list the same pictures"); +} + +#[test] +fn pictures_stay_small() { + // Committed screenshots are few and small (scripts/guide-shots.sh shrinks them). + for (path, bytes) in IMAGES { + assert!(bytes.len() <= 300 * 1024, "{path} is {} KB; keep guide pictures under 300 KB", bytes.len() / 1024); + assert!(bytes.starts_with(b"\x89PNG"), "{path} is not a PNG"); + } +} + +#[test] +fn every_page_has_a_title_and_the_site_has_a_page_for_each() { + let site = site(); + for p in PAGES { + assert!(!title(p.markdown).trim().is_empty(), "{} has no title", p.file); + let html = html_path(p.file); + let f = site.iter().find(|f| f.path == html).unwrap_or_else(|| panic!("no {html}")); + let text = String::from_utf8_lossy(&f.bytes); + assert!(text.contains("