Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

klad 0.1.0

Indicode BVdcf6ec2c1c6c
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000..7617754
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,20 @@
+---
+name: Something is wrong
+about: A crash, a wrong render, an edit that does not do what it says
+labels: bug
+---
+
+**What happened**
+
+**What you expected**
+
+**How to make it happen again**
+The steps in the editor, or the `klad` commands. A zipped `.draw` folder that shows it helps most.
+
+**Version and machine**
+- `klad --version`:
+- OS and version:
+- Pen or tablet, if it is about drawing:
+
+**Pictures**
+A screenshot, or `klad render` before and after.
diff --git a/.github/ISSUE_TEMPLATE/idea.md b/.github/ISSUE_TEMPLATE/idea.md
new file mode 100644
index 0000000..c8d1902
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/idea.md
@@ -0,0 +1,13 @@
+---
+name: An idea
+about: Something you would like klad to do
+labels: idea
+---
+
+**What you are trying to make**
+The piece of art or the workflow, not only the feature.
+
+**What gets in the way today**
+
+**What would help**
+How you picture it working, in the editor, for the agent, or both.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..4f6fa74
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,6 @@
+**What changed**
+
+**How you checked it**
+- [ ] `just lint`, `just test` and `just audit` pass
+- [ ] Visual changes: a render before and after is attached
+- [ ] Sample hashes that moved are named, with the reason
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1fca8d9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+target/
+/examples/
+.DS_Store
+*.draw/.cache/
+/scratch
+/references/
+
+__pycache__/
+/samples/*/*.draw/
+/samples/*/*.png
+/samples/*/*-godot/
+/samples/*/*.json
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..1cbbb23
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,35 @@
+# klad
+
+_Last updated: 2026-11-04 15:05_
+
+Agent-first 2D art application in Rust: a `klad` CLI for agents and a native editor for people with a pen, sharing one document bundle on disk. What and why: `docs/DESIGN.md`. How to build, test and send a change: `CONTRIBUTING.md`. How an agent draws with it: `docs/skill/SKILL.md`.
+
+## Toolchain
+
+- Rust stable through rustup with clippy and rustfmt (`rust-toolchain.toml`), `just` for recipes. Builds go to `target/` or to `$CARGO_TARGET_DIR`; run cargo from the repository root.
+- The editor (`crates/app`, `klad open`) runs on macOS for now. It compiles and its tests run on Linux too; `klad open` exists only in the macOS build.
+- The editor's panels run headless in tests through `egui_kittest` (`Editor::open` needs no GPU): click, type, drag, read sizes and accessible names. `just ui-pictures` and `cargo test -p klad-app -- --ignored start_pictures` render the UI into `scratch/ui/` with a blank canvas; `editor_picture` draws the canvas too (the kittest renderer gets the canvas resources, and the canvas is redrawn once it has caught up, since uploads made in a pass kittest did not render are lost). `just ui-time` measures UI work per frame.
+- `cargo test -p klad-app` alone does not rebuild the `klad` binary that the job and thumbnail tests run; `just test` (the workspace) does.
+- macOS-only code (`crates/app/src/pen.rs`, `crates/app/src/picker.rs`) can be type-checked from Linux with `rustup target add aarch64-apple-darwin` and a small scratch crate holding the module and its objc2 dependencies (`cargo check --offline --target aarch64-apple-darwin`); the full workspace cannot, `zstd-sys` needs the macOS SDK.
+
+## Working
+
+- Every doc in `docs/` starts with a `_Last updated: YYYY-MM-DD HH:MM_` line; update it when the doc changes.
+- Never commit build output or binaries, and check `git status` before `git add -A`. `samples/` holds generators only; the bundles and pictures they make stay out of git.
+- Commit messages and docs name no one: say what changed and why.
+
+**Done means**
+
+- Tests for new behaviour in the crate that owns it.
+- `just lint` (fmt check plus clippy with `-D warnings`), `just test` and `just audit` are clean.
+- A change that moves a sample's hash says why.
+
+## Standing rules
+
+- No comments in code except `// TODO:`.
+- Iterator chains over `for` loops where they read better; plain loops in hot pixel paths where they are clearer or faster.
+- Determinism in `core`, `brush` and `render`: transcendental math through `libm`, one seeded RNG (`klad_core::rng`), no wall clock, no `HashMap` iteration order in output, parallelism only over independent units (tiles, image rows).
+- Bundles are never broken by a format change: bump the format version and add a migration. The format id inside `doc.json` stays `draw-anything/N` (the project's earlier name) so every bundle keeps opening.
+- Permissive dependencies only: MIT, Apache-2.0, BSD-2/3, ISC, Zlib, BSL-1.0, Unicode-3.0, CC0-1.0; fonts bundled in the editor may be OFL-1.1 or the Ubuntu Font Licence (egui's). No GPL, LGPL or MPL unless dual licensed with one of these. `deny.toml` holds the list and `just audit` checks it; every shipped licence text is in `THIRD-PARTY-NOTICES.md` (`just notices`).
+- The project is source-available, not open source: the PolyForm Internal Use License 1.0.0 with a personal-use permission, copyright Indicode BV (`LICENSE`).
+- No em-dashes in docs, messages or UI text.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..9f2e053
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,37 @@
+# Contributing
+
+Thank you for looking. klad is young and changes fast; issues with a drawing that shows the problem are the most useful thing you can send.
+
+## Before you start
+
+- Bugs: open an issue with what you did, what you saw, `klad --version`, your OS, and if you can the `.draw` folder (zipped) or the commands that make it.
+- Larger changes: open an issue first, so we can agree on the shape before you build it.
+- Security problems: see `SECURITY.md`, not the issue tracker.
+
+## Building
+
+- Rust through [rustup](https://rustup.rs); `rust-toolchain.toml` picks the version. [`just`](https://github.com/casey/just) runs the recipes.
+- macOS: the Xcode command line tools. Linux: `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`. Windows is not tested yet.
+- The first build downloads a prebuilt Skia for your platform (`skia-bindings` does this), so it needs network once.
+- `just build`, `just test`, `just lint`. `just audit` needs [`cargo-deny`](https://github.com/EmbarkStudios/cargo-deny) and [`cargo-about`](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-deny --locked` and `cargo install cargo-about --locked --features cli`).
+- The editor is `klad open`. Its panels are tested headless with `egui_kittest`; `cargo test -p klad-app -- --ignored editor_picture` (the editor with a sample drawing on its canvas), `start_pictures` and `just ui-pictures` write pictures of the UI to `scratch/ui/`.
+
+## The rules the code follows
+
+These come from `CLAUDE.md`, which is also the guide for coding agents working on the repository.
+
+- No comments in code except `// TODO:`. Names and small functions carry the meaning.
+- Iterator chains where they read better than loops; plain loops in hot pixel code where they are clearer or faster.
+- Determinism: `core`, `brush` and `render` give the same pixels on every machine. Transcendental math goes through `libm`, randomness through the seeded `klad_core::rng`, no clock, no `HashMap` order in output, parallelism only over independent tiles or rows. A change that moves a sample's hash says why.
+- Bundles never break: a format change bumps the format version and adds a migration, so older drawings open unchanged.
+- Dependencies are permissive only (MIT, Apache-2.0, BSD, ISC, Zlib and the others in `deny.toml`). Adding one means `just audit` passes and `just notices` regenerates `THIRD-PARTY-NOTICES.md` in the same change.
+- New behaviour comes with tests in the crate that owns it. `just lint` and `just test` are clean before a pull request.
+- No em-dashes in docs or messages; every doc in `docs/` starts with a `_Last updated:_` line.
+
+## Sending a change
+
+1. Fork, branch from `main`, keep the change to one thing.
+2. `just lint`, `just test` and `just audit` pass.
+3. Describe what changed and how you checked it; for anything visual, attach a render (`klad render`) before and after.
+
+By sending a contribution you agree that Indicode BV may publish it under the licence of the project.
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..b881486
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,4681 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "accesskit"
+version = "0.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be"
+dependencies = [
+ "uuid",
+]
+
+[[package]]
+name = "accesskit_atspi_common"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d"
+dependencies = [
+ "accesskit",
+ "accesskit_consumer",
+ "atspi-common",
+ "phf",
+ "serde",
+ "zvariant",
+]
+
+[[package]]
+name = "accesskit_consumer"
+version = "0.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3"
+dependencies = [
+ "accesskit",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "accesskit_ios"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5280724673bbfa8b30a838c013500b719392989be3b97c5a9964062c252c232"
+dependencies = [
+ "accesskit",
+ "accesskit_consumer",
+ "hashbrown 0.17.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+ "objc2-ui-kit 0.2.2",
+]
+
+[[package]]
+name = "accesskit_macos"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84"
+dependencies = [
+ "accesskit",
+ "accesskit_consumer",
+ "hashbrown 0.17.1",
+ "objc2 0.5.3",
+ "objc2-app-kit 0.2.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "accesskit_unix"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6"
+dependencies = [
+ "accesskit",
+ "accesskit_atspi_common",
+ "async-channel",
+ "async-executor",
+ "async-task",
+ "atspi",
+ "futures-lite",
+ "futures-util",
+ "serde",
+ "zbus",
+]
+
+[[package]]
+name = "accesskit_windows"
+version = "0.35.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "498668b90da9995302a0055aaecad4756932333da2ddef6baee1c00844c430fc"
+dependencies = [
+ "accesskit",
+ "accesskit_consumer",
+ "hashbrown 0.17.1",
+ "static_assertions",
+ "windows",
+ "windows-core",
+]
+
+[[package]]
+name = "accesskit_winit"
+version = "0.34.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd4ab4437b520ff03088fbe48676a11e7d44a929535e64b31432c1073e48dbcc"
+dependencies = [
+ "accesskit",
+ "accesskit_ios",
+ "accesskit_macos",
+ "accesskit_unix",
+ "accesskit_windows",
+ "raw-window-handle",
+ "winit",
+]
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "version_check",
+ "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 = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "android-activity"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"
+dependencies = [
+ "android-properties",
+ "bitflags 2.13.2",
+ "cc",
+ "jni",
+ "libc",
+ "log",
+ "ndk",
+ "ndk-context",
+ "ndk-sys",
+ "num_enum",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "android-properties"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "arboard"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917"
+dependencies = [
+ "clipboard-win",
+ "image",
+ "log",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "parking_lot",
+ "percent-encoding",
+ "windows-sys 0.61.2",
+ "wl-clipboard-rs",
+ "x11rb",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
+[[package]]
+name = "as-raw-xcb-connection"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
+
+[[package]]
+name = "ash"
+version = "0.38.0+1.3.281"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
+dependencies = [
+ "libloading",
+]
+
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-executor"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
+dependencies = [
+ "async-task",
+ "concurrent-queue",
+ "fastrand",
+ "futures-lite",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "async-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix 1.1.6",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix 1.1.6",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix 1.1.6",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
+name = "async-trait"
+version = "0.1.92"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "atspi"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d"
+dependencies = [
+ "atspi-common",
+ "atspi-proxies",
+]
+
+[[package]]
+name = "atspi-common"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d"
+dependencies = [
+ "enumflags2",
+ "serde",
+ "static_assertions",
+ "zbus",
+ "zbus-lockstep",
+ "zbus-lockstep-macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "atspi-proxies"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc"
+dependencies = [
+ "atspi-common",
+ "serde",
+ "zbus",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bindgen"
+version = "0.73.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
+dependencies = [
+ "bitflags 2.13.2",
+ "cexpr",
+ "clang-sys",
+ "log",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash 2.1.3",
+ "shlex",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "bit-set"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block2"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
+dependencies = [
+ "objc2 0.5.3",
+]
+
+[[package]]
+name = "block2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
+dependencies = [
+ "objc2 0.6.5",
+]
+
+[[package]]
+name = "blocking"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "calloop"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
+dependencies = [
+ "bitflags 2.13.2",
+ "log",
+ "polling",
+ "rustix 0.38.44",
+ "slab",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "calloop"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e"
+dependencies = [
+ "bitflags 2.13.2",
+ "polling",
+ "rustix 1.1.6",
+ "tracing",
+]
+
+[[package]]
+name = "calloop-wayland-source"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
+dependencies = [
+ "calloop 0.13.0",
+ "rustix 0.38.44",
+ "wayland-backend",
+ "wayland-client",
+]
+
+[[package]]
+name = "calloop-wayland-source"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa"
+dependencies = [
+ "calloop 0.14.5",
+ "rustix 1.1.6",
+ "wayland-backend",
+ "wayland-client",
+]
+
+[[package]]
+name = "cc"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom 7.1.3",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "cgl"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "clang-sys"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
+
+[[package]]
+name = "clipboard-win"
+version = "5.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
+dependencies = [
+ "error-code",
+]
+
+[[package]]
+name = "codespan-reporting"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
+dependencies = [
+ "serde",
+ "termcolor",
+ "unicode-width",
+]
+
+[[package]]
+name = "color"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "combine"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics"
+version = "0.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "core-graphics-types",
+ "foreign-types",
+ "libc",
+]
+
+[[package]]
+name = "core-graphics-types"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "cursor-icon"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+
+[[package]]
+name = "dispatch"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
+
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+]
+
+[[package]]
+name = "dlib"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
+dependencies = [
+ "libloading",
+]
+
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
+[[package]]
+name = "downcast-rs"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
+[[package]]
+name = "dpi"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+
+[[package]]
+name = "ecolor"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31bcbef0d4263a63eb32c4834e5d711613035ce1333468e107d928923e21e6e2"
+dependencies = [
+ "bytemuck",
+ "emath",
+]
+
+[[package]]
+name = "eframe"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c5642501a65ca657d05f00c643a5c14ff2346cb3818032bfe23d58e1f8e5f84"
+dependencies = [
+ "ahash",
+ "bytemuck",
+ "document-features",
+ "egui",
+ "egui-wgpu",
+ "egui-winit",
+ "egui_glow",
+ "glutin",
+ "glutin-winit",
+ "image",
+ "js-sys",
+ "log",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "parking_lot",
+ "percent-encoding",
+ "pollster",
+ "profiling",
+ "raw-window-handle",
+ "send_wrapper",
+ "static_assertions",
+ "wasm-bindgen",
+ "web-sys",
+ "web-time",
+ "wgpu",
+ "windows-sys 0.61.2",
+ "winit",
+]
+
+[[package]]
+name = "egui"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bec9144f49b7a28b5f395d3147e325b4fe3e77ba686eac11d1bdf0a7da3f375f"
+dependencies = [
+ "accesskit",
+ "ahash",
+ "bitflags 2.13.2",
+ "emath",
+ "epaint",
+ "itertools",
+ "log",
+ "nohash-hasher",
+ "profiling",
+ "smallvec",
+ "unicode-segmentation",
+ "web-sys",
+]
+
+[[package]]
+name = "egui-wgpu"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0309cbe1febed48af5b974e4bcc424b35e9664863a4d402697147b57a488c864"
+dependencies = [
+ "ahash",
+ "bytemuck",
+ "document-features",
+ "egui",
+ "epaint",
+ "log",
+ "profiling",
+ "thiserror 2.0.21",
+ "type-map",
+ "web-time",
+ "wgpu",
+ "winit",
+]
+
+[[package]]
+name = "egui-winit"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e449f4c4a2a60c7ccb4ba7fa4078417bfe1f9ddc03b5e05ce75748e33a70de"
+dependencies = [
+ "accesskit_winit",
+ "arboard",
+ "block2 0.6.2",
+ "bytemuck",
+ "egui",
+ "log",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "objc2-ui-kit 0.3.2",
+ "profiling",
+ "raw-window-handle",
+ "smithay-clipboard",
+ "web-time",
+ "windows-sys 0.61.2",
+ "winit",
+]
+
+[[package]]
+name = "egui_glow"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9275ca5cc35a6b7c94e0e8cedf22542f66cb0cf45ed8ab2657c78ff49fec7268"
+dependencies = [
+ "bytemuck",
+ "egui",
+ "glow",
+ "log",
+ "profiling",
+ "winit",
+]
+
+[[package]]
+name = "egui_kittest"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0979c2e37860fcf13a2bea77508607f067a9a6a84ba9bd47b5e298582fb59b86"
+dependencies = [
+ "eframe",
+ "egui",
+ "egui-wgpu",
+ "image",
+ "kittest",
+ "log",
+ "pollster",
+ "serde",
+ "toml",
+ "wgpu",
+]
+
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
+[[package]]
+name = "emath"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e73ce90f54750be8672c02be0743fe47530e6f251e066f0ee2869b59eb297af5"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
+[[package]]
+name = "enumflags2"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
+dependencies = [
+ "enumflags2_derive",
+ "serde",
+]
+
+[[package]]
+name = "enumflags2_derive"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "epaint"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97bac86ae3dde93fc3951e790951caea739ff39a6c89d909cdaf1d9278dbb1bd"
+dependencies = [
+ "ahash",
+ "bytemuck",
+ "ecolor",
+ "emath",
+ "epaint_default_fonts",
+ "font-types",
+ "harfrust",
+ "log",
+ "nohash-hasher",
+ "parking_lot",
+ "profiling",
+ "self_cell",
+ "skrifa",
+ "smallvec",
+ "unicode-general-category",
+ "unicode-properties",
+ "unicode-segmentation",
+ "vello_cpu",
+]
+
+[[package]]
+name = "epaint_default_fonts"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfc1cc505827f4c23eedc297975a0fd038268d41293f389dd8ff3b574aefab19"
+
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "error-code"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
+
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "fearless_simd"
+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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
+
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
+]
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "font-types"
+version = "0.12.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-macro",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix 1.1.6",
+ "windows-link",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+]
+
+[[package]]
+name = "gl_generator"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
+dependencies = [
+ "khronos_api",
+ "log",
+ "xml-rs",
+]
+
+[[package]]
+name = "glifo"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be"
+dependencies = [
+ "bytemuck",
+ "foldhash 0.2.0",
+ "hashbrown 0.17.1",
+ "log",
+ "peniko",
+ "skrifa",
+ "smallvec",
+ "vello_common",
+]
+
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
+[[package]]
+name = "glow"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"
+dependencies = [
+ "js-sys",
+ "slotmap",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "glutin"
+version = "0.32.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg_aliases",
+ "cgl",
+ "dispatch2",
+ "glutin_egl_sys",
+ "glutin_glx_sys",
+ "glutin_wgl_sys",
+ "libloading",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "once_cell",
+ "raw-window-handle",
+ "wayland-sys",
+ "windows-sys 0.52.0",
+ "x11-dl",
+]
+
+[[package]]
+name = "glutin-winit"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f"
+dependencies = [
+ "cfg_aliases",
+ "glutin",
+ "raw-window-handle",
+ "winit",
+]
+
+[[package]]
+name = "glutin_egl_sys"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2"
+dependencies = [
+ "gl_generator",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "glutin_glx_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185"
+dependencies = [
+ "gl_generator",
+ "x11-dl",
+]
+
+[[package]]
+name = "glutin_wgl_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
+dependencies = [
+ "gl_generator",
+]
+
+[[package]]
+name = "gpu-allocator"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
+dependencies = [
+ "ash",
+ "hashbrown 0.16.1",
+ "log",
+ "presser",
+ "thiserror 2.0.21",
+ "windows",
+]
+
+[[package]]
+name = "guillotiere"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab"
+dependencies = [
+ "euclid",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "bytemuck",
+ "cfg-if",
+ "crunchy",
+ "num-traits",
+ "zerocopy",
+]
+
+[[package]]
+name = "harfrust"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "read-fonts",
+ "smallvec",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash 0.1.5",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash 0.2.0",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash 0.2.0",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "moxcms",
+ "num-traits",
+ "png",
+ "tiff",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "inotify"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
+dependencies = [
+ "bitflags 2.13.2",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itertools"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys 0.4.1",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.21",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "khronos-egl"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"
+dependencies = [
+ "libc",
+ "libloading",
+ "pkg-config",
+]
+
+[[package]]
+name = "khronos_api"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
+
+[[package]]
+name = "kittest"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75"
+dependencies = [
+ "accesskit",
+ "accesskit_consumer",
+]
+
+[[package]]
+name = "klad-app"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "block2 0.6.2",
+ "bytemuck",
+ "eframe",
+ "egui",
+ "egui-wgpu",
+ "egui_kittest",
+ "half",
+ "klad-brush",
+ "klad-core",
+ "klad-render",
+ "notify",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "png",
+ "pollster",
+ "rayon",
+ "serde",
+ "serde_json",
+ "zstd",
+]
+
+[[package]]
+name = "klad-brush"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytemuck",
+ "half",
+ "klad-core",
+ "libm",
+ "png",
+ "rayon",
+ "serde",
+ "serde_json",
+ "zstd",
+]
+
+[[package]]
+name = "klad-cli"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "klad-app",
+ "klad-brush",
+ "klad-core",
+ "klad-render",
+ "libc",
+ "libm",
+ "notify",
+ "rayon",
+ "serde_json",
+ "zstd",
+]
+
+[[package]]
+name = "klad-core"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "half",
+ "libm",
+ "serde",
+ "serde_json",
+ "zstd",
+]
+
+[[package]]
+name = "klad-render"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytemuck",
+ "half",
+ "klad-brush",
+ "klad-core",
+ "libm",
+ "png",
+ "rayon",
+ "serde_json",
+ "skia-safe",
+ "skrifa",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "kqueue"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+]
+
+[[package]]
+name = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+ "plain",
+ "redox_syscall 0.9.5",
+]
+
+[[package]]
+name = "linebender_resource_handle"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litrs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memmap2"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
+dependencies = [
+ "libc",
+ "log",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "naga"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "libm",
+ "log",
+ "naga-types",
+ "num-traits",
+ "once_cell",
+ "rustc-hash 1.1.0",
+ "spirv",
+ "thiserror 2.0.21",
+ "unicode-ident",
+]
+
+[[package]]
+name = "naga-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
+dependencies = [
+ "hashbrown 0.17.1",
+ "indexmap",
+ "rustc-hash 1.1.0",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "ndk"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
+dependencies = [
+ "bitflags 2.13.2",
+ "jni-sys 0.3.1",
+ "log",
+ "ndk-sys",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ndk-context"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+
+[[package]]
+name = "ndk-sys"
+version = "0.6.0+11769913"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
+[[package]]
+name = "nohash-hasher"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "notify"
+version = "8.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674"
+dependencies = [
+ "bitflags 2.13.2",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log",
+ "mio",
+ "notify-types",
+ "objc2-core-foundation",
+ "objc2-core-services",
+ "walkdir",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "notify-types"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a437a9308232ce794b1e7fdf540d38ea37efc3c73492640c13b4c8568b8f108"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "objc-sys"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
+
+[[package]]
+name = "objc2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b"
+dependencies = [
+ "objc-sys",
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "libc",
+ "objc2 0.5.3",
+ "objc2-core-data 0.2.2",
+ "objc2-core-image 0.2.2",
+ "objc2-foundation 0.2.2",
+ "objc2-quartz-core 0.2.2",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "libc",
+ "objc2 0.6.5",
+ "objc2-cloud-kit 0.3.2",
+ "objc2-core-data 0.3.2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-core-image 0.3.2",
+ "objc2-core-text",
+ "objc2-core-video",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-contacts"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.2",
+ "dispatch2",
+ "objc2 0.6.5",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
+dependencies = [
+ "bitflags 2.13.2",
+ "dispatch2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+ "objc2-metal 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
+dependencies = [
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-contacts",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-services"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-core-text"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+]
+
+[[package]]
+name = "objc2-core-video"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "dispatch",
+ "libc",
+ "objc2 0.5.3",
+]
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "libc",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-surface"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-link-presentation"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-app-kit 0.2.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+ "objc2-metal 0.2.2",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
+]
+
+[[package]]
+name = "objc2-symbols"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"
+dependencies = [
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-cloud-kit 0.2.2",
+ "objc2-core-data 0.2.2",
+ "objc2-core-image 0.2.2",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+ "objc2-link-presentation",
+ "objc2-quartz-core 0.2.2",
+ "objc2-symbols",
+ "objc2-uniform-type-identifiers",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-uniform-type-identifiers"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.3",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "orbclient"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"
+dependencies = [
+ "libc",
+ "libredox",
+]
+
+[[package]]
+name = "ordered-float"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "os_pipe"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall 0.5.18",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "peniko"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6"
+dependencies = [
+ "bytemuck",
+ "color",
+ "kurbo",
+ "linebender_resource_handle",
+ "smallvec",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset",
+ "hashbrown 0.15.5",
+ "indexmap",
+]
+
+[[package]]
+name = "phf"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+ "serde",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
+dependencies = [
+ "fastrand",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"
+dependencies = [
+ "siphasher",
+]
+
+[[package]]
+name = "pin-project"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.13.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix 1.1.6",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "pollster"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
+
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
+[[package]]
+name = "prettyplease"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
+dependencies = [
+ "proc-macro2",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "range-alloc"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "raw-window-metal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
+dependencies = [
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+]
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "read-fonts"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
+dependencies = [
+ "bytemuck",
+ "font-types",
+ "once_cell",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"
+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 = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.12.1",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "scoped-tls"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "self_cell"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "send_wrapper"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
+[[package]]
+name = "simdutf8"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+
+[[package]]
+name = "siphasher"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
+
+[[package]]
+name = "skia-bindings"
+version = "0.157.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3930c7f5e8d813364d74c3b17b227f3bb3a84504f93bb1f8c222d8fd5a7d9c6f"
+dependencies = [
+ "bindgen",
+ "cc",
+ "flate2",
+ "heck",
+ "pkg-config",
+ "regex",
+ "serde_json",
+ "tar",
+ "toml",
+]
+
+[[package]]
+name = "skia-safe"
+version = "0.157.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1c946dbc1a10b6b1ace7e368ea71f96c81448bbf55effcad0a9a3a392358eb"
+dependencies = [
+ "bitflags 2.13.2",
+ "skia-bindings",
+]
+
+[[package]]
+name = "skrifa"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
+dependencies = [
+ "bytemuck",
+ "read-fonts",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "slotmap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
+
+[[package]]
+name = "smithay-client-toolkit"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
+dependencies = [
+ "bitflags 2.13.2",
+ "calloop 0.13.0",
+ "calloop-wayland-source 0.3.0",
+ "cursor-icon",
+ "libc",
+ "log",
+ "memmap2",
+ "rustix 0.38.44",
+ "thiserror 1.0.69",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-csd-frame",
+ "wayland-cursor",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+ "wayland-scanner",
+ "xkeysym",
+]
+
+[[package]]
+name = "smithay-client-toolkit"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0"
+dependencies = [
+ "bitflags 2.13.2",
+ "calloop 0.14.5",
+ "calloop-wayland-source 0.4.1",
+ "cursor-icon",
+ "libc",
+ "log",
+ "memmap2",
+ "rustix 1.1.6",
+ "thiserror 2.0.21",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-csd-frame",
+ "wayland-cursor",
+ "wayland-protocols",
+ "wayland-protocols-experimental",
+ "wayland-protocols-misc",
+ "wayland-protocols-wlr",
+ "wayland-scanner",
+ "xkeysym",
+]
+
+[[package]]
+name = "smithay-clipboard"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226"
+dependencies = [
+ "libc",
+ "smithay-client-toolkit 0.20.0",
+ "wayland-backend",
+]
+
+[[package]]
+name = "smol_str"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "spirv"
+version = "0.4.0+sdk-1.4.341.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tar"
+version = "0.4.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix 1.1.6",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl 2.0.21",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "tokio"
+version = "1.54.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
+dependencies = [
+ "pin-project-lite",
+]
+
+[[package]]
+name = "toml"
+version = "1.1.8+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.17+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
+dependencies = [
+ "indexmap",
+ "toml_datetime",
+ "toml_parser",
+ "winnow",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
+dependencies = [
+ "winnow",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "tree_magic_mini"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
+dependencies = [
+ "memchr",
+ "nom 8.0.0",
+ "petgraph",
+]
+
+[[package]]
+name = "type-map"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90"
+dependencies = [
+ "rustc-hash 2.1.3",
+]
+
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "unicode-general-category"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-width"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "uuid"
+version = "1.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
+dependencies = [
+ "js-sys",
+ "serde_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "vello_common"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd"
+dependencies = [
+ "bytemuck",
+ "fearless_simd",
+ "guillotiere",
+ "log",
+ "peniko",
+ "smallvec",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "vello_cpu"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"
+dependencies = [
+ "bytemuck",
+ "glifo",
+ "hashbrown 0.17.1",
+ "vello_common",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
+dependencies = [
+ "cfg-if",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.80"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wayland-backend"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
+dependencies = [
+ "cc",
+ "downcast-rs",
+ "rustix 1.1.6",
+ "scoped-tls",
+ "smallvec",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-client"
+version = "0.31.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
+dependencies = [
+ "bitflags 2.13.2",
+ "rustix 1.1.6",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-csd-frame"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
+dependencies = [
+ "bitflags 2.13.2",
+ "cursor-icon",
+ "wayland-backend",
+]
+
+[[package]]
+name = "wayland-cursor"
+version = "0.31.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
+dependencies = [
+ "rustix 1.1.6",
+ "wayland-client",
+ "xcursor",
+]
+
+[[package]]
+name = "wayland-protocols"
+version = "0.32.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-experimental"
+version = "20250721.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-misc"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-plasma"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-wlr"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-scanner"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
+dependencies = [
+ "proc-macro2",
+ "quick-xml",
+ "quote",
+]
+
+[[package]]
+name = "wayland-sys"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
+dependencies = [
+ "dlib",
+ "log",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "wgpu"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "js-sys",
+ "log",
+ "naga",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "smallvec",
+ "static_assertions",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wgpu-core",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bit-vec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "log",
+ "naga",
+ "naga-types",
+ "once_cell",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "rustc-hash 1.1.0",
+ "smallvec",
+ "thiserror 2.0.21",
+ "wgpu-core-deps-apple",
+ "wgpu-core-deps-emscripten",
+ "wgpu-core-deps-wasm",
+ "wgpu-core-deps-windows-linux-android",
+ "wgpu-hal",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core-deps-apple"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-emscripten"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-wasm"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-windows-linux-android"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-hal"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
+dependencies = [
+ "android_system_properties",
+ "arrayvec",
+ "ash",
+ "bit-set",
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "glow",
+ "glutin_wgl_sys",
+ "gpu-allocator",
+ "hashbrown 0.17.1",
+ "js-sys",
+ "khronos-egl",
+ "libc",
+ "libloading",
+ "log",
+ "naga",
+ "naga-types",
+ "ndk-sys",
+ "objc2 0.6.5",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
+ "objc2-quartz-core 0.3.2",
+ "once_cell",
+ "ordered-float",
+ "parking_lot",
+ "portable-atomic",
+ "portable-atomic-util",
+ "profiling",
+ "range-alloc",
+ "raw-window-handle",
+ "raw-window-metal",
+ "renderdoc-sys",
+ "smallvec",
+ "static_assertions",
+ "thiserror 2.0.21",
+ "wasm-bindgen",
+ "wayland-sys",
+ "web-sys",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+ "windows",
+ "windows-core",
+ "windows-result",
+]
+
+[[package]]
+name = "wgpu-naga-bridge"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"
+dependencies = [
+ "naga",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "js-sys",
+ "log",
+ "naga-types",
+ "raw-window-handle",
+ "static_assertions",
+ "web-sys",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections",
+ "windows-core",
+ "windows-future",
+ "windows-numerics",
+]
+
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core",
+ "windows-link",
+ "windows-threading",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core",
+ "windows-link",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "winit"
+version = "0.30.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
+dependencies = [
+ "ahash",
+ "android-activity",
+ "atomic-waker",
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "bytemuck",
+ "calloop 0.13.0",
+ "cfg_aliases",
+ "concurrent-queue",
+ "core-foundation",
+ "core-graphics",
+ "cursor-icon",
+ "dpi",
+ "js-sys",
+ "libc",
+ "memmap2",
+ "ndk",
+ "objc2 0.5.3",
+ "objc2-app-kit 0.2.2",
+ "objc2-foundation 0.2.2",
+ "objc2-ui-kit 0.2.2",
+ "orbclient",
+ "percent-encoding",
+ "pin-project",
+ "raw-window-handle",
+ "redox_syscall 0.4.1",
+ "rustix 0.38.44",
+ "smithay-client-toolkit 0.19.2",
+ "smol_str",
+ "tracing",
+ "unicode-segmentation",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-plasma",
+ "web-sys",
+ "web-time",
+ "windows-sys 0.52.0",
+ "x11-dl",
+ "x11rb",
+ "xkbcommon-dl",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "wl-clipboard-rs"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848"
+dependencies = [
+ "libc",
+ "log",
+ "os_pipe",
+ "rustix 1.1.6",
+ "thiserror 2.0.21",
+ "tree_magic_mini",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+]
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "as-raw-xcb-connection",
+ "gethostname",
+ "libc",
+ "libloading",
+ "once_cell",
+ "rustix 1.1.6",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
+[[package]]
+name = "xattr"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08"
+dependencies = [
+ "libc",
+ "rustix 1.1.6",
+]
+
+[[package]]
+name = "xcursor"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
+
+[[package]]
+name = "xkbcommon-dl"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"
+dependencies = [
+ "bitflags 2.13.2",
+ "dlib",
+ "log",
+ "once_cell",
+ "xkeysym",
+]
+
+[[package]]
+name = "xkeysym"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+
+[[package]]
+name = "xml-rs"
+version = "0.8.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+
+[[package]]
+name = "zbus"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
+dependencies = [
+ "async-broadcast",
+ "async-executor",
+ "async-io",
+ "async-lock",
+ "async-process",
+ "async-recursion",
+ "async-task",
+ "async-trait",
+ "blocking",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-lite",
+ "hex",
+ "libc",
+ "ordered-stream",
+ "rustix 1.1.6",
+ "serde",
+ "serde_repr",
+ "tracing",
+ "uds_windows",
+ "uuid",
+ "windows-sys 0.61.2",
+ "winnow",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus-lockstep"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863"
+dependencies = [
+ "zbus_xml",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus-lockstep-macros"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zbus-lockstep",
+ "zbus_xml",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+ "zbus_names",
+ "zvariant",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "4.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
+dependencies = [
+ "serde",
+ "winnow",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_xml"
+version = "5.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a"
+dependencies = [
+ "serde",
+ "winnow",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zcheapstr"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zstd"
+version = "0.14.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "8.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.1.2+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
+
+[[package]]
+name = "zvariant"
+version = "5.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "winnow",
+ "zcheapstr",
+ "zvariant_derive",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "5.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 3.0.9",
+ "winnow",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..3859e50
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,16 @@
+[workspace]
+resolver = "3"
+members = ["crates/*"]
+
+[workspace.package]
+version = "0.1.0"
+edition = "2024"
+license-file = "LICENSE"
+repository = "https://github.com/klad-app/klad"
+publish = false
+
+[profile.release]
+debug = 1
+
+[profile.dev.package."*"]
+opt-level = 3
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..47def88
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,77 @@
+klad
+Copyright 2026 Indicode BV
+
+The klad software is licensed under the PolyForm Internal Use License 1.0.0
+below, with these additional permissions:
+
+- Use of the software for your own personal purposes is also use for a
+ permitted purpose.
+- You may distribute changes and new works based on the software to
+ Indicode BV, for example as a pull request, to propose them as a
+ contribution to the software.
+- Drawings you make with the software are yours. You may share them,
+ including the brush settings and brush pictures the software copies into
+ them; fonts copied into them keep their own licences.
+
+Builds of the software that you buy, from Indicode BV or from a store such
+as itch.io or Steam, are licensed under these same terms.
+
+Third-party parts keep their own licences: see THIRD-PARTY-NOTICES.md.
+
+---
+
+# PolyForm Internal Use License 1.0.0
+
+<https://polyformproject.org/licenses/internal-use/1.0.0>
+
+## Acceptance
+
+In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
+
+## Copyright License
+
+The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license), and you may not distribute the software.
+
+## Changes and New Works License
+
+The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
+
+## Patent License
+
+The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
+
+## Fair Use
+
+You may have "fair use" rights for the software under the law. These terms do not limit them.
+
+## Internal Business Use
+
+Use of the software for the internal business operations of you and your company is use for a permitted purpose.
+
+## No Other Rights
+
+These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
+
+## Patent Defense
+
+If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
+
+## Violations
+
+The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
+
+## No Liability
+
+***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
+
+## Definitions
+
+The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
+
+**You** refers to the individual or entity agreeing to these terms.
+
+**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
+
+**Your licenses** are all the licenses granted to you for the software under these terms.
+
+**Use** means anything you do with the software requiring one of your licenses.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..73fcdeb
--- /dev/null
+++ b/README.md
@@ -0,0 +1,61 @@
+# klad
+
+![The klad editor with a painted lantern prop open](docs/images/editor.png)
+
+A 2D art app you share with an AI agent. You draw and paint in the editor with a pen; the agent works on the same drawing through the `klad` command line, and each of you sees the other's changes within a second. Everything in a drawing stays editable: strokes are kept as data (their path, pressure and brush), vector shapes keep their points, and effects, light and depth are settings on layers.
+
+![Three solids painted stroke by stroke by the agent](docs/images/solids.png)
+
+![A lantern prop, inked on the left and painted by form on the right](docs/images/lantern.png)
+
+It is made for game art: props, characters, backgrounds and frame-by-frame animation, exported as PNGs, sprite sheets or straight into Godot.
+
+## Status
+
+Early, and open for testing. What works today:
+
+- The `klad` CLI on macOS and Linux: layers, brush strokes, vector shapes, fills, inking, painting from shapes, light, effects, depth and fog, text, frames and clips, in-betweens, exports.
+- The editor on macOS: a pen with pressure and tilt, brushes, layers, masks, the timeline, onion skins, notes for the agent, and a start window for new and recent drawings.
+- Coming next: downloadable builds for macOS, Windows and Linux, the editor on Windows and Linux, and an agent inside the editor you sign in to, so you never need a terminal.
+
+![The start window](docs/images/start-window.png)
+
+## Try it
+
+There are no downloads yet; build it from source (about ten minutes the first time).
+
+1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev` and `libfontconfig1-dev`.
+2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes the `klad` binary in `target/release/`.
+3. On a Mac, `target/release/klad open` starts the editor on its start window: make a drawing and start painting.
+4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, painted solids, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.
+
+## Drawing with an agent
+
+Any coding agent that can run commands (Claude Code, Codex and others) can draw. Give it `docs/skill/SKILL.md` as its instructions (it is written as an agent skill) and the path to a drawing, then ask:
+
+```sh
+target/release/klad new art.draw --width 1600 --height 1200 --background '#e9e4da' --sketch
+target/release/klad open art.draw # in another terminal, to watch and draw along
+```
+
+> "Block in a rock on the sketch layer, fill it, and paint it as a round form lit from the upper left."
+
+The agent looks at the drawing through renders (`klad render`), changes it with `klad` commands or batches of JSON ops (`klad apply`), and reads what you pinned for it with notes or selected in the editor. Its strokes are marked as agent strokes and every change is one step in the shared history, so you can undo it in the editor.
+
+## Building on it
+
+- `docs/DESIGN.md`: the document format, the CLI, the brush engine, rendering, the editor, the dependencies.
+- `CONTRIBUTING.md`: building, testing, the code rules and how to send a change.
+- `samples/`: generators that make drawings from scratch, the best place to see the ops in use.
+
+```sh
+just build # release build of the klad CLI and the editor
+just test # every test, and the drawkit check
+just lint # rustfmt and clippy, warnings as errors
+just audit # licences, RustSec advisories, sources, and the notices are current
+just samples # build the sample drawings
+```
+
+## Licence
+
+Source-available, not open source: the PolyForm Internal Use License 1.0.0 with a personal-use permission, copyright Indicode BV (`LICENSE`). klad is built on open source libraries, fonts and Skia; their licences are in `THIRD-PARTY-NOTICES.md`, also shown by `klad licences` and in the editor's About window.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..a6bdedf
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,13 @@
+# Security
+
+klad opens `.draw` folders, pictures and fonts that may come from anyone, and runs agents' commands on them. A file that crashes it, reads or writes outside the drawing, or runs code is a security problem.
+
+## Reporting
+
+Please report privately through GitHub's "Report a vulnerability" on the repository's Security tab, not in a public issue. Include the version (`klad --version`), your OS, and the smallest file or command that shows the problem.
+
+We aim to answer within a week, agree on a fix and a date with you, and credit you in the release notes unless you would rather not be named.
+
+## Supported versions
+
+Only the latest release and `main` get fixes while the project is below 1.0.
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
new file mode 100644
index 0000000..63c69bd
--- /dev/null
+++ b/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,6713 @@
+# Third-party notices
+
+klad is source-available under the PolyForm Internal Use License 1.0.0 with additional permissions (see LICENSE), copyright Indicode BV. It is built on the open source work below. This file is generated by `just notices` from the Rust crates in `Cargo.lock` (cargo-about), followed by the parts Cargo does not see: the Skia library and what is built into it, and the fonts.
+
+## Rust crates
+
+### Apache License 2.0
+
+Used by:
+- moxcms 0.8.1 (https://github.com/awxkee/moxcms.git)
+- pxfm 0.1.30 (https://github.com/awxkee/pxfm)
+
+```text
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 Radzivon Bartoshyk
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+```
+
+### Apache License 2.0
+
+Used by:
+- codespan-reporting 0.13.1 (https://github.com/brendanzab/codespan)
+- self_cell 1.3.0 (https://github.com/Voultapher/self_cell)
+
+```text
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+```
+
+### Apache License 2.0
+
+Used by:
+- unicode-general-category 1.1.0 (https://github.com/yeslogic/unicode-general-category)
+
+```text
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+```
+
+### Apache License 2.0
+
+Used by:
+- gethostname 1.1.0 (https://codeberg.org/swsnr/gethostname.rs.git)
+
+```text
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+```
+
+### Apache License 2.0
+
+Used by:
+- glutin_wgl_sys 0.6.1 (https://github.com/rust-windowing/glutin)
+
+```text
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2022 Kirill Chibisov
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+```
+
+### Apache License 2.0
+
+Used by:
+- dpi 0.1.2 (https://github.com/rust-windowing/winit)
+- winit 0.30.13 (https://github.com/rust-windowing/winit)
+
+```text
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+```
+
+### Apache License 2.0
+
+Used by:
+- accesskit_winit 0.34.2 (https://github.com/AccessKit/accesskit)
+- spirv 0.4.0+sdk-1.4.341.0 (https://github.com/gfx-rs/rspirv)
+
+```text
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+```
+
+### BSD 3-Clause "New" or "Revised" License
+
+Used by:
+- zstd-safe 8.2.0 (https://github.com/gyscos/zstd-rs)
+- zstd-sys 2.1.2+zstd.1.5.7 (https://github.com/gyscos/zstd-rs)
+- zstd 0.14.3 (https://github.com/gyscos/zstd-rs)
+
+```text
+BSD 3-Clause License
+
+Copyright (c) 2026, Alexandre Bury
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+```
+
+### BSD 3-Clause "New" or "Revised" License
+
+Used by:
+- zstd-sys 2.1.2+zstd.1.5.7 (https://github.com/gyscos/zstd-rs)
+
+```text
+BSD License
+
+For Zstandard software
+
+Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook, nor Meta, nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+```
+
+### BSD 3-Clause "New" or "Revised" License
+
+Used by:
+- zstd-sys 2.1.2+zstd.1.5.7 (https://github.com/gyscos/zstd-rs)
+
+```text
+The auto-generated bindings are under the 3-clause BSD license:
+
+BSD License
+
+For Zstandard software
+
+Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook, nor Meta, nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+```
+
+### Boost Software License 1.0
+
+Used by:
+- error-code 3.4.0 (https://github.com/DoumanAsh/error-code)
+
+```text
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### Boost Software License 1.0
+
+Used by:
+- clipboard-win 5.4.3 (https://github.com/DoumanAsh/clipboard-win)
+
+```text
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### Creative Commons Zero v1.0 Universal
+
+Used by:
+- notify 8.2.1 (https://github.com/notify-rs/notify.git)
+
+```text
+Creative Commons CC0 1.0 Universal
+
+<<beginOptional;name=ccOptionalIntro>> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. <<endOptional>>
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
+
+ ii. moral rights retained by the original author(s) and/or performer(s);
+
+ iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
+
+ iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
+
+ v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
+
+ vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
+
+ vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
+
+ b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
+
+ c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
+
+ d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
+```
+
+### ISC License
+
+Used by:
+- inotify-sys 0.1.8 (https://github.com/hannobraun/inotify-sys)
+
+```text
+Copyright (c) Hanno Braun and contributors
+
+Permission to use, copy, modify, and/or distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright notice
+and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+```
+
+### ISC License
+
+Used by:
+- inotify 0.11.5 (https://github.com/hannobraun/inotify-rs)
+
+```text
+Copyright (c) Hanno Braun and contributors
+
+Permission to use, copy, modify, and/or distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright notice
+and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+
+```
+
+### ISC License
+
+Used by:
+- libloading 0.8.9 (https://github.com/nagisa/rust_libloading/)
+
+```text
+Copyright © 2015, Simonas Kazlauskas
+
+Permission to use, copy, modify, and/or distribute this software for any purpose with or without
+fee is hereby granted, provided that the above copyright notice and this permission notice appear
+in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
+AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- uds_windows 1.2.1 (https://github.com/haraldh/rust_uds_windows)
+
+```text
+ MIT License
+
+ Copyright (c) Microsoft Corporation. All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
+
+```
+
+### MIT License
+
+Used by:
+- atomic-waker 1.1.2 (https://github.com/smol-rs/atomic-waker)
+- futures-lite 2.6.1 (https://github.com/smol-rs/futures-lite)
+
+```text
+===============================================================================
+
+Copyright (c) 2016 Alex Crichton
+Copyright (c) 2017 The Tokio Authors
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+===============================================================================
+
+Copyright (c) 2016 Alex Crichton
+Copyright (c) 2017 The Tokio Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- rayon-core 1.13.0 (https://github.com/rayon-rs/rayon)
+- rayon 1.12.0 (https://github.com/rayon-rs/rayon)
+
+```text
+Copyright (c) 2010 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- core-foundation-sys 0.8.7 (https://github.com/servo/core-foundation-rs)
+- core-foundation 0.9.4 (https://github.com/servo/core-foundation-rs)
+- core-graphics-types 0.1.3 (https://github.com/servo/core-foundation-rs)
+- core-graphics 0.23.2 (https://github.com/servo/core-foundation-rs)
+- euclid 0.22.14 (https://github.com/servo/euclid)
+
+```text
+Copyright (c) 2012-2013 Mozilla Foundation
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- hex 0.4.3 (https://github.com/KokaKiwi/rust-hex)
+
+```text
+Copyright (c) 2013-2014 The Rust Project Developers.
+Copyright (c) 2015-2020 The rust-hex Developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- percent-encoding 2.3.2 (https://github.com/servo/rust-url/)
+
+```text
+Copyright (c) 2013-2025 The rust-url developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- cfg-if 1.0.5 (https://github.com/rust-lang/cfg-if)
+- scoped-tls 1.0.1 (https://github.com/alexcrichton/scoped-tls)
+
+```text
+Copyright (c) 2014 Alex Crichton
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- mio 1.2.4 (https://github.com/tokio-rs/mio)
+
+```text
+Copyright (c) 2014 Carl Lerche and other MIO contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- errno 0.3.14 (https://github.com/lambda-fairy/rust-errno)
+
+```text
+Copyright (c) 2014 Chris Wong
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- bitflags 1.3.2 (https://github.com/bitflags/bitflags)
+- bitflags 2.13.2 (https://github.com/bitflags/bitflags)
+- log 0.4.35 (https://github.com/rust-lang/log)
+- num-traits 0.2.19 (https://github.com/rust-num/num-traits)
+
+```text
+Copyright (c) 2014 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- uuid 1.29.0 (https://github.com/uuid-rs/uuid)
+
+```text
+Copyright (c) 2014 The Rust Project Developers
+Copyright (c) 2018 Ashley Mannix, Christopher Armstrong, Dylan DPC, Hunar Roop Kahlon
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- nom 8.0.0 (https://github.com/rust-bakery/nom)
+
+```text
+Copyright (c) 2014-2019 Geoffroy Couprie
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- flate2 1.1.10 (https://github.com/rust-lang/flate2-rs)
+
+```text
+Copyright (c) 2014-2026 Alex Crichton
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- either 1.19.0 (https://github.com/rayon-rs/either)
+- itertools 0.15.0 (https://github.com/rust-itertools/itertools)
+- petgraph 0.8.3 (https://github.com/petgraph/petgraph)
+
+```text
+Copyright (c) 2015
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- wayland-backend 0.3.17 (https://github.com/smithay/wayland-rs)
+- wayland-client 0.31.15 (https://github.com/smithay/wayland-rs)
+- wayland-cursor 0.31.14 (https://github.com/smithay/wayland-rs)
+- wayland-protocols-experimental 20250721.0.1 (https://github.com/smithay/wayland-rs)
+- wayland-protocols-misc 0.3.12 (https://github.com/smithay/wayland-rs)
+- wayland-protocols-plasma 0.3.12 (https://github.com/smithay/wayland-rs)
+- wayland-protocols-wlr 0.3.12 (https://github.com/smithay/wayland-rs)
+- wayland-protocols 0.32.13 (https://github.com/smithay/wayland-rs)
+- wayland-scanner 0.31.11 (https://github.com/smithay/wayland-rs)
+- wayland-sys 0.31.11 (https://github.com/smithay/wayland-rs)
+
+```text
+Copyright (c) 2015 Elinor Berger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- ordered-float 5.5.1 (https://github.com/reem/rust-ordered-float)
+
+```text
+Copyright (c) 2015 Jonathan Reem
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- tempfile 3.27.0 (https://github.com/Stebalien/tempfile)
+
+```text
+Copyright (c) 2015 Steven Allen
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- heck 0.5.0 (https://github.com/withoutboats/heck)
+- unicode-properties 0.1.5 (https://github.com/unicode-rs/unicode-properties)
+- unicode-segmentation 1.13.3 (https://github.com/unicode-rs/unicode-segmentation)
+- unicode-width 0.2.3 (https://github.com/unicode-rs/unicode-width)
+
+```text
+Copyright (c) 2015 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- quick-error 2.0.1 (http://github.com/tailhook/quick-error)
+
+```text
+Copyright (c) 2015 The quick-error Developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- dlib 0.5.3 (https://github.com/elinorbgr/dlib)
+
+```text
+Copyright (c) 2015 Victor Berger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- png 0.18.1 (https://github.com/image-rs/image-png)
+
+```text
+Copyright (c) 2015 nwin
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- fixedbitset 0.5.7 (https://github.com/petgraph/fixedbitset)
+
+```text
+Copyright (c) 2015-2017
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- ash 0.38.0+1.3.281 (https://github.com/ash-rs/ash)
+
+```text
+Copyright (c) 2016 ASH
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- futures-core 0.3.34 (https://github.com/rust-lang/futures-rs)
+- futures-io 0.3.34 (https://github.com/rust-lang/futures-rs)
+- futures-macro 0.3.34 (https://github.com/rust-lang/futures-rs)
+- futures-task 0.3.34 (https://github.com/rust-lang/futures-rs)
+- futures-util 0.3.34 (https://github.com/rust-lang/futures-rs)
+
+```text
+Copyright (c) 2016 Alex Crichton
+Copyright (c) 2017 The Tokio Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- hashbrown 0.15.5 (https://github.com/rust-lang/hashbrown)
+- hashbrown 0.16.1 (https://github.com/rust-lang/hashbrown)
+- hashbrown 0.17.1 (https://github.com/rust-lang/hashbrown)
+
+```text
+Copyright (c) 2016 Amanieu d'Antras
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- utf8parse 0.2.2 (https://github.com/alacritty/vte)
+
+```text
+Copyright (c) 2016 Joe Wilm
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- lock_api 0.4.14 (https://github.com/Amanieu/parking_lot)
+- parking_lot 0.12.5 (https://github.com/Amanieu/parking_lot)
+- parking_lot_core 0.9.12 (https://github.com/Amanieu/parking_lot)
+
+```text
+Copyright (c) 2016 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- indexmap 2.14.2 (https://github.com/indexmap-rs/indexmap)
+
+```text
+Copyright (c) 2016--2017
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- equivalent 1.0.3 (https://github.com/indexmap-rs/equivalent)
+
+```text
+Copyright (c) 2016--2023
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- scopeguard 1.2.0 (https://github.com/bluss/scopeguard)
+
+```text
+Copyright (c) 2016-2019 Ulrik Sverdrup "bluss" and scopeguard developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- memoffset 0.9.1 (https://github.com/Gilnaa/memoffset)
+
+```text
+Copyright (c) 2017 Gilad Naaman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- enumflags2_derive 0.7.12 (https://github.com/meithecatte/enumflags2)
+
+```text
+Copyright (c) 2017 Maik Klein
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- foreign-types-macros 0.2.4 (https://github.com/sfackler/foreign-types)
+- foreign-types-shared 0.3.1 (https://github.com/sfackler/foreign-types)
+- foreign-types 0.5.0 (https://github.com/sfackler/foreign-types)
+
+```text
+Copyright (c) 2017 The foreign-types Developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- signal-hook-registry 1.4.8 (https://github.com/vorner/signal-hook)
+
+```text
+Copyright (c) 2017 tokio-jsonrpc developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- enumflags2 0.7.12 (https://github.com/meithecatte/enumflags2)
+
+```text
+Copyright (c) 2017-2023 Maik Klein, Maja Kądziołka
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- smithay-clipboard 0.7.3 (https://github.com/smithay/smithay-clipboard)
+
+```text
+Copyright (c) 2018 Lucas Timmins & Victor Berger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- fearless_simd 0.4.1 (https://github.com/linebender/fearless_simd)
+- kurbo 0.13.1 (https://github.com/linebender/kurbo)
+- peniko 0.6.1 (https://github.com/linebender/peniko)
+- polycool 0.4.0 (https://github.com/linebender/kurbo)
+
+```text
+Copyright (c) 2018 Raph Levien
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- smallvec 1.16.4 (https://github.com/servo/rust-smallvec)
+
+```text
+Copyright (c) 2018 The Servo Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- ahash 0.8.12 (https://github.com/tkaitchuck/ahash)
+
+```text
+Copyright (c) 2018 Tom Kaitchuck
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- smithay-client-toolkit 0.19.2 (https://github.com/smithay/client-toolkit)
+- smithay-client-toolkit 0.20.0 (https://github.com/smithay/client-toolkit)
+
+```text
+Copyright (c) 2018 Victor Berger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- calloop 0.13.0 (https://github.com/Smithay/calloop)
+- calloop 0.14.5 (https://github.com/Smithay/calloop)
+
+```text
+Copyright (c) 2018 Victor Berger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- getrandom 0.3.4 (https://github.com/rust-random/getrandom)
+
+```text
+Copyright (c) 2018-2025 The rust-random Project Developers
+Copyright (c) 2014 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- getrandom 0.4.3 (https://github.com/rust-random/getrandom)
+
+```text
+Copyright (c) 2018-2026 The rust-random Project Developers
+Copyright (c) 2014 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- slab 0.4.12 (https://github.com/tokio-rs/slab)
+
+```text
+Copyright (c) 2019 Carl Lerche
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- presser 0.3.1 (https://github.com/EmbarkStudios/presser)
+
+```text
+Copyright (c) 2019 Embark Studios
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- font-types 0.12.7 (https://github.com/googlefonts/fontations)
+- read-fonts 0.41.0 (https://github.com/googlefonts/fontations)
+- skrifa 0.44.0 (https://github.com/googlefonts/fontations)
+
+```text
+Copyright (c) 2019 Fontations Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- wl-clipboard-rs 0.9.5 (https://github.com/YaLTeR/wl-clipboard-rs)
+
+```text
+Copyright (c) 2019 Ivan Molodetskikh
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- tracing-attributes 0.1.31 (https://github.com/tokio-rs/tracing)
+- tracing-core 0.1.36 (https://github.com/tokio-rs/tracing)
+- tracing 0.1.44 (https://github.com/tokio-rs/tracing)
+
+```text
+Copyright (c) 2019 Tokio Contributors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- downcast-rs 1.2.1 (https://github.com/marcianx/downcast-rs)
+
+```text
+Copyright (c) 2020 Ashish Myles and contributors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- document-features 0.2.12 (https://github.com/slint-ui/document-features)
+
+```text
+Copyright (c) 2020 Olivier Goffart <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- litrs 1.0.1 (https://github.com/LukasKalbertodt/litrs)
+
+```text
+Copyright (c) 2020 Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- memmap2 0.9.12 (https://github.com/RazrFalcon/memmap2-rs)
+
+```text
+Copyright (c) 2020 Yevhenii Reizner
+Copyright (c) 2015 Dan Burkert
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- pollster 1.0.1 (https://github.com/zesterer/pollster)
+
+```text
+Copyright (c) 2020-2021 Joshua Barretto
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- gpu-allocator 0.28.0 (https://github.com/Traverse-Research/gpu-allocator)
+
+```text
+Copyright (c) 2021 Traverse Research B.V.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- renderdoc-sys 1.1.0 (https://github.com/ebkalderon/renderdoc-rs)
+
+```text
+Copyright (c) 2022 Eyal Kalderon
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- atspi-common 0.13.0 (https://github.com/odilia-app/atspi)
+- atspi-proxies 0.13.0 (https://github.com/odilia-app/atspi)
+- atspi 0.29.0 (https://github.com/odilia-app/atspi)
+
+```text
+Copyright (c) 2022 Tait Hoyem <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- xkeysym 0.2.1 (https://github.com/notgull/xkeysym)
+
+```text
+Copyright (c) 2022-2023 John Nunley
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- calloop-wayland-source 0.3.0 (https://github.com/smithay/calloop-wayland-source)
+- calloop-wayland-source 0.4.1 (https://github.com/smithay/calloop-wayland-source)
+
+```text
+Copyright (c) 2023 Kirill Chibisov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- cursor-icon 1.2.0 (https://github.com/rust-windowing/cursor-icon)
+- wayland-csd-frame 0.3.0 (https://github.com/rust-windowing/wayland-csd-frame)
+
+```text
+Copyright (c) 2023 Kirill Chibisov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- notify-types 2.2.0 (https://github.com/notify-rs/notify.git)
+
+```text
+Copyright (c) 2023 Notify Contributors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- bit-vec 0.9.1 (https://github.com/contain-rs/bit-vec)
+
+```text
+Copyright (c) 2023 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- zbus 5.19.0 (https://github.com/z-galaxy/zbus/)
+- zbus_macros 5.19.0 (https://github.com/z-galaxy/zbus/)
+- zbus_names 4.3.5 (https://github.com/z-galaxy/zbus/)
+- zbus_xml 5.2.1 (https://github.com/z-galaxy/zbus/)
+- zvariant 5.15.1 (https://github.com/z-galaxy/zbus/)
+- zvariant_derive 5.15.1 (https://github.com/z-galaxy/zbus/)
+
+```text
+Copyright (c) 2024 Zeeshan Ali Khan & zbus contributors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- bit-set 0.10.0 (https://github.com/contain-rs/bit-set)
+
+```text
+Copyright (c) 2026 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- zcheapstr 1.2.0 (https://github.com/z-galaxy/zcheapstr/)
+
+```text
+Copyright (c) 2026 Zeeshan Ali Khan & zcheapstr contributors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- anstream 1.0.0 (https://github.com/rust-cli/anstyle.git)
+- anstyle-parse 1.0.0 (https://github.com/rust-cli/anstyle.git)
+- anstyle-query 1.1.5 (https://github.com/rust-cli/anstyle.git)
+- anstyle-wincon 3.0.11 (https://github.com/rust-cli/anstyle.git)
+- anstyle 1.0.14 (https://github.com/rust-cli/anstyle.git)
+- clap 4.6.7 (https://github.com/clap-rs/clap)
+- clap_builder 4.6.7 (https://github.com/clap-rs/clap)
+- clap_derive 4.6.7 (https://github.com/clap-rs/clap)
+- clap_lex 1.1.1 (https://github.com/clap-rs/clap)
+- colorchoice 1.0.5 (https://github.com/rust-cli/anstyle.git)
+- is_terminal_polyfill 1.70.2 (https://github.com/polyfill-rs/is_terminal_polyfill)
+- once_cell_polyfill 1.70.2 (https://github.com/polyfill-rs/once_cell_polyfill)
+- toml_datetime 1.1.2+spec-1.1.0 (https://github.com/toml-rs/toml)
+- toml_edit 0.25.17+spec-1.1.0 (https://github.com/toml-rs/toml)
+- toml_parser 1.1.5+spec-1.1.0 (https://github.com/toml-rs/toml)
+
+```text
+Copyright (c) Individual contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- libc 0.2.191 (https://github.com/rust-lang/libc)
+
+```text
+Copyright (c) The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- arrayvec 0.7.8 (https://github.com/bluss/arrayvec)
+
+```text
+Copyright (c) Ulrik Sverdrup "bluss" 2015-2023
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- nohash-hasher 0.2.0 (https://github.com/paritytech/nohash-hasher)
+
+```text
+Copyright 2018 Parity Technologies (UK) Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- as-raw-xcb-connection 1.0.1 (https://github.com/psychon/as-raw-xcb-connection)
+
+```text
+Copyright 2019 as-raw-xcb-connection Contributers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- x11rb-protocol 0.13.2 (https://github.com/psychon/x11rb)
+- x11rb 0.13.2 (https://github.com/psychon/x11rb)
+
+```text
+Copyright 2019 x11rb Contributers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- vello_common 0.2.0 (https://github.com/linebender/vello)
+- vello_cpu 0.2.0 (https://github.com/linebender/vello)
+
+```text
+Copyright 2020 the Vello Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- zerocopy-derive 0.8.63 (https://github.com/google/zerocopy)
+- zerocopy 0.8.63 (https://github.com/google/zerocopy)
+
+```text
+Copyright 2023 The Fuchsia Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+```
+
+### MIT License
+
+Used by:
+- wayland-protocols 0.32.13 (https://github.com/smithay/wayland-rs)
+
+```text
+Copyright © 2008-2013 Kristian Høgsberg
+Copyright © 2010-2013 Intel Corporation
+Copyright © 2013 Rafael Antognolli
+Copyright © 2013 Jasper St. Pierre
+Copyright © 2014 Jonas Ådahl
+Copyright © 2014 Jason Ekstrand
+Copyright © 2014-2015 Collabora, Ltd.
+Copyright © 2015 Red Hat Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice (including the next
+paragraph) shall be included in all copies or substantial portions of the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+---
+
+The above is the version of the MIT "Expat" License used by X.org:
+
+ http://cgit.freedesktop.org/xorg/xserver/tree/COPYING
+
+```
+
+### MIT License
+
+Used by:
+- fax 0.2.7 (https://github.com/pdf-rs/fax)
+
+```text
+Copyright © 2021 The pdf-rs contributers.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- epaint_default_fonts 0.37.0 (https://github.com/emilk/egui/tree/main/crates/epaint_default_fonts)
+
+```text
+MIT License
+
+Copyright (c) 2014 John Slegers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- tree_magic_mini 3.2.2 (https://github.com/mbrubeck/tree_magic/)
+
+```text
+MIT License
+
+Copyright (c) 2017 Aaron Hancock
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- static_assertions 1.1.0 (https://github.com/nvzqz/static-assertions-rs)
+
+```text
+MIT License
+
+Copyright (c) 2017 Nikolai Vazquez
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- tiff 0.11.3 (https://github.com/image-rs/image-tiff)
+
+```text
+MIT License
+
+Copyright (c) 2018 PistonDevelopers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- crc32fast 1.5.4 (https://github.com/srijs/rust-crc32fast)
+
+```text
+MIT License
+
+Copyright (c) 2018 Sam Rijs, Alex Crichton and contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- bytemuck 1.25.2 (https://github.com/Lokathor/bytemuck)
+- bytemuck_derive 1.12.1 (https://github.com/Lokathor/bytemuck)
+
+```text
+MIT License
+
+Copyright (c) 2019 Daniel "Lokathor" Gee.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- raw-window-handle 0.6.2 (https://github.com/rust-windowing/raw-window-handle)
+
+```text
+MIT License
+
+Copyright (c) 2019 Osspial
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- xcursor 0.3.11 (https://github.com/esposm03/xcursor-rs)
+
+```text
+MIT License
+
+Copyright (c) 2020 Samuele Esposito
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- arboard 3.7.0 (https://github.com/1Password/arboard)
+
+```text
+MIT License
+
+Copyright (c) 2022 The Arboard contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- range-alloc 0.1.5 (https://github.com/gfx-rs/range-alloc)
+
+```text
+MIT License
+
+Copyright (c) 2023 The gfx-rs developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- web-time 1.1.0 (https://github.com/daxpedda/web-time)
+
+```text
+MIT License
+
+Copyright (c) 2023 dAxpeDDa
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- naga-types 30.0.1 (https://github.com/gfx-rs/wgpu)
+- naga 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-core-deps-apple 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-core-deps-windows-linux-android 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-core 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-hal 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-naga-bridge 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu-types 30.0.1 (https://github.com/gfx-rs/wgpu)
+- wgpu 30.0.1 (https://github.com/gfx-rs/wgpu)
+
+```text
+MIT License
+
+Copyright (c) 2025 The gfx-rs developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- accesskit 0.25.2 (https://github.com/AccessKit/accesskit)
+- accesskit_atspi_common 0.21.1 (https://github.com/AccessKit/accesskit)
+- accesskit_consumer 0.39.2 (https://github.com/AccessKit/accesskit)
+- accesskit_macos 0.27.2 (https://github.com/AccessKit/accesskit)
+- accesskit_unix 0.24.1 (https://github.com/AccessKit/accesskit)
+- accesskit_windows 0.35.2 (https://github.com/AccessKit/accesskit)
+- block2 0.5.1 (https://github.com/madsmtm/objc2)
+- block2 0.6.2 (https://github.com/madsmtm/objc2)
+- dispatch 0.2.0 (http://github.com/SSheldon/rust-dispatch)
+- dpi 0.1.2 (https://github.com/rust-windowing/winit)
+- ecolor 0.37.0 (https://github.com/emilk/egui)
+- eframe 0.37.0 (https://github.com/emilk/egui/tree/main/crates/eframe)
+- egui-wgpu 0.37.0 (https://github.com/emilk/egui/tree/main/crates/egui-wgpu)
+- egui-winit 0.37.0 (https://github.com/emilk/egui/tree/main/crates/egui-winit)
+- egui 0.37.0 (https://github.com/emilk/egui)
+- emath 0.37.0 (https://github.com/emilk/egui/tree/main/crates/emath)
+- epaint 0.37.0 (https://github.com/emilk/egui/tree/main/crates/epaint)
+- libm 0.2.16 (https://github.com/rust-lang/compiler-builtins)
+- objc-sys 0.3.5 (https://github.com/madsmtm/objc2)
+- objc2-app-kit 0.2.2 (https://github.com/madsmtm/objc2)
+- objc2-app-kit 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-cloud-kit 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-data 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-foundation 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-graphics 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-image 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-services 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-text 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-core-video 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-encode 4.1.0 (https://github.com/madsmtm/objc2)
+- objc2-foundation 0.2.2 (https://github.com/madsmtm/objc2)
+- objc2-foundation 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-metal 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2-quartz-core 0.3.2 (https://github.com/madsmtm/objc2)
+- objc2 0.5.3 (https://github.com/madsmtm/objc2)
+- objc2 0.6.5 (https://github.com/madsmtm/objc2)
+- profiling 1.0.18 (https://github.com/aclysma/profiling)
+- skia-bindings 0.157.0 (https://github.com/rust-skia/rust-skia)
+- skia-safe 0.157.0 (https://github.com/rust-skia/rust-skia)
+- type-map 0.5.1 (https://github.com/kardeiz/type-map)
+- windows-collections 0.3.2 (https://github.com/microsoft/windows-rs)
+- windows-core 0.62.2 (https://github.com/microsoft/windows-rs)
+- windows-future 0.3.2 (https://github.com/microsoft/windows-rs)
+- windows-implement 0.60.2 (https://github.com/microsoft/windows-rs)
+- windows-interface 0.59.3 (https://github.com/microsoft/windows-rs)
+- windows-link 0.2.1 (https://github.com/microsoft/windows-rs)
+- windows-numerics 0.3.1 (https://github.com/microsoft/windows-rs)
+- windows-result 0.4.1 (https://github.com/microsoft/windows-rs)
+- windows-strings 0.5.1 (https://github.com/microsoft/windows-rs)
+- windows-sys 0.52.0 (https://github.com/microsoft/windows-rs)
+- windows-sys 0.59.0 (https://github.com/microsoft/windows-rs)
+- windows-sys 0.61.2 (https://github.com/microsoft/windows-rs)
+- windows-targets 0.52.6 (https://github.com/microsoft/windows-rs)
+- windows-threading 0.2.1 (https://github.com/microsoft/windows-rs)
+- windows 0.62.2 (https://github.com/microsoft/windows-rs)
+- windows_x86_64_gnu 0.52.6 (https://github.com/microsoft/windows-rs)
+- windows_x86_64_msvc 0.52.6 (https://github.com/microsoft/windows-rs)
+
+```text
+MIT License
+
+Copyright (c) <year> <copyright holders>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- simd-adler32 0.3.10 (https://github.com/mcountryman/simd-adler32)
+
+```text
+MIT License
+
+Copyright (c) [2021] [Marvin Countryman]
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- zune-core 0.5.3 (https://github.com/etemesi254/zune-image)
+- zune-jpeg 0.5.15 (https://github.com/etemesi254/zune-image/tree/dev/crates/zune-jpeg)
+
+```text
+MIT License
+
+Copyright (c) zune-image developers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- miniz_oxide 0.8.9 (https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide)
+- miniz_oxide 0.9.1 (https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide)
+
+```text
+MIT License
+
+Copyright 2013-2014 RAD Game Tools and Valve Software
+Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
+Copyright (c) 2017 Frommi
+Copyright (c) 2017-2024 oyvindln
+
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- miniz_oxide 0.8.9 (https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide)
+- miniz_oxide 0.9.1 (https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide)
+
+```text
+MIT License
+
+Copyright 2013-2014 RAD Game Tools and Valve Software
+Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
+Copyright (c) 2017 Frommi
+Copyright (c) 2017-2024 oyvindln
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- fdeflate 0.3.7 (https://github.com/image-rs/fdeflate)
+- image 0.25.10 (https://github.com/image-rs/image)
+
+```text
+MIT License
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- color 0.3.3 (https://github.com/linebender/color)
+- half 2.7.1 (https://github.com/VoidStarKat/half-rs)
+- linebender_resource_handle 0.1.1 (https://github.com/linebender/raw_resource_handle)
+
+```text
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- wayland-protocols-plasma 0.3.12 (https://github.com/smithay/wayland-rs)
+
+```text
+MIT License Copyright (c) <year> <copyright holders>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice (including the next
+paragraph) shall be included in all copies or substantial portions of the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
+OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- rustc-hash 2.1.3 (https://github.com/rust-lang/rustc-hash)
+
+```text
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- adler2 2.0.1 (https://github.com/oyvindln/adler2)
+- anyhow 1.0.104 (https://github.com/dtolnay/anyhow)
+- async-channel 2.5.0 (https://github.com/smol-rs/async-channel)
+- async-executor 1.14.0 (https://github.com/smol-rs/async-executor)
+- async-io 2.6.0 (https://github.com/smol-rs/async-io)
+- async-lock 3.4.2 (https://github.com/smol-rs/async-lock)
+- async-process 2.5.0 (https://github.com/smol-rs/async-process)
+- async-signal 0.2.14 (https://github.com/smol-rs/async-signal)
+- async-task 4.7.1 (https://github.com/smol-rs/async-task)
+- async-trait 0.1.92 (https://github.com/dtolnay/async-trait)
+- atomic-waker 1.1.2 (https://github.com/smol-rs/atomic-waker)
+- blocking 1.7.0 (https://github.com/smol-rs/blocking)
+- concurrent-queue 2.5.0 (https://github.com/smol-rs/concurrent-queue)
+- endi 1.1.1 (https://github.com/zeenix/endi)
+- event-listener-strategy 0.5.4 (https://github.com/smol-rs/event-listener-strategy)
+- event-listener 5.4.2 (https://github.com/smol-rs/event-listener)
+- fastrand 2.5.0 (https://github.com/smol-rs/fastrand)
+- futures-lite 2.6.1 (https://github.com/smol-rs/futures-lite)
+- itoa 1.0.18 (https://github.com/dtolnay/itoa)
+- khronos-egl 6.0.0 (https://github.com/timothee-haudebourg/khronos-egl)
+- linux-raw-sys 0.12.1 (https://github.com/sunfishcode/linux-raw-sys)
+- linux-raw-sys 0.4.15 (https://github.com/sunfishcode/linux-raw-sys)
+- once_cell 1.21.4 (https://github.com/matklad/once_cell)
+- ordered-stream 0.2.0 (https://github.com/danieldg/ordered-stream)
+- parking 2.2.1 (https://github.com/smol-rs/parking)
+- pin-project-lite 0.2.17 (https://github.com/taiki-e/pin-project-lite)
+- piper 0.2.5 (https://github.com/smol-rs/piper)
+- polling 3.11.0 (https://github.com/smol-rs/polling)
+- proc-macro-crate 3.5.0 (https://github.com/bkchr/proc-macro-crate)
+- proc-macro2 1.0.107 (https://github.com/dtolnay/proc-macro2)
+- quote 1.0.47 (https://github.com/dtolnay/quote)
+- rustc-hash 1.1.0 (https://github.com/rust-lang-nursery/rustc-hash)
+- rustix 0.38.44 (https://github.com/bytecodealliance/rustix)
+- rustix 1.1.6 (https://github.com/bytecodealliance/rustix)
+- serde 1.0.229 (https://github.com/serde-rs/serde)
+- serde_core 1.0.229 (https://github.com/serde-rs/serde)
+- serde_derive 1.0.229 (https://github.com/serde-rs/serde)
+- serde_json 1.0.154 (https://github.com/serde-rs/json)
+- serde_repr 0.1.21 (https://github.com/dtolnay/serde-repr)
+- smol_str 0.2.2 (https://github.com/rust-analyzer/smol_str)
+- syn 2.0.119 (https://github.com/dtolnay/syn)
+- syn 3.0.9 (https://github.com/dtolnay/syn)
+- thiserror-impl 1.0.69 (https://github.com/dtolnay/thiserror)
+- thiserror-impl 2.0.21 (https://github.com/dtolnay/thiserror)
+- thiserror 1.0.69 (https://github.com/dtolnay/thiserror)
+- thiserror 2.0.21 (https://github.com/dtolnay/thiserror)
+- unicode-ident 1.0.27 (https://github.com/dtolnay/unicode-ident)
+- x11-dl 2.21.0 (https://github.com/AltF02/x11-rs.git)
+- zbus-lockstep-macros 0.5.2 (https://github.com/luukvanderduim/zbus-lockstep)
+- zbus-lockstep 0.5.2 (https://github.com/luukvanderduim/zbus-lockstep)
+- zmij 1.0.23 (https://github.com/dtolnay/zmij)
+- zvariant_utils 4.2.0 (https://github.com/z-galaxy/zbus/)
+
+```text
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- async-recursion 1.2.0 (https://github.com/dcchut/async-recursion)
+- glow 0.17.0 (https://github.com/grovesNL/glow)
+
+```text
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+```
+
+### MIT License
+
+Used by:
+- allocator-api2 0.2.21 (https://github.com/zakarumych/allocator-api2)
+
+```text
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- winnow 1.0.4 (https://github.com/winnow-rs/winnow)
+
+```text
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- raw-window-metal 1.1.0 (https://github.com/rust-windowing/raw-window-metal)
+- siphasher 1.0.4 (https://github.com/jedisct1/rust-siphash)
+
+```text
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- tracing-core 0.1.36 (https://github.com/tokio-rs/tracing)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2014 Mathijs van de Nes
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- phf 0.14.0 (https://github.com/rust-phf/rust-phf)
+- phf_generator 0.14.0 (https://github.com/rust-phf/rust-phf)
+- phf_macros 0.14.0 (https://github.com/rust-phf/rust-phf)
+- phf_shared 0.14.0 (https://github.com/rust-phf/rust-phf)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2014-2022 Steven Fackler, Yuki Okushi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- byteorder-lite 0.1.0 (https://github.com/image-rs/byteorder-lite)
+- memchr 2.8.3 (https://github.com/BurntSushi/memchr)
+- walkdir 2.5.0 (https://github.com/BurntSushi/walkdir)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2015 Andrew Gallant
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- strsim 0.11.1 (https://github.com/rapidfuzz/strsim-rs)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2015 Danny Guo
+Copyright (c) 2016 Titus Wormer <[email protected]>
+Copyright (c) 2018 Akash Kurdekar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- same-file 1.0.6 (https://github.com/BurntSushi/same-file)
+- winapi-util 0.1.11 (https://github.com/BurntSushi/winapi-util)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2017 Andrew Gallant
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- guillotiere 0.7.0 (https://github.com/nical/guillotiere)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2019 Nicolas Silva
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- crossbeam-deque 0.8.8 (https://github.com/crossbeam-rs/crossbeam)
+- crossbeam-epoch 0.9.21 (https://github.com/crossbeam-rs/crossbeam)
+- crossbeam-utils 0.8.23 (https://github.com/crossbeam-rs/crossbeam)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2019 The Crossbeam Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- async-broadcast 0.7.2 (https://github.com/smol-rs/async-broadcast)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2020 Yoshua Wuyts
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- xkbcommon-dl 0.4.2 (https://github.com/rust-windowing/xkbcommon-dl)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2023 Kirill Chibisov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- harfrust 0.12.0 (https://github.com/harfbuzz/harfrust)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) HarfBuzz developers
+Copyright (c) 2020 Yevhenii Reizner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- weezl 0.1.12 (https://github.com/image-rs/weezl)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) HeroicKatora 2020
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+```
+
+### MIT License
+
+Used by:
+- os_pipe 1.2.3 (https://github.com/oconnor663/os_pipe.rs)
+
+```text
+The MIT License (MIT)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### MIT License
+
+Used by:
+- quick-xml 0.41.0 (https://github.com/tafia/quick-xml)
+
+```text
+The MIT License (MIT)
+
+Copyright (c) 2016 Johann Tuffe
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+```
+
+### SIL Open Font License 1.1
+
+Used by:
+- epaint_default_fonts 0.37.0 (https://github.com/emilk/egui/tree/main/crates/epaint_default_fonts)
+
+```text
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to
+provide a free and open framework in which fonts may be shared and
+improved in partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software
+components as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to,
+deleting, or substituting -- in part or in whole -- any of the
+components of the Original Version, by changing formats or by porting
+the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed,
+modify, redistribute, and sell modified and unmodified copies of the
+Font Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components, in
+Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the
+corresponding Copyright Holder. This restriction only applies to the
+primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created using
+the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
+```
+
+### Ubuntu Font Licence v1.0
+
+Used by:
+- epaint_default_fonts 0.37.0 (https://github.com/emilk/egui/tree/main/crates/epaint_default_fonts)
+
+```text
+-------------------------------
+UBUNTU FONT LICENCE Version 1.0
+-------------------------------
+
+PREAMBLE
+This licence allows the licensed fonts to be used, studied, modified and
+redistributed freely. The fonts, including any derivative works, can be
+bundled, embedded, and redistributed provided the terms of this licence
+are met. The fonts and derivatives, however, cannot be released under
+any other licence. The requirement for fonts to remain under this
+licence does not require any document created using the fonts or their
+derivatives to be published under this licence, as long as the primary
+purpose of the document is not to be a vehicle for the distribution of
+the fonts.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this licence and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Original Version" refers to the collection of Font Software components
+as received under this licence.
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to
+a new environment.
+
+"Copyright Holder(s)" refers to all individuals and companies who have a
+copyright ownership of the Font Software.
+
+"Substantially Changed" refers to Modified Versions which can be easily
+identified as dissimilar to the Font Software by users of the Font
+Software comparing the Original Version with the Modified Version.
+
+To "Propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification and with or without charging
+a redistribution fee), making available to the public, and in some
+countries other activities as well.
+
+PERMISSION & CONDITIONS
+This licence does not grant any rights under trademark law and all such
+rights are reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of the Font Software, to propagate the Font Software, subject to
+the below conditions:
+
+1) Each copy of the Font Software must contain the above copyright
+notice and this licence. These can be included either as stand-alone
+text files, human-readable headers or in the appropriate machine-
+readable metadata fields within text or binary files as long as those
+fields can be easily viewed by the user.
+
+2) The font name complies with the following:
+(a) The Original Version must retain its name, unmodified.
+(b) Modified Versions which are Substantially Changed must be renamed to
+avoid use of the name of the Original Version or similar names entirely.
+(c) Modified Versions which are not Substantially Changed must be
+renamed to both (i) retain the name of the Original Version and (ii) add
+additional naming elements to distinguish the Modified Version from the
+Original Version. The name of such Modified Versions must be the name of
+the Original Version, with "derivative X" where X represents the name of
+the new work, appended to that name.
+
+3) The name(s) of the Copyright Holder(s) and any contributor to the
+Font Software shall not be used to promote, endorse or advertise any
+Modified Version, except (i) as required by this licence, (ii) to
+acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
+their explicit written permission.
+
+4) The Font Software, modified or unmodified, in part or in whole, must
+be distributed entirely under this licence, and must not be distributed
+under any other licence. The requirement for fonts to remain under this
+licence does not affect any document created using the Font Software,
+except any version of the Font Software extracted from a document
+created using the Font Software may only be distributed under this
+licence.
+
+TERMINATION
+This licence becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
+DEALINGS IN THE FONT SOFTWARE.
+
+```
+
+### Unicode License v3
+
+Used by:
+- unicode-ident 1.0.27 (https://github.com/dtolnay/unicode-ident)
+
+```text
+UNICODE LICENSE V3
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright © 1991-2023 Unicode, Inc.
+
+NOTICE TO USER: Carefully read the following legal agreement. BY
+DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
+SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
+TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
+DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of data files and any associated documentation (the "Data Files") or
+software and any associated documentation (the "Software") to deal in the
+Data Files or Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, and/or sell
+copies of the Data Files or Software, and to permit persons to whom the
+Data Files or Software are furnished to do so, provided that either (a)
+this copyright and permission notice appear with all copies of the Data
+Files or Software, or (b) this copyright and permission notice appear in
+associated Documentation.
+
+THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+THIRD PARTY RIGHTS.
+
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
+BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
+OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
+FILES OR SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall
+not be used in advertising or otherwise to promote the sale, use or other
+dealings in these Data Files or Software without prior written
+authorization of the copyright holder.
+
+```
+
+### Unicode License v3
+
+Used by:
+- unicode-properties 0.1.5 (https://github.com/unicode-rs/unicode-properties)
+
+```text
+UNICODE LICENSE V3
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright © 1991-2026 Unicode, Inc.
+
+NOTICE TO USER: Carefully read the following legal agreement. BY
+DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
+SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
+TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
+DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of data files and any associated documentation (the "Data Files") or
+software and any associated documentation (the "Software") to deal in the
+Data Files or Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, and/or sell
+copies of the Data Files or Software, and to permit persons to whom the
+Data Files or Software are furnished to do so, provided that either (a)
+this copyright and permission notice appear with all copies of the Data
+Files or Software, or (b) this copyright and permission notice appear in
+associated Documentation.
+
+THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+THIRD PARTY RIGHTS.
+
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
+BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
+OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
+FILES OR SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall
+not be used in advertising or otherwise to promote the sale, use or other
+dealings in these Data Files or Software without prior written
+authorization of the copyright holder.
+
+```
+
+### zlib License
+
+Used by:
+- foldhash 0.1.5 (https://github.com/orlp/foldhash)
+- foldhash 0.2.0 (https://github.com/orlp/foldhash)
+
+```text
+Copyright (c) 2024 Orson Peters
+
+This software is provided 'as-is', without any express or implied warranty. In
+no event will the authors be held liable for any damages arising from the use of
+this software.
+
+Permission is granted to anyone to use this software for any purpose, including
+commercial applications, and to alter it and redistribute it freely, subject to
+the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must not claim
+ that you wrote the original software. If you use this software in a product,
+ an acknowledgment in the product documentation would be appreciated but is
+ not required.
+
+2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+
+3. This notice may not be removed or altered from any source distribution.
+```
+
+## Built into Skia
+
+`skia-bindings` links a prebuilt Skia (m157) with these libraries compiled in. On Linux, FreeType and fontconfig come from the system and are not shipped.
+
+### Skia
+
+The 2D library that draws every pixel. BSD 3-Clause.
+
+```text
+Copyright (c) 2011 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+```
+
+### libpng
+
+PNG decoding and encoding inside Skia.
+
+```text
+COPYRIGHT NOTICE, DISCLAIMER, and LICENSE
+=========================================
+
+PNG Reference Library License version 2
+---------------------------------------
+
+ * Copyright (c) 1995-2026 The PNG Reference Library Authors.
+ * Copyright (c) 2018-2026 Cosmin Truta.
+ * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson.
+ * Copyright (c) 1996-1997 Andreas Dilger.
+ * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+The software is supplied "as is", without warranty of any kind,
+express or implied, including, without limitation, the warranties
+of merchantability, fitness for a particular purpose, title, and
+non-infringement. In no event shall the Copyright owners, or
+anyone distributing the software, be liable for any damages or
+other liability, whether in contract, tort or otherwise, arising
+from, out of, or in connection with the software, or the use or
+other dealings in the software, even if advised of the possibility
+of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute
+this software, or portions hereof, for any purpose, without fee,
+subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you
+ use this software in a product, an acknowledgment in the product
+ documentation would be appreciated, but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and must
+ not be misrepresented as being the original software.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+
+PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35)
+-----------------------------------------------------------------------
+
+libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
+
+ Simon-Pierre Cadieux
+ Eric S. Raymond
+ Mans Rullgard
+ Cosmin Truta
+ Gilles Vollant
+ James Yu
+ Mandar Sahastrabuddhe
+ Google Inc.
+ Vadim Barkov
+
+and with the following additions to the disclaimer:
+
+ There is no warranty against interference with your enjoyment of
+ the library or against infringement. There is no warranty that our
+ efforts or the library will fulfill any of your particular purposes
+ or needs. This library is provided with all faults, and the entire
+ risk of satisfactory quality, performance, accuracy, and effort is
+ with the user.
+
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners, and
+are released under other open source licenses.
+
+libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the
+list of Contributing Authors:
+
+ Tom Lane
+ Glenn Randers-Pehrson
+ Willem van Schaik
+
+libpng versions 0.89, June 1996, through 0.96, May 1997, are
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
+
+ John Bowler
+ Kevin Bracey
+ Sam Bushell
+ Magnus Holmgren
+ Greg Roelofs
+ Tom Tanner
+
+Some files in the "scripts" directory have other copyright owners,
+but are released under this license.
+
+libpng versions 0.5, May 1995, through 0.88, January 1996, are
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+For the purposes of this copyright and license, "Contributing Authors"
+is defined as the following set of individuals:
+
+ Andreas Dilger
+ Dave Martindale
+ Guy Eric Schalnat
+ Paul Schmidt
+ Tim Wegner
+
+The PNG Reference Library is supplied "AS IS". The Contributing
+Authors and Group 42, Inc. disclaim all warranties, expressed or
+implied, including, without limitation, the warranties of
+merchantability and of fitness for any purpose. The Contributing
+Authors and Group 42, Inc. assume no liability for direct, indirect,
+incidental, special, exemplary, or consequential damages, which may
+result from the use of the PNG Reference Library, even if advised of
+the possibility of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+source code, or portions hereof, for any purpose, without fee, subject
+to the following restrictions:
+
+ 1. The origin of this source code must not be misrepresented.
+
+ 2. Altered versions must be plainly marked as such and must not
+ be misrepresented as being the original source.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+The Contributing Authors and Group 42, Inc. specifically permit,
+without fee, and encourage the use of this source code as a component
+to supporting the PNG file format in commercial products. If you use
+this source code in a product, acknowledgment is not required but would
+be appreciated.
+
+```
+
+### zlib
+
+Compression for PNG and PDF inside Skia.
+
+```text
+Copyright notice:
+
+ (C) 1995-2026 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+
+```
+
+### libjpeg-turbo
+
+JPEG decoding and encoding inside Skia. IJG, BSD 3-Clause and zlib licences.
+
+```text
+libjpeg-turbo Licenses
+======================
+
+libjpeg-turbo is covered by two compatible BSD-style open source licenses:
+
+- The IJG (Independent JPEG Group) License, which is listed in
+ [README.ijg](README.ijg)
+
+ This license applies to the libjpeg API library and associated programs,
+ including any code inherited from libjpeg and any modifications to that
+ code.
+
+- The Modified (3-clause) BSD License, which is listed below
+
+ This license applies to the TurboJPEG API library and associated programs,
+ [libspng](https://libspng.org) (which is used by cjpeg and djpeg), and the
+ build/test system.
+
+ * The TurboJPEG API library wraps the libjpeg API library, so in the context
+ of the overall TurboJPEG API library, both the terms of the IJG License and
+ the terms of the Modified (3-clause) BSD License apply.
+ * cjpeg and djpeg use libspng, so in the context of those programs, both the
+ terms of the IJG License and the terms of the Modified (3-clause) BSD
+ License apply.
+
+
+Component Licenses
+==================
+
+Some of libjpeg-turbo's modules and internal dependencies are covered by less
+restrictive licenses, but in the context of libjpeg-turbo as a whole, the terms
+of the less restrictive licenses are subsumed by either the IJG License or the
+Modified BSD License. (In other words, the terms of the less restrictive
+licenses are satisfied if the terms of the IJG and Modified BSD Licenses are
+satisfied.)
+
+- The libjpeg-turbo SIMD source code and zlib are covered by the
+ [zlib License](https://spdx.org/licenses/Zlib.html), which is subsumed by the
+ IJG License in the context of the cjpeg and djpeg programs and the libjpeg
+ API library.
+
+- Some of the libspng source code is covered by the
+ [PNG Reference Library License v2](https://spdx.org/licenses/libpng-2.0.html),
+ which is subsumed by the IJG License in the context of the cjpeg and djpeg
+ programs and the TurboJPEG API library.
+
+- Most of the libspng source code is covered by the
+ [Simplified (2-clause) BSD License](https://spdx.org/licenses/BSD-2-Clause.html),
+ which is subsumed by the Modified BSD License in the context of the cjpeg and
+ djpeg programs and the TurboJPEG API library.
+
+
+Complying with the libjpeg-turbo Licenses
+=========================================
+
+This section provides a roll-up of the libjpeg-turbo licensing terms, to the
+best of our understanding. This is not a license in and of itself. It is
+intended solely for clarification.
+
+1. If you are distributing a modified version of the libjpeg-turbo source,
+ then:
+
+ 1. You cannot alter or remove any existing copyright or license notices
+ from the source.
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 1 of the Modified BSD License
+
+ 2. You must add your own copyright notice to the header of each source
+ file you modified, so others can tell that you modified that file. (If
+ there is not an existing copyright header in that file, then you can
+ simply add a notice stating that you modified the file.)
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+ 3. You must include the IJG README file, and you must not alter any of the
+ copyright or license text in that file.
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+2. If you are distributing only libjpeg-turbo binaries without the source, or
+ if you are distributing an application that statically links with
+ libjpeg-turbo, then:
+
+ 1. Your product documentation must include a message stating:
+
+ This software is based in part on the work of the Independent JPEG
+ Group.
+
+ **Origin**
+ - Clause 2 of the IJG license
+
+ 2. If your binary distribution includes or uses the TurboJPEG API or
+ associated programs, cjpeg, or djpeg, then your product documentation
+ must include the text of the Modified BSD License (see below.)
+
+ **Origin**
+ - Clause 2 of the Modified BSD License
+
+3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
+ contributors thereof in advertising, publicity, etc.
+
+ **Origin**
+ - IJG License
+ - Clause 3 of the Modified BSD License
+
+4. The authors and distributors do not warrant libjpeg-turbo to be free of
+ defects, nor do we accept any liability for undesirable consequences
+ resulting from your use of the software.
+
+ **Origin**
+ - IJG License
+ - Modified BSD License
+
+
+The Modified (3-clause) BSD License
+===================================
+
+Copyright (C) 2009-2026 D. R. Commander<br>
+Copyright (C) 2018-2023 Randy <[email protected]>
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+- Neither the name of the libjpeg-turbo Project nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+```
+
+```text
+libjpeg-turbo note: This file has been modified by The libjpeg-turbo Project
+to include only information relevant to libjpeg-turbo, to wordsmith certain
+sections, and to remove impolitic language that existed in the libjpeg v8
+README. It is included only for reference. Please see README.md for
+information specific to libjpeg-turbo.
+
+
+The Independent JPEG Group's JPEG software
+==========================================
+
+This distribution contains a release of the Independent JPEG Group's free JPEG
+software. You are welcome to redistribute this software and to use it for any
+purpose, subject to the conditions under LEGAL ISSUES, below.
+
+This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone,
+Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson,
+Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers,
+and other members of the Independent JPEG Group.
+
+IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee
+(also known as JPEG, together with ITU-T SG16).
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ doc/usage.txt Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ doc/*.1 Unix-style man pages for programs (same info as
+ usage.txt).
+ doc/wizard.txt Advanced usage instructions for JPEG wizards only.
+ doc/change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ doc/libjpeg.txt How to use the JPEG library in your own programs.
+ src/example.c Sample code for calling the JPEG library.
+ doc/structure.txt Overview of the JPEG library's internal structure.
+ doc/coderules.txt Coding style rules --- please read if you contribute
+ code.
+
+Please read at least usage.txt. Some information can also be found in the JPEG
+FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find
+out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image encoding, decoding,
+and transcoding. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and grayscale images. JPEG's strong suit is compressing
+photographic images or other types of images that have smooth color and
+brightness transitions between neighboring pixels. Images with sharp lines or
+other abrupt features may not compress well with JPEG, and a higher JPEG
+quality may have to be used to avoid visible compression artifacts with such
+images.
+
+JPEG is normally lossy, meaning that the output pixels are not necessarily
+identical to the input pixels. However, on photographic content and other
+"smooth" images, very good compression ratios can be obtained with no visible
+compression artifacts, and extremely high compression ratios are possible if
+you are willing to sacrifice image quality (by reducing the "quality" setting
+in the compressor.)
+
+This software implements JPEG baseline, extended-sequential, progressive, and
+lossless compression processes. Provision is made for supporting all variants
+of these processes, although some uncommon parameter settings aren't
+implemented yet. We have made no provision for supporting the hierarchical
+processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats. These
+extra functions can be compiled out of the library if not required for a
+particular application.
+
+We have also included "jpegtran", a utility for lossless transcoding between
+different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple
+applications for inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+REFERENCES
+==========
+
+We recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PDF file containing a revised version of Wallace's article is
+available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best currently available description of JPEG is the textbook "JPEG Still
+Image Data Compression Standard" by William B. Pennebaker and Joan L.
+Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.
+Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG
+standards (DIS 10918-1 and draft DIS 10918-2).
+
+The original JPEG standard is divided into two parts, Part 1 being the actual
+specification, while Part 2 covers compliance testing methods. Part 1 is
+titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details, we follow the "JFIF" conventions, revision
+1.02. JFIF version 1 has been adopted as ISO/IEC 10918-5 (05/2013) and
+Recommendation ITU-T T.871 (05/2011): Information technology - Digital
+compression and coding of continuous-tone still images: JPEG File Interchange
+Format (JFIF). It is available as a free download in PDF file format from
+https://www.iso.org/standard/54989.html and http://www.itu.int/rec/T-REC-T.871.
+A PDF file of the older JFIF 1.02 specification is available at
+http://www.w3.org/Graphics/JPEG/jfif3.pdf.
+
+The TIFF 6.0 file format specification can be obtained from
+http://mirrors.ctan.org/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation
+scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious
+problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression
+tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note
+#2 (Compression tag 7). Copies of this Note can be obtained from
+http://www.ijg.org/files/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is www.ijg.org.
+The most recent released version can always be found there in
+directory "files".
+
+The JPEG FAQ (Frequently Asked Questions) article is a source of some
+general information about JPEG. It is available at
+http://www.faqs.org/faqs/jpeg-faq.
+
+
+FILE FORMAT COMPATIBILITY
+=========================
+
+This software implements ITU T.81 | ISO/IEC 10918 with some extensions from
+ITU T.871 | ISO/IEC 10918-5 (JPEG File Interchange Format-- see REFERENCES).
+Informally, the term "JPEG image" or "JPEG file" most often refers to JFIF or
+a subset thereof, but there are other formats containing the name "JPEG" that
+are incompatible with the original JPEG standard or with JFIF (for instance,
+JPEG 2000 and JPEG XR). This software therefore does not support these
+formats. Indeed, one of the original reasons for developing this free software
+was to help force convergence on a common, interoperable format standard for
+JPEG files.
+
+JFIF is a minimal or "low end" representation. TIFF/JPEG (TIFF revision 6.0 as
+modified by TIFF Technical Note #2) can be used for "high end" applications
+that need to record a lot of additional data about an image.
+
+
+TO DO
+=====
+
+Please send bug reports, offers of help, etc. to [email protected].
+
+```
+
+### Expat
+
+XML parsing inside Skia. MIT.
+
+```text
+Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper
+Copyright (c) 2001-2025 Expat maintainers
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+### Wuffs
+
+GIF decoding inside Skia. MIT and Apache-2.0.
+
+```text
+This software is distributed under the terms of both the MIT license and the
+Apache License (Version 2.0).
+
+
+MIT license
+
+Copyright 2023 The Wuffs Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+Apache 2 license
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+```
+
+## Fonts
+
+The editor shows its interface in these fonts. Ubuntu Light (Ubuntu Font Licence) and Noto Emoji (SIL Open Font License) come with egui; their licence texts are above, under epaint_default_fonts.
+
+### Phosphor icons
+
+The editor's icons. MIT.
+
+```text
+MIT License
+
+Copyright (c) 2020-2021 Phosphor Icons
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+```
+
+### Hack
+
+egui's monospace font. MIT, with the Bitstream Vera licence for the glyphs it builds on.
+
+```text
+The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
+
+The work in the DejaVu project was committed to the public domain.
+
+Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
+MIT License
+
+Copyright (c) 2018 Source Foundry Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+BITSTREAM VERA LICENSE
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
+
+The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
+
+The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
+
+```
+
+### emoji-icon-font and egui-icons
+
+egui's icon glyphs. MIT.
+
+```text
+MIT License
+
+Copyright (c) 2014 John Slegers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+```
+
+```text
+egui-icons.ttf
+
+A subset of emoji-icon-font.ttf (https://github.com/jslegers/emoji-icon-font),
+containing only the five glyphs that egui exposes as `egui::special_emojis`:
+
+ U+E618 the Android logo
+ U+E61F the Windows logo
+ U+E624 the GitHub logo
+ U+E625 the word `git`
+ U+F8FF the Apple logo
+
+No platform font has these, so egui bundles them even when the rest of
+emoji-icon-font.ttf is left out (the `monochrome_emoji_fonts` feature).
+
+Regenerate with:
+
+ pip install fonttools
+ python3 -m fontTools.subset emoji-icon-font.ttf \
+ --unicodes=E618,E61F,E624,E625,F8FF \
+ --no-hinting --desubroutinize \
+ --output-file=egui-icons.ttf
+
+The license is that of emoji-icon-font.ttf: see emoji-icon-font-mit-license.txt.
+
+```
+
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
new file mode 100644
index 0000000..e3750ef
--- /dev/null
+++ b/crates/app/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "klad-app"
+version.workspace = true
+edition.workspace = true
+license-file.workspace = true
+publish.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+bytemuck = "1.25.2"
+klad-brush = { version = "0.1.0", path = "../brush" }
+klad-core = { version = "0.1.0", path = "../core" }
+klad-render = { version = "0.1.0", path = "../render" }
+eframe = { version = "0.37.0", default-features = false, features = ["wgpu", "default_fonts", "accesskit", "clipboard", "wayland", "x11"] }
+egui = "0.37.0"
+egui-wgpu = "0.37.0"
+half = { version = "2.7.1", features = ["bytemuck"] }
+notify = "8"
+png = "0.18.1"
+pollster = "1.0.1"
+rayon = "1.12.0"
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.154"
+zstd = "0.14.3"
+
+[target.'cfg(target_os = "macos")'.dependencies]
+block2 = "0.6"
+objc2 = "0.6"
+objc2-app-kit = { version = "0.3", features = ["NSEvent", "NSResponder", "NSGraphics", "NSApplication", "NSWindow", "NSPanel", "NSSavePanel", "NSOpenPanel"] }
+objc2-foundation = "0.3"
+
+[dev-dependencies]
+egui_kittest = { version = "0.37.0", features = ["wgpu"] }
diff --git a/crates/app/assets/Phosphor-LICENSE b/crates/app/assets/Phosphor-LICENSE
new file mode 100644
index 0000000..c04a19d
--- /dev/null
+++ b/crates/app/assets/Phosphor-LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020-2021 Phosphor Icons
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/crates/app/assets/Phosphor.ttf b/crates/app/assets/Phosphor.ttf
new file mode 100644
index 0000000..7c1b8a7
Binary files /dev/null and b/crates/app/assets/Phosphor.ttf differ
diff --git a/crates/app/src/canvas.wgsl b/crates/app/src/canvas.wgsl
new file mode 100644
index 0000000..4deee32
--- /dev/null
+++ b/crates/app/src/canvas.wgsl
@@ -0,0 +1,40 @@
+struct View {
+ a: vec4<f32>,
+ b: vec4<f32>,
+ c: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> view: View;
+@group(0) @binding(1) var canvas_tex: texture_2d<f32>;
+@group(0) @binding(2) var canvas_sampler: sampler;
+
+struct Out {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) index: u32) -> Out {
+ var corners = array<vec2<f32>, 6>(
+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
+ vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0),
+ );
+ let uv = corners[index];
+ let p = uv * view.c.xy;
+ let px = vec2<f32>(
+ view.a.x * p.x + view.a.y * p.y + view.b.x,
+ view.a.z * p.x + view.a.w * p.y + view.b.y,
+ );
+ var out: Out;
+ out.pos = vec4<f32>(px.x / view.b.z * 2.0 - 1.0, 1.0 - px.y / view.b.w * 2.0, 0.0, 1.0);
+ out.uv = uv;
+ return out;
+}
+
+@fragment
+fn fs_main(in: Out) -> @location(0) vec4<f32> {
+ let color = textureSample(canvas_tex, canvas_sampler, in.uv);
+ let cell = vec2<i32>(floor(in.pos.xy / view.c.w));
+ let checker = select(0.80, 0.92, ((cell.x + cell.y) & 1) == 0);
+ return vec4<f32>(color.rgb + vec3<f32>(checker) * (1.0 - color.a), 1.0);
+}
diff --git a/crates/app/src/color.rs b/crates/app/src/color.rs
new file mode 100644
index 0000000..f427cd8
--- /dev/null
+++ b/crates/app/src/color.rs
@@ -0,0 +1,237 @@
+use egui::{Color32, Mesh, Pos2, Rect, Sense, Shape, Stroke, Vec2, pos2, vec2};
+use klad_core::color::parse_hex;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Hsva {
+ pub h: f32,
+ pub s: f32,
+ pub v: f32,
+ pub a: f32,
+}
+
+pub fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
+ let h = h.rem_euclid(1.0) * 6.0;
+ let sector = h.floor();
+ let f = h - sector;
+ let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
+ match sector as u8 {
+ 0 => [v, t, p],
+ 1 => [q, v, p],
+ 2 => [p, v, t],
+ 3 => [p, q, v],
+ 4 => [t, p, v],
+ _ => [v, p, q],
+ }
+}
+
+impl Hsva {
+ pub fn from_rgba([r, g, b, a]: [f32; 4], keep_hue: f32) -> Self {
+ let max = r.max(g).max(b);
+ let min = r.min(g).min(b);
+ let d = max - min;
+ let h = if d <= 1e-6 {
+ keep_hue
+ } else if max == r {
+ ((g - b) / d).rem_euclid(6.0) / 6.0
+ } else if max == g {
+ ((b - r) / d + 2.0) / 6.0
+ } else {
+ ((r - g) / d + 4.0) / 6.0
+ };
+ let s = if max <= 1e-6 { 0.0 } else { d / max };
+ Self { h, s, v: max, a }
+ }
+
+ pub fn rgba(&self) -> [f32; 4] {
+ let [r, g, b] = hsv_to_rgb(self.h, self.s, self.v);
+ [r, g, b, self.a]
+ }
+}
+
+pub fn color32([r, g, b, a]: [f32; 4]) -> Color32 {
+ let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ Color32::from_rgba_unmultiplied(byte(r), byte(g), byte(b), byte(a))
+}
+
+pub fn hex(rgba: [f32; 4]) -> String {
+ let [r, g, b, a] = rgba.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ if a == 255 {
+ format!("#{r:02x}{g:02x}{b:02x}")
+ } else {
+ format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
+ }
+}
+
+pub fn rgba_of(text: &str) -> Option<[f32; 4]> {
+ let trimmed = text.trim();
+ let with_hash = if trimmed.starts_with('#') {
+ trimmed.to_string()
+ } else {
+ format!("#{trimmed}")
+ };
+ parse_hex(&with_hash).ok()
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum Part {
+ Ring,
+ Square,
+}
+
+fn square(center: Pos2, inner: f32) -> Rect {
+ Rect::from_center_size(center, Vec2::splat(inner * std::f32::consts::SQRT_2 - 8.0))
+}
+
+pub fn picker(ui: &mut egui::Ui, color: &mut Hsva, size: f32) -> bool {
+ let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), Sense::click_and_drag());
+ let center = rect.center();
+ let outer = size / 2.0 - 1.0;
+ let inner = outer - (size * 0.09).max(10.0);
+ let sv = square(center, inner);
+ let id = response.id.with("part");
+ let mut changed = false;
+ if let Some(pos) = response.interact_pointer_pos() {
+ if response.drag_started() || response.clicked() || ui.data(|d| d.get_temp::<u8>(id)).is_none() {
+ let d = (pos - center).length();
+ let part = if d >= inner - 2.0 && d <= outer + 4.0 {
+ Some(Part::Ring)
+ } else if sv.expand(4.0).contains(pos) {
+ Some(Part::Square)
+ } else {
+ None
+ };
+ ui.data_mut(|data| match part {
+ Some(Part::Ring) => data.insert_temp(id, 1u8),
+ Some(Part::Square) => data.insert_temp(id, 2u8),
+ None => data.insert_temp(id, 0u8),
+ });
+ }
+ match ui.data(|d| d.get_temp::<u8>(id)) {
+ Some(1) => {
+ let d = pos - center;
+ color.h = (d.y.atan2(d.x) / std::f32::consts::TAU).rem_euclid(1.0);
+ changed = true;
+ }
+ Some(2) => {
+ color.s = ((pos.x - sv.left()) / sv.width()).clamp(0.0, 1.0);
+ color.v = 1.0 - ((pos.y - sv.top()) / sv.height()).clamp(0.0, 1.0);
+ changed = true;
+ }
+ _ => {}
+ }
+ }
+ if response.drag_stopped() || (!response.dragged() && !response.is_pointer_button_down_on()) {
+ ui.data_mut(|d| d.remove::<u8>(id));
+ }
+ let painter = ui.painter_at(rect.expand(2.0));
+ let mut ring = Mesh::default();
+ let segments = 96;
+ (0..=segments).for_each(|i| {
+ let t = i as f32 / segments as f32;
+ let angle = t * std::f32::consts::TAU;
+ let dir = vec2(angle.cos(), angle.sin());
+ let [r, g, b] = hsv_to_rgb(t, 1.0, 1.0);
+ let c = color32([r, g, b, 1.0]);
+ ring.colored_vertex(center + dir * inner, c);
+ ring.colored_vertex(center + dir * outer, c);
+ if i > 0 {
+ let k = (i as u32) * 2;
+ ring.add_triangle(k - 2, k - 1, k);
+ ring.add_triangle(k - 1, k + 1, k);
+ }
+ });
+ painter.add(Shape::mesh(ring));
+ let mut field = Mesh::default();
+ let cells = 16;
+ (0..=cells).for_each(|j| {
+ (0..=cells).for_each(|i| {
+ let (s, v) = (i as f32 / cells as f32, 1.0 - j as f32 / cells as f32);
+ let [r, g, b] = hsv_to_rgb(color.h, s, v);
+ field.colored_vertex(
+ pos2(sv.left() + sv.width() * s, sv.top() + sv.height() * (1.0 - v)),
+ color32([r, g, b, 1.0]),
+ );
+ if i > 0 && j > 0 {
+ let at = |x: u32, y: u32| y * (cells + 1) + x;
+ field.add_triangle(at(i - 1, j - 1), at(i, j - 1), at(i, j));
+ field.add_triangle(at(i - 1, j - 1), at(i, j), at(i - 1, j));
+ }
+ });
+ });
+ painter.add(Shape::mesh(field));
+ let dark = Stroke::new(2.5, Color32::from_black_alpha(200));
+ let light = Stroke::new(1.5, Color32::WHITE);
+ let hue_at = center
+ + vec2(
+ (color.h * std::f32::consts::TAU).cos(),
+ (color.h * std::f32::consts::TAU).sin(),
+ ) * (inner + outer)
+ / 2.0;
+ painter.circle_stroke(hue_at, (outer - inner) / 2.0, dark);
+ painter.circle_stroke(hue_at, (outer - inner) / 2.0, light);
+ let sv_at = pos2(
+ sv.left() + sv.width() * color.s,
+ sv.top() + sv.height() * (1.0 - color.v),
+ );
+ painter.circle_stroke(sv_at, 5.0, dark);
+ painter.circle_stroke(sv_at, 5.0, light);
+ changed
+}
+
+pub fn swatch(ui: &mut egui::Ui, rgba: [f32; 4], selected: bool, size: f32) -> egui::Response {
+ swatch_with(ui, rgba, selected, size, Sense::click())
+}
+
+pub fn swatch_with(ui: &mut egui::Ui, rgba: [f32; 4], selected: bool, size: f32, sense: Sense) -> egui::Response {
+ let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), sense);
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, hex(rgba)));
+ let painter = ui.painter_at(rect);
+ let half = rect.width() / 2.0;
+ painter.rect_filled(rect, 2.0, Color32::from_gray(200));
+ painter.rect_filled(
+ Rect::from_min_size(rect.min, Vec2::splat(half)),
+ 0.0,
+ Color32::from_gray(140),
+ );
+ painter.rect_filled(
+ Rect::from_min_size(rect.min + Vec2::splat(half), Vec2::splat(half)),
+ 0.0,
+ Color32::from_gray(140),
+ );
+ painter.rect_filled(rect, 2.0, color32(rgba));
+ let outline = if selected {
+ Stroke::new(2.0, Color32::WHITE)
+ } else {
+ Stroke::new(1.0, Color32::from_black_alpha(160))
+ };
+ painter.rect_stroke(rect, 2.0, outline, egui::StrokeKind::Inside);
+ response
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hsv_round_trips_and_keeps_the_hue_of_greys() {
+ [
+ [1.0, 0.0, 0.0, 1.0],
+ [0.2, 0.6, 0.4, 0.5],
+ [0.95, 0.9, 0.1, 1.0],
+ [0.1, 0.2, 0.9, 1.0],
+ ]
+ .iter()
+ .for_each(|rgba| {
+ let back = Hsva::from_rgba(*rgba, 0.0).rgba();
+ assert!(
+ back.iter().zip(rgba).all(|(a, b)| (a - b).abs() < 1e-5),
+ "{rgba:?} {back:?}"
+ );
+ });
+ assert_eq!(Hsva::from_rgba([0.5, 0.5, 0.5, 1.0], 0.3).h, 0.3);
+ assert_eq!(hex([1.0, 0.5, 0.0, 1.0]), "#ff8000");
+ assert_eq!(hex([0.0, 0.0, 0.0, 0.5]), "#00000080");
+ assert_eq!(rgba_of("ff8000"), Some([1.0, 128.0 / 255.0, 0.0, 1.0]));
+ assert!(rgba_of("nope").is_none());
+ }
+}
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
new file mode 100644
index 0000000..5a15a17
--- /dev/null
+++ b/crates/app/src/commands.rs
@@ -0,0 +1,2211 @@
+use crate::theme::icon;
+use egui::{Key, Modifiers};
+use std::collections::BTreeMap;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum Cmd {
+ Brush,
+ Eraser,
+ Fill,
+ Pen,
+ ShapeTool,
+ Symmetry,
+ Parallax,
+ MakeRepeat,
+ MakeScatter,
+ MakeMirror,
+ Unwrap,
+ ImportPicture,
+ Shapes,
+ Strokes,
+ Points,
+ Note,
+ Eyedropper,
+ Smaller,
+ Bigger,
+ Pan,
+ Zoom,
+ Fit,
+ ActualSize,
+ TurnRight,
+ TurnLeft,
+ Undo,
+ Redo,
+ Delete,
+ Deselect,
+ Copy,
+ Paste,
+ SelectAll,
+ CutLasso,
+ Recolour,
+ Thinner,
+ Thicker,
+ FlipH,
+ FlipV,
+ Corner,
+ Smooth,
+ Simplify,
+ MakePath,
+ AddSwatch,
+ NewPaintLayer,
+ NewVectorLayer,
+ ToggleVisible,
+ ToggleLocked,
+ ToggleClip,
+ ToggleLockAlpha,
+ AddMask,
+ AddMaskHiding,
+ PaintMask,
+ BackToLayer,
+ RemoveMask,
+ ToggleMask,
+ TintMask,
+ OnionLayer,
+ NextFrame,
+ PrevFrame,
+ NextDrawing,
+ PrevDrawing,
+ FirstFrame,
+ LastFrame,
+ NewDrawing,
+ NewDrawingAfter,
+ Duplicate,
+ Link,
+ Unlink,
+ DeleteDrawing,
+ HoldLonger,
+ HoldShorter,
+ InsertFrame,
+ InsertFrameAll,
+ RemoveFrame,
+ RemoveFrameAll,
+ ExposeOnes,
+ ExposeTwos,
+ ExposeThrees,
+ FlipFrames,
+ Roll,
+ Play,
+ LoopRange,
+ Prepare,
+ Onion,
+ OnionSettings,
+ OnOnes,
+ OnTwos,
+ OnThrees,
+ FitFrames,
+ Reverse,
+ Pingpong,
+ EveryLayer,
+ Inbetween,
+ RedoInbetweens,
+ NewClip,
+ DeleteClip,
+ ClipLoops,
+ ClipOwnFps,
+ ExportGodot,
+ Palette,
+ Keys,
+ HideAll,
+ HideDock,
+ LayersPane,
+ ToolPane,
+ InspectorPane,
+ NotesPane,
+ HistoryPane,
+ Timeline,
+ Numbers,
+ Settings,
+ BrushWindow,
+ MessageLog,
+ Spin,
+ ResetNumbers,
+ FlipView,
+ ResetRotation,
+ SwapColours,
+ SizeDrag,
+ TurnLeft90,
+ TurnRight90,
+ DuplicateInPlace,
+ NudgeLeft,
+ NudgeRight,
+ NudgeUp,
+ NudgeDown,
+ NewGroupLayer,
+ NewAdjustLayer,
+ DuplicateLayer,
+ DeleteLayer,
+ GroupLayer,
+ RenameLayer,
+ MoveEarlier,
+ MoveLater,
+ CopyCells,
+ PasteCells,
+ PasteCellsLinked,
+ ClipSettings,
+ NewDocument,
+ OpenDocument,
+ OpenRecent,
+ CopyPath,
+ About,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Group {
+ Tools,
+ View,
+ Edit,
+ Colour,
+ Layers,
+ Frames,
+ Playback,
+ Selected,
+ Clips,
+ Panels,
+ File,
+}
+
+impl Group {
+ pub fn name(self) -> &'static str {
+ match self {
+ Group::Tools => "tools",
+ Group::View => "view",
+ Group::Edit => "edit",
+ Group::Colour => "colour",
+ Group::Layers => "layers",
+ Group::Frames => "frames",
+ Group::Playback => "playback",
+ Group::Selected => "selected frames",
+ Group::Clips => "clips",
+ Group::Panels => "panels",
+ Group::File => "file",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Keys {
+ pub key: Key,
+ pub shift: bool,
+ pub alt: bool,
+ pub command: bool,
+ pub any_shift: bool,
+}
+
+const fn keys(key: Key, shift: bool, alt: bool, command: bool) -> Keys {
+ Keys {
+ key,
+ shift,
+ alt,
+ command,
+ any_shift: false,
+ }
+}
+
+const fn plain(key: Key) -> Keys {
+ keys(key, false, false, false)
+}
+
+const fn shift(key: Key) -> Keys {
+ keys(key, true, false, false)
+}
+
+const fn alt(key: Key) -> Keys {
+ keys(key, false, true, false)
+}
+
+const fn cmd(key: Key) -> Keys {
+ keys(key, false, false, true)
+}
+
+const fn symbol(key: Key) -> Keys {
+ Keys {
+ any_shift: true,
+ ..plain(key)
+ }
+}
+
+impl Keys {
+ pub fn matches(&self, key: Key, m: Modifiers) -> bool {
+ self.key == key && self.alt == m.alt && self.command == m.command && (self.any_shift || self.shift == m.shift)
+ }
+
+ pub fn label(&self) -> String {
+ let key = NAMED
+ .iter()
+ .find(|(k, _)| *k == self.key)
+ .map_or_else(|| self.key.name().to_string(), |(_, n)| n.to_string());
+ [(self.shift, "shift "), (self.alt, "alt "), (self.command, "cmd ")]
+ .iter()
+ .filter(|(on, _)| *on)
+ .map(|(_, word)| *word)
+ .collect::<String>()
+ + &key
+ }
+}
+
+const NAMED: [(Key, &str); 15] = [
+ (Key::Period, "."),
+ (Key::Comma, ","),
+ (Key::OpenBracket, "["),
+ (Key::CloseBracket, "]"),
+ (Key::Equals, "="),
+ (Key::Plus, "+"),
+ (Key::Minus, "-"),
+ (Key::Questionmark, "?"),
+ (Key::Enter, "Return"),
+ (Key::Escape, "Esc"),
+ (Key::Num1, "1"),
+ (Key::ArrowLeft, "left"),
+ (Key::ArrowRight, "right"),
+ (Key::ArrowUp, "up"),
+ (Key::ArrowDown, "down"),
+];
+
+const HELD: [(Key, &str); 4] = [
+ (Key::Q, "flip through frames (hold Q)"),
+ (Key::W, "show the previous drawing (hold W)"),
+ (Key::Space, "pan (hold space)"),
+ (Key::D, "parallax preview (hold D)"),
+];
+
+impl Keys {
+ pub fn pressed(key: Key, m: Modifiers) -> Self {
+ keys(key, m.shift, m.alt, m.command)
+ }
+
+ pub fn parse(text: &str) -> Option<Self> {
+ let words: Vec<&str> = text.split_whitespace().collect();
+ let (name, mods) = words.split_last()?;
+ let key = NAMED
+ .iter()
+ .find(|(_, n)| n == name)
+ .map(|(k, _)| *k)
+ .or_else(|| Key::from_name(name))?;
+ let has = |w: &str| mods.contains(&w);
+ if mods.iter().any(|m| !["shift", "alt", "cmd"].contains(m)) {
+ return None;
+ }
+ Some(keys(key, has("shift"), has("alt"), has("cmd")))
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Bindings {
+ overrides: BTreeMap<Cmd, Vec<Keys>>,
+}
+
+impl Bindings {
+ pub fn from_settings(saved: &BTreeMap<String, Vec<String>>) -> Self {
+ Self {
+ overrides: saved
+ .iter()
+ .filter_map(|(id, list)| {
+ let cmd = Cmd::find(id).filter(|c| !c.spec().is_hold())?;
+ Some((cmd, list.iter().filter_map(|k| Keys::parse(k)).collect()))
+ })
+ .collect(),
+ }
+ }
+
+ pub fn to_settings(&self) -> BTreeMap<String, Vec<String>> {
+ self.overrides
+ .iter()
+ .map(|(c, list)| (c.spec().id.to_string(), list.iter().map(Keys::label).collect()))
+ .collect()
+ }
+
+ pub fn keys(&self, cmd: Cmd) -> Vec<Keys> {
+ match (self.overrides.get(&cmd), cmd.spec().trigger) {
+ (Some(list), _) => list.clone(),
+ (None, Trigger::Press(list)) => list.to_vec(),
+ _ => Vec::new(),
+ }
+ }
+
+ pub fn for_key(&self, key: Key, m: Modifiers) -> Option<Cmd> {
+ Cmd::ALL
+ .into_iter()
+ .find(|c| self.keys(*c).iter().any(|k| k.matches(key, m)))
+ }
+
+ pub fn label(&self, cmd: Cmd) -> String {
+ match cmd.spec().trigger {
+ Trigger::Hold(how) => how.to_string(),
+ _ => self.keys(cmd).iter().map(Keys::label).collect::<Vec<_>>().join(" or "),
+ }
+ }
+
+ pub fn is_default(&self, cmd: Cmd) -> bool {
+ !self.overrides.contains_key(&cmd)
+ }
+
+ pub fn bind(&mut self, cmd: Cmd, k: Keys) -> Result<(), String> {
+ if cmd.spec().is_hold() {
+ return Err(format!("{} is a hold; its keys do not change", cmd.spec().name));
+ }
+ if !k.shift
+ && !k.alt
+ && !k.command
+ && let Some((_, what)) = HELD.iter().find(|(key, _)| *key == k.key)
+ {
+ return Err(format!("{} is taken by {what}", k.label()));
+ }
+ if let Some(other) = self.taken_by(k, cmd) {
+ return Err(format!("{} already runs {}", k.label(), other.spec().name));
+ }
+ self.overrides.insert(cmd, vec![k]);
+ Ok(())
+ }
+
+ pub fn taken_by(&self, k: Keys, except: Cmd) -> Option<Cmd> {
+ let m = Modifiers {
+ shift: k.shift,
+ alt: k.alt,
+ command: k.command,
+ mac_cmd: k.command,
+ ctrl: false,
+ };
+ Cmd::ALL
+ .into_iter()
+ .filter(|c| *c != except)
+ .find(|c| self.keys(*c).iter().any(|o| o.matches(k.key, m)))
+ }
+
+ pub fn clear(&mut self, cmd: Cmd) {
+ self.overrides.insert(cmd, Vec::new());
+ }
+
+ pub fn reset(&mut self, cmd: Cmd) {
+ self.overrides.remove(&cmd);
+ }
+
+ pub fn reset_all(&mut self) {
+ self.overrides.clear();
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Trigger {
+ None,
+ Press(&'static [Keys]),
+ Hold(&'static str),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Repeat {
+ No,
+ Yes,
+ WhenShown,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Spec {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub icon: &'static str,
+ pub group: Group,
+ pub trigger: Trigger,
+ pub repeat: Repeat,
+ pub about: &'static str,
+}
+
+impl Spec {
+ pub fn key_label(&self) -> String {
+ match self.trigger {
+ Trigger::None => String::new(),
+ Trigger::Press(list) => list.iter().map(Keys::label).collect::<Vec<_>>().join(" or "),
+ Trigger::Hold(how) => how.to_string(),
+ }
+ }
+
+ pub fn hint(&self) -> String {
+ self.hint_with(&self.key_label())
+ }
+
+ pub fn hint_with(&self, key: &str) -> String {
+ let key = key.to_string();
+ match (key.is_empty(), self.trigger) {
+ (true, _) => format!("{}\n{}", self.name, self.about),
+ (false, Trigger::Hold(_)) => format!("{}: {key}\n{}", self.name, self.about),
+ (false, _) => format!("{} ({key})\n{}", self.name, self.about),
+ }
+ }
+
+ pub fn is_hold(&self) -> bool {
+ matches!(self.trigger, Trigger::Hold(_))
+ }
+}
+
+const fn spec(
+ id: &'static str,
+ name: &'static str,
+ icon: &'static str,
+ group: Group,
+ trigger: Trigger,
+ repeat: Repeat,
+ about: &'static str,
+) -> Spec {
+ Spec {
+ id,
+ name,
+ icon,
+ group,
+ trigger,
+ repeat,
+ about,
+ }
+}
+
+use Group as G;
+use Repeat as R;
+use Trigger as T;
+
+impl Cmd {
+ pub const ALL: [Cmd; 143] = [
+ Cmd::Brush,
+ Cmd::Eraser,
+ Cmd::Fill,
+ Cmd::Pen,
+ Cmd::ShapeTool,
+ Cmd::Symmetry,
+ Cmd::Parallax,
+ Cmd::MakeRepeat,
+ Cmd::MakeScatter,
+ Cmd::MakeMirror,
+ Cmd::Unwrap,
+ Cmd::ImportPicture,
+ Cmd::Shapes,
+ Cmd::Strokes,
+ Cmd::Points,
+ Cmd::Note,
+ Cmd::Eyedropper,
+ Cmd::Smaller,
+ Cmd::Bigger,
+ Cmd::Pan,
+ Cmd::Zoom,
+ Cmd::Fit,
+ Cmd::ActualSize,
+ Cmd::TurnRight,
+ Cmd::TurnLeft,
+ Cmd::Undo,
+ Cmd::Redo,
+ Cmd::Delete,
+ Cmd::Deselect,
+ Cmd::Copy,
+ Cmd::Paste,
+ Cmd::SelectAll,
+ Cmd::CutLasso,
+ Cmd::Recolour,
+ Cmd::Thinner,
+ Cmd::Thicker,
+ Cmd::FlipH,
+ Cmd::FlipV,
+ Cmd::Corner,
+ Cmd::Smooth,
+ Cmd::Simplify,
+ Cmd::MakePath,
+ Cmd::AddSwatch,
+ Cmd::NewPaintLayer,
+ Cmd::NewVectorLayer,
+ Cmd::ToggleVisible,
+ Cmd::ToggleLocked,
+ Cmd::ToggleClip,
+ Cmd::ToggleLockAlpha,
+ Cmd::AddMask,
+ Cmd::AddMaskHiding,
+ Cmd::PaintMask,
+ Cmd::BackToLayer,
+ Cmd::RemoveMask,
+ Cmd::ToggleMask,
+ Cmd::TintMask,
+ Cmd::OnionLayer,
+ Cmd::NextFrame,
+ Cmd::PrevFrame,
+ Cmd::NextDrawing,
+ Cmd::PrevDrawing,
+ Cmd::FirstFrame,
+ Cmd::LastFrame,
+ Cmd::NewDrawing,
+ Cmd::NewDrawingAfter,
+ Cmd::Duplicate,
+ Cmd::Link,
+ Cmd::Unlink,
+ Cmd::DeleteDrawing,
+ Cmd::HoldLonger,
+ Cmd::HoldShorter,
+ Cmd::InsertFrame,
+ Cmd::InsertFrameAll,
+ Cmd::RemoveFrame,
+ Cmd::RemoveFrameAll,
+ Cmd::ExposeOnes,
+ Cmd::ExposeTwos,
+ Cmd::ExposeThrees,
+ Cmd::FlipFrames,
+ Cmd::Roll,
+ Cmd::Play,
+ Cmd::LoopRange,
+ Cmd::Prepare,
+ Cmd::Onion,
+ Cmd::OnionSettings,
+ Cmd::OnOnes,
+ Cmd::OnTwos,
+ Cmd::OnThrees,
+ Cmd::FitFrames,
+ Cmd::Reverse,
+ Cmd::Pingpong,
+ Cmd::EveryLayer,
+ Cmd::Inbetween,
+ Cmd::RedoInbetweens,
+ Cmd::NewClip,
+ Cmd::DeleteClip,
+ Cmd::ClipLoops,
+ Cmd::ClipOwnFps,
+ Cmd::ExportGodot,
+ Cmd::Palette,
+ Cmd::Keys,
+ Cmd::HideAll,
+ Cmd::HideDock,
+ Cmd::LayersPane,
+ Cmd::ToolPane,
+ Cmd::InspectorPane,
+ Cmd::NotesPane,
+ Cmd::HistoryPane,
+ Cmd::Timeline,
+ Cmd::Numbers,
+ Cmd::Settings,
+ Cmd::BrushWindow,
+ Cmd::MessageLog,
+ Cmd::Spin,
+ Cmd::ResetNumbers,
+ Cmd::FlipView,
+ Cmd::ResetRotation,
+ Cmd::SwapColours,
+ Cmd::SizeDrag,
+ Cmd::TurnLeft90,
+ Cmd::TurnRight90,
+ Cmd::DuplicateInPlace,
+ Cmd::NudgeLeft,
+ Cmd::NudgeRight,
+ Cmd::NudgeUp,
+ Cmd::NudgeDown,
+ Cmd::NewGroupLayer,
+ Cmd::NewAdjustLayer,
+ Cmd::DuplicateLayer,
+ Cmd::DeleteLayer,
+ Cmd::GroupLayer,
+ Cmd::RenameLayer,
+ Cmd::MoveEarlier,
+ Cmd::MoveLater,
+ Cmd::CopyCells,
+ Cmd::PasteCells,
+ Cmd::PasteCellsLinked,
+ Cmd::ClipSettings,
+ Cmd::NewDocument,
+ Cmd::OpenDocument,
+ Cmd::OpenRecent,
+ Cmd::CopyPath,
+ Cmd::About,
+ ];
+
+ pub fn spec(self) -> Spec {
+ match self {
+ Cmd::Brush => spec(
+ "tool.brush",
+ "brush",
+ icon::BRUSH,
+ G::Tools,
+ T::Press(const { &[plain(Key::B)] }),
+ R::No,
+ "paint strokes on the active paint layer",
+ ),
+ Cmd::Eraser => spec(
+ "tool.eraser",
+ "eraser",
+ icon::ERASER,
+ G::Tools,
+ T::Press(const { &[plain(Key::E)] }),
+ R::No,
+ "switch between the brush and the eraser; the pen's eraser end erases too",
+ ),
+ Cmd::Fill => spec(
+ "tool.fill",
+ "fill",
+ icon::FILL,
+ G::Tools,
+ T::Press(const { &[plain(Key::G)] }),
+ R::No,
+ "click inside lines to fill, drag a loop to lasso fill",
+ ),
+ Cmd::Shapes => spec(
+ "tool.shapes",
+ "select and move",
+ icon::SHAPES,
+ G::Tools,
+ T::Press(const { &[plain(Key::V)] }),
+ R::No,
+ "pick the stroke or vector shape under the pen and drag it; alt drag drags a copy",
+ ),
+ Cmd::Strokes => spec(
+ "tool.strokes",
+ "select strokes",
+ icon::STROKES,
+ G::Tools,
+ T::Press(const { &[plain(Key::S)] }),
+ R::No,
+ "pick strokes and fills on the active paint layer, or lasso them",
+ ),
+ Cmd::Pen => spec(
+ "tool.pen",
+ "pen",
+ icon::PEN,
+ G::Tools,
+ T::Press(const { &[plain(Key::P)] }),
+ R::No,
+ "draw vector paths on a vector layer: click for corners, drag for curves, click the first point to close, Return to finish",
+ ),
+ Cmd::ShapeTool => spec(
+ "tool.shape",
+ "rectangles and ellipses",
+ icon::RECTANGLE,
+ G::Tools,
+ T::Press(const { &[plain(Key::U)] }),
+ R::No,
+ "drag rectangles or ellipses on a vector layer: shift for a square or circle, alt from the centre",
+ ),
+ Cmd::Symmetry => spec(
+ "brush.mirror",
+ "mirror painting",
+ icon::FLIP_H,
+ G::Tools,
+ T::None,
+ R::No,
+ "every stroke gets its mirror image across an upright line as you paint it",
+ ),
+ Cmd::Parallax => spec(
+ "view.parallax",
+ "parallax preview",
+ icon::MOUNTAINS,
+ G::View,
+ T::Hold("hold D and move the pointer"),
+ R::No,
+ "the planes at the top of the stack slide by their depth, near ones most",
+ ),
+ Cmd::MakeRepeat => spec(
+ "shape.repeat",
+ "repeat it",
+ icon::REPEAT,
+ G::Layers,
+ T::None,
+ R::No,
+ "put the selected shape in a repeat: copies along a line, an arc or a grid, kept as settings",
+ ),
+ Cmd::MakeScatter => spec(
+ "shape.scatter",
+ "scatter it",
+ icon::SCATTER,
+ G::Layers,
+ T::None,
+ R::No,
+ "put the selected shape in a scatter: copies strewn over a region, sized and turned from a seed",
+ ),
+ Cmd::MakeMirror => spec(
+ "shape.mirror",
+ "mirror it",
+ icon::FLIP_H,
+ G::Layers,
+ T::None,
+ R::No,
+ "put the selected shape in a mirror: it and its mirror image across an axis",
+ ),
+ Cmd::Unwrap => spec(
+ "shape.unwrap",
+ "take the shapes out",
+ icon::REPEAT,
+ G::Layers,
+ T::None,
+ R::No,
+ "remove the selected repeat, scatter or mirror and keep the shapes inside it (where the first copy was)",
+ ),
+ Cmd::ImportPicture => spec(
+ "layer.import-picture",
+ "import a picture",
+ icon::IMAGE,
+ G::Layers,
+ T::None,
+ R::No,
+ "place a PNG or JPEG on a new layer to trace over or paint from (dropping the file works too)",
+ ),
+ Cmd::Points => spec(
+ "tool.points",
+ "edit points",
+ icon::POINTS,
+ G::Tools,
+ T::Press(const { &[plain(Key::A)] }),
+ R::No,
+ "move the points and handles of vector shapes and of brush strokes (a stroke keeps its pressure along its new path)",
+ ),
+ Cmd::Note => spec(
+ "tool.note",
+ "pin a note for the agent",
+ icon::NOTE,
+ G::Tools,
+ T::Press(const { &[plain(Key::N)] }),
+ R::No,
+ "click the canvas to pin a note; the agent reads it with klad notes",
+ ),
+ Cmd::Eyedropper => spec(
+ "colour.pick",
+ "pick a colour",
+ icon::EYEDROPPER,
+ G::Colour,
+ T::Hold("hold alt and click (shift alt: this layer only)"),
+ R::No,
+ "take the colour under the pointer with the brush or fill tool",
+ ),
+ Cmd::Smaller => spec(
+ "brush.smaller",
+ "smaller brush",
+ icon::MINUS,
+ G::Tools,
+ T::Press(const { &[plain(Key::OpenBracket)] }),
+ R::Yes,
+ "the brush size goes down by a fifth",
+ ),
+ Cmd::Bigger => spec(
+ "brush.bigger",
+ "bigger brush",
+ icon::PLUS,
+ G::Tools,
+ T::Press(const { &[plain(Key::CloseBracket)] }),
+ R::Yes,
+ "the brush size goes up by a quarter",
+ ),
+ Cmd::Pan => spec(
+ "view.pan",
+ "pan",
+ icon::HAND,
+ G::View,
+ T::Hold("hold space and drag, or drag with the middle button"),
+ R::No,
+ "move the view",
+ ),
+ Cmd::Zoom => spec(
+ "view.zoom",
+ "zoom",
+ icon::ZOOM,
+ G::View,
+ T::Hold("pinch, or cmd and scroll"),
+ R::No,
+ "zoom the view about the pointer",
+ ),
+ Cmd::Fit => spec(
+ "view.fit",
+ "fit the canvas in the window",
+ icon::FIT,
+ G::View,
+ T::Press(const { &[plain(Key::F)] }),
+ R::No,
+ "zoom and centre so the whole canvas shows",
+ ),
+ Cmd::ActualSize => spec(
+ "view.100",
+ "zoom to 100%",
+ icon::ZOOM,
+ G::View,
+ T::Press(const { &[plain(Key::Num1)] }),
+ R::No,
+ "one canvas pixel per screen pixel",
+ ),
+ Cmd::TurnRight => spec(
+ "view.turn-right",
+ "turn the view right",
+ icon::TURN,
+ G::View,
+ T::Press(const { &[plain(Key::R)] }),
+ R::Yes,
+ "rotate the view 15 degrees clockwise",
+ ),
+ Cmd::TurnLeft => spec(
+ "view.turn-left",
+ "turn the view left",
+ icon::TURN,
+ G::View,
+ T::Press(const { &[shift(Key::R)] }),
+ R::Yes,
+ "rotate the view 15 degrees anticlockwise",
+ ),
+ Cmd::Undo => spec(
+ "edit.undo",
+ "undo",
+ icon::UNDO,
+ G::Edit,
+ T::Press(const { &[cmd(Key::Z)] }),
+ R::Yes,
+ "undo the last change, yours or the agent's",
+ ),
+ Cmd::Redo => spec(
+ "edit.redo",
+ "redo",
+ icon::REDO,
+ G::Edit,
+ T::Press(const { &[keys(Key::Z, true, false, true)] }),
+ R::Yes,
+ "redo what was undone",
+ ),
+ Cmd::Delete => spec(
+ "edit.delete",
+ "delete the selection",
+ icon::TRASH,
+ G::Edit,
+ T::Press(const { &[plain(Key::Delete), plain(Key::Backspace)] }),
+ R::No,
+ "remove the selected strokes, points or shape",
+ ),
+ Cmd::Deselect => spec(
+ "edit.deselect",
+ "clear the selection",
+ icon::CLOSE,
+ G::Edit,
+ T::Press(const { &[plain(Key::Escape)] }),
+ R::No,
+ "drop the selection on the canvas and in the timeline",
+ ),
+ Cmd::Copy => spec(
+ "edit.copy",
+ "copy the selected strokes",
+ icon::COPY,
+ G::Edit,
+ T::Press(const { &[cmd(Key::C)] }),
+ R::No,
+ "keep the strokes selected with S for cmd V",
+ ),
+ Cmd::Paste => spec(
+ "edit.paste",
+ "paste strokes into this frame",
+ icon::PASTE,
+ G::Edit,
+ T::Press(const { &[cmd(Key::V)] }),
+ R::No,
+ "copy the kept strokes into the active layer's drawing at this frame, in place",
+ ),
+ Cmd::SelectAll => spec(
+ "edit.select-all",
+ "select every stroke on this layer",
+ icon::SELECT_ALL,
+ G::Edit,
+ T::Press(const { &[cmd(Key::A)] }),
+ R::No,
+ "every stroke and fill of the active layer's drawing at this frame",
+ ),
+ Cmd::CutLasso => spec(
+ "edit.cut-lasso",
+ "a lasso cuts strokes at its edge",
+ icon::LASSO,
+ G::Edit,
+ T::None,
+ R::No,
+ "on: a lasso also takes the parts of strokes crossing it; off: only strokes wholly inside",
+ ),
+ Cmd::Recolour => spec(
+ "edit.recolour",
+ "recolour the selected strokes",
+ icon::PALETTE,
+ G::Edit,
+ T::None,
+ R::No,
+ "give the selected strokes and fills the current colour",
+ ),
+ Cmd::Thinner => spec(
+ "edit.thinner",
+ "make the selected strokes thinner",
+ icon::MINUS,
+ G::Edit,
+ T::None,
+ R::No,
+ "four fifths of their size",
+ ),
+ Cmd::Thicker => spec(
+ "edit.thicker",
+ "make the selected strokes thicker",
+ icon::PLUS,
+ G::Edit,
+ T::None,
+ R::No,
+ "a quarter bigger",
+ ),
+ Cmd::FlipH => spec(
+ "edit.flip-h",
+ "flip the selection left-right",
+ icon::FLIP_H,
+ G::Edit,
+ T::None,
+ R::No,
+ "mirror the selected strokes about their middle",
+ ),
+ Cmd::FlipV => spec(
+ "edit.flip-v",
+ "flip the selection up-down",
+ icon::FLIP_V,
+ G::Edit,
+ T::None,
+ R::No,
+ "mirror the selected strokes about their middle",
+ ),
+ Cmd::Corner => spec(
+ "points.corner",
+ "make the selected points corners",
+ icon::POINTS,
+ G::Edit,
+ T::None,
+ R::No,
+ "drop their handles",
+ ),
+ Cmd::Smooth => spec(
+ "points.smooth",
+ "make the selected points smooth",
+ icon::POINTS,
+ G::Edit,
+ T::None,
+ R::No,
+ "handles in line, a third of the way to the neighbours",
+ ),
+ Cmd::Simplify => spec(
+ "points.simplify",
+ "simplify the path",
+ icon::POINTS,
+ G::Edit,
+ T::None,
+ R::No,
+ "fewer, smooth points that stay within the set distance of the outline",
+ ),
+ Cmd::MakePath => spec(
+ "points.make-path",
+ "turn the shape into a path",
+ icon::POINTS,
+ G::Edit,
+ T::None,
+ R::No,
+ "a rect or ellipse becomes a path that looks the same",
+ ),
+ Cmd::AddSwatch => spec(
+ "colour.add",
+ "add the colour to the palette",
+ icon::PALETTE,
+ G::Colour,
+ T::None,
+ R::No,
+ "the current colour, with the name typed next to it",
+ ),
+ Cmd::NewPaintLayer => spec(
+ "layer.new-paint",
+ "new paint layer",
+ icon::LAYERS,
+ G::Layers,
+ T::None,
+ R::No,
+ "a paint layer above the active one, with a drawing at this frame",
+ ),
+ Cmd::NewAdjustLayer => spec(
+ "layer.new-adjust",
+ "new adjustment layer",
+ icon::ADJUST,
+ G::Layers,
+ T::None,
+ R::No,
+ "curves above the active layer, changing what is under it in its group; the inspector picks levels, hue, balance, a gradient map or a colour fill instead",
+ ),
+ Cmd::NewVectorLayer => spec(
+ "layer.new-vector",
+ "new vector layer",
+ icon::LAYERS,
+ G::Layers,
+ T::None,
+ R::No,
+ "a vector layer above the active one",
+ ),
+ Cmd::ToggleVisible => spec(
+ "layer.visible",
+ "show or hide the active layer",
+ icon::EYE,
+ G::Layers,
+ T::None,
+ R::No,
+ "the eye of the active layer",
+ ),
+ Cmd::ToggleLocked => spec(
+ "layer.locked",
+ "lock the active layer",
+ icon::LOCK,
+ G::Layers,
+ T::None,
+ R::No,
+ "a locked layer cannot be picked or edited on the canvas",
+ ),
+ Cmd::ToggleClip => spec(
+ "layer.clip",
+ "clip the active layer to the one below",
+ icon::CLIP,
+ G::Layers,
+ T::None,
+ R::No,
+ "show it only where the layer below has paint",
+ ),
+ Cmd::ToggleLockAlpha => spec(
+ "layer.lock-alpha",
+ "lock the active layer's alpha",
+ icon::LOCK,
+ G::Layers,
+ T::None,
+ R::No,
+ "new strokes and fills land only where the layer already has paint",
+ ),
+ Cmd::AddMask => spec(
+ "mask.add",
+ "add a mask",
+ icon::MASK,
+ G::Layers,
+ T::None,
+ R::No,
+ "an empty mask: paint on it to hide parts of the layer",
+ ),
+ Cmd::AddMaskHiding => spec(
+ "mask.add-hiding",
+ "add a mask hiding all",
+ icon::MASK,
+ G::Layers,
+ T::None,
+ R::No,
+ "a full mask: erase it to show parts of the layer",
+ ),
+ Cmd::PaintMask => spec(
+ "mask.paint",
+ "paint on the mask",
+ icon::MASK,
+ G::Layers,
+ T::None,
+ R::No,
+ "make the active layer's mask the layer you paint on",
+ ),
+ Cmd::BackToLayer => spec(
+ "mask.back",
+ "back to the layer",
+ icon::LAYERS,
+ G::Layers,
+ T::None,
+ R::No,
+ "paint on the layer again instead of its mask",
+ ),
+ Cmd::RemoveMask => spec(
+ "mask.remove",
+ "remove the mask",
+ icon::TRASH,
+ G::Layers,
+ T::None,
+ R::No,
+ "delete the active layer's mask (cmd Z brings it back)",
+ ),
+ Cmd::ToggleMask => spec(
+ "mask.on",
+ "turn the mask on or off",
+ icon::MASK,
+ G::Layers,
+ T::None,
+ R::No,
+ "an off mask hides nothing",
+ ),
+ Cmd::TintMask => spec(
+ "mask.tint",
+ "show the mask in red",
+ icon::MASK,
+ G::Layers,
+ T::None,
+ R::No,
+ "tint what the mask hides while you paint on it",
+ ),
+ Cmd::OnionLayer => spec(
+ "onion.layer",
+ "show this layer's onion too",
+ icon::ONION,
+ G::Layers,
+ T::None,
+ R::No,
+ "the dot at the right of a layer's name in the timeline",
+ ),
+ Cmd::NextFrame => spec(
+ "frame.next",
+ "next frame",
+ icon::STEP_ON,
+ G::Frames,
+ T::Press(const { &[plain(Key::Period)] }),
+ R::WhenShown,
+ "held, it waits for each frame to show",
+ ),
+ Cmd::PrevFrame => spec(
+ "frame.previous",
+ "previous frame",
+ icon::STEP_BACK,
+ G::Frames,
+ T::Press(const { &[plain(Key::Comma)] }),
+ R::WhenShown,
+ "held, it waits for each frame to show",
+ ),
+ Cmd::NextDrawing => spec(
+ "frame.next-drawing",
+ "next drawing",
+ icon::NEXT,
+ G::Frames,
+ T::Press(const { &[alt(Key::Period)] }),
+ R::WhenShown,
+ "jump to where the active layer's next drawing starts",
+ ),
+ Cmd::PrevDrawing => spec(
+ "frame.previous-drawing",
+ "previous drawing",
+ icon::PREVIOUS,
+ G::Frames,
+ T::Press(const { &[alt(Key::Comma)] }),
+ R::WhenShown,
+ "jump to where the active layer's previous drawing starts",
+ ),
+ Cmd::FirstFrame => spec(
+ "frame.first",
+ "first frame",
+ icon::PREVIOUS,
+ G::Frames,
+ T::Press(const { &[plain(Key::Home)] }),
+ R::No,
+ "go to frame 0",
+ ),
+ Cmd::LastFrame => spec(
+ "frame.last",
+ "last frame",
+ icon::NEXT,
+ G::Frames,
+ T::Press(const { &[plain(Key::End)] }),
+ R::No,
+ "go to the timeline's last frame",
+ ),
+ Cmd::NewDrawing => spec(
+ "drawing.new",
+ "new drawing here",
+ icon::NEW_DRAWING,
+ G::Frames,
+ T::Press(const { &[plain(Key::K)] }),
+ R::No,
+ "a blank drawing at this frame on the active layer",
+ ),
+ Cmd::NewDrawingAfter => spec(
+ "drawing.new-after",
+ "new drawing after this one",
+ icon::NEW_DRAWING,
+ G::Frames,
+ T::Press(const { &[shift(Key::K)] }),
+ R::No,
+ "a blank drawing right after this exposure, on ones, twos or threes, and go there",
+ ),
+ Cmd::Duplicate => spec(
+ "drawing.duplicate",
+ "duplicate to the next frame",
+ icon::COPY,
+ G::Frames,
+ T::None,
+ R::No,
+ "a copy of this drawing right after its exposure, with the same stroke ids",
+ ),
+ Cmd::Link => spec(
+ "drawing.link",
+ "show a drawing here (link)",
+ icon::LINK,
+ G::Frames,
+ T::None,
+ R::No,
+ "expose one of the layer's drawings again at this frame; drawing on it changes both",
+ ),
+ Cmd::Unlink => spec(
+ "drawing.unlink",
+ "unlink",
+ icon::UNLINK,
+ G::Frames,
+ T::None,
+ R::No,
+ "the link at this frame becomes a drawing of its own",
+ ),
+ Cmd::DeleteDrawing => spec(
+ "drawing.delete",
+ "delete the drawing on this frame",
+ icon::TRASH,
+ G::Frames,
+ T::None,
+ R::No,
+ "links to it are handed the drawing",
+ ),
+ Cmd::HoldLonger => spec(
+ "drawing.longer",
+ "hold one frame longer",
+ icon::PLUS,
+ G::Frames,
+ T::Press(const { &[plain(Key::Equals), symbol(Key::Plus)] }),
+ R::Yes,
+ "this drawing shows one frame more; later drawings move along",
+ ),
+ Cmd::HoldShorter => spec(
+ "drawing.shorter",
+ "hold one frame shorter",
+ icon::MINUS,
+ G::Frames,
+ T::Press(const { &[plain(Key::Minus)] }),
+ R::Yes,
+ "this drawing shows one frame less",
+ ),
+ Cmd::InsertFrame => spec(
+ "frames.insert",
+ "insert a frame in this layer",
+ icon::INSERT,
+ G::Frames,
+ T::Press(const { &[plain(Key::I)] }),
+ R::No,
+ "what shows here also shows one frame more",
+ ),
+ Cmd::InsertFrameAll => spec(
+ "frames.insert-all",
+ "insert a frame in every layer",
+ icon::INSERT,
+ G::Frames,
+ T::Press(const { &[shift(Key::I)] }),
+ R::No,
+ "the timeline and its clips grow by a frame",
+ ),
+ Cmd::RemoveFrame => spec(
+ "frames.remove",
+ "remove this frame from this layer",
+ icon::REMOVE,
+ G::Frames,
+ T::None,
+ R::No,
+ "later drawings of the layer move forward",
+ ),
+ Cmd::RemoveFrameAll => spec(
+ "frames.remove-all",
+ "remove this frame from every layer",
+ icon::REMOVE,
+ G::Frames,
+ T::None,
+ R::No,
+ "the timeline and its clips shrink by a frame",
+ ),
+ Cmd::ExposeOnes => spec(
+ "expose.ones",
+ "new drawings on ones",
+ icon::NEW_DRAWING,
+ G::Frames,
+ T::None,
+ R::No,
+ "shift K makes drawings that show one frame each",
+ ),
+ Cmd::ExposeTwos => spec(
+ "expose.twos",
+ "new drawings on twos",
+ icon::NEW_DRAWING,
+ G::Frames,
+ T::None,
+ R::No,
+ "shift K makes drawings that show two frames each",
+ ),
+ Cmd::ExposeThrees => spec(
+ "expose.threes",
+ "new drawings on threes",
+ icon::NEW_DRAWING,
+ G::Frames,
+ T::None,
+ R::No,
+ "shift K makes drawings that show three frames each",
+ ),
+ Cmd::FlipFrames => spec(
+ "frame.flip",
+ "flip through frames",
+ icon::FLIP_FRAMES,
+ G::Frames,
+ T::Hold("hold Q and move the pen sideways"),
+ R::No,
+ "about one frame per 22 pt; let go to stay",
+ ),
+ Cmd::Roll => spec(
+ "frame.roll",
+ "see the previous drawing",
+ icon::PREVIOUS,
+ G::Frames,
+ T::Hold("hold W"),
+ R::No,
+ "let go to come back",
+ ),
+ Cmd::Play => spec(
+ "play.toggle",
+ "play or stop",
+ icon::PLAY,
+ G::Playback,
+ T::Press(const { &[plain(Key::Enter)] }),
+ R::No,
+ "plays the loop range, else the clip under the playhead, else everything",
+ ),
+ Cmd::LoopRange => spec(
+ "play.loop",
+ "loop a range of frames",
+ icon::LOOP,
+ G::Playback,
+ T::None,
+ R::No,
+ "mark a range around the playhead (or shift drag on the ruler) that Return plays",
+ ),
+ Cmd::Prepare => spec(
+ "play.prepare",
+ "prepare frames",
+ icon::PREPARE,
+ G::Playback,
+ T::None,
+ R::No,
+ "buffer the loop range, else the clip, else every frame: each frame's picture so it shows at once, each drawing's pixels so drawing there starts fast; the strip on the ruler shows what is ready; again to stop",
+ ),
+ Cmd::Onion => spec(
+ "onion.toggle",
+ "onion skin",
+ icon::ONION,
+ G::Playback,
+ T::Press(const { &[plain(Key::O)] }),
+ R::No,
+ "see the drawings before (red) and after (green) under the active layer",
+ ),
+ Cmd::OnionSettings => spec(
+ "onion.settings",
+ "onion skin settings",
+ icon::SETTINGS,
+ G::Playback,
+ T::None,
+ R::No,
+ "how many before and after, by drawings or frames, opacity, falloff, tint",
+ ),
+ Cmd::OnOnes => spec(
+ "span.ones",
+ "retime the selected frames on ones",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "each picture shows one frame; later frames and clips move",
+ ),
+ Cmd::OnTwos => spec(
+ "span.twos",
+ "retime the selected frames on twos",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "each picture shows two frames; later frames and clips move",
+ ),
+ Cmd::OnThrees => spec(
+ "span.threes",
+ "retime the selected frames on threes",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "each picture shows three frames; later frames and clips move",
+ ),
+ Cmd::FitFrames => spec(
+ "span.fit",
+ "fit the selected frames into n frames",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "keep their order and relative timing in the number set in the selection's menu",
+ ),
+ Cmd::Reverse => spec(
+ "span.reverse",
+ "reverse the selected frames",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "play the pictures backwards",
+ ),
+ Cmd::Pingpong => spec(
+ "span.pingpong",
+ "ping-pong the selected frames",
+ icon::RETIME,
+ G::Selected,
+ T::None,
+ R::No,
+ "add them again backwards as links, ends not repeated",
+ ),
+ Cmd::EveryLayer => spec(
+ "span.every-layer",
+ "retime on every layer",
+ icon::LAYERS,
+ G::Selected,
+ T::None,
+ R::No,
+ "on: every layer and the clips follow; off: only the selected rows",
+ ),
+ Cmd::Inbetween => spec(
+ "span.inbetween",
+ "in-between the selection",
+ icon::INBETWEEN,
+ G::Selected,
+ T::None,
+ R::No,
+ "make the drawings between the selection's two keys, with the count, spacing and pairing from its menu",
+ ),
+ Cmd::RedoInbetweens => spec(
+ "span.redo",
+ "redo the in-betweens in the selection",
+ icon::INBETWEEN,
+ G::Selected,
+ T::None,
+ R::No,
+ "remake them after a key changed; ones drawn on are refused",
+ ),
+ Cmd::NewClip => spec(
+ "clip.new",
+ "new clip from the selection",
+ icon::CLIP_BAR,
+ G::Clips,
+ T::None,
+ R::No,
+ "a looping clip over the selected frames, else the loop range",
+ ),
+ Cmd::DeleteClip => spec(
+ "clip.delete",
+ "delete the clip",
+ icon::TRASH,
+ G::Clips,
+ T::None,
+ R::No,
+ "the picked clip, or the one under the playhead",
+ ),
+ Cmd::ClipLoops => spec(
+ "clip.loops",
+ "the clip loops",
+ icon::LOOP,
+ G::Clips,
+ T::None,
+ R::No,
+ "off: it plays once and stops on its last frame",
+ ),
+ Cmd::ClipOwnFps => spec(
+ "clip.fps",
+ "the clip has its own fps",
+ icon::CLIP_BAR,
+ G::Clips,
+ T::None,
+ R::No,
+ "off: it plays at the document's fps",
+ ),
+ Cmd::ExportGodot => spec(
+ "clip.godot",
+ "export to Godot",
+ icon::EXPORT,
+ G::Clips,
+ T::None,
+ R::No,
+ "write the sprite sheet, SpriteFrames and scene into the Godot folder",
+ ),
+ Cmd::Palette => spec(
+ "panel.palette",
+ "find a command",
+ icon::SEARCH,
+ G::Panels,
+ T::Press(const { &[cmd(Key::K)] }),
+ R::No,
+ "type a few letters of what you want to do",
+ ),
+ Cmd::Keys => spec(
+ "panel.keys",
+ "every key",
+ icon::KEYBOARD,
+ G::Panels,
+ T::Press(const { &[symbol(Key::Questionmark)] }),
+ R::No,
+ "the command list with every key",
+ ),
+ Cmd::HideAll => spec(
+ "panel.hide-all",
+ "hide the panels",
+ icon::SIDEBAR,
+ G::Panels,
+ T::Press(const { &[plain(Key::Tab)] }),
+ R::No,
+ "canvas only, with the status line; again to bring them back",
+ ),
+ Cmd::HideDock => spec(
+ "panel.hide-dock",
+ "hide the dock",
+ icon::SIDEBAR,
+ G::Panels,
+ T::Press(const { &[shift(Key::Tab)] }),
+ R::No,
+ "the panels on the right",
+ ),
+ Cmd::LayersPane => spec(
+ "panel.layers",
+ "layers panel",
+ icon::LAYERS,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide it in the dock",
+ ),
+ Cmd::ToolPane => spec(
+ "panel.tool",
+ "colour and brush panel",
+ icon::PALETTE,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide it in the dock",
+ ),
+ Cmd::InspectorPane => spec(
+ "panel.inspector",
+ "inspector panel",
+ icon::INSPECTOR,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide it in the dock",
+ ),
+ Cmd::NotesPane => spec(
+ "panel.notes",
+ "notes panel",
+ icon::NOTE,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide it in the dock",
+ ),
+ Cmd::HistoryPane => spec(
+ "panel.history",
+ "history panel",
+ icon::HISTORY,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide it in the dock",
+ ),
+ Cmd::Timeline => spec(
+ "panel.timeline",
+ "timeline",
+ icon::TIMELINE,
+ G::Panels,
+ T::None,
+ R::No,
+ "show or hide the timeline",
+ ),
+ Cmd::Numbers => spec(
+ "panel.numbers",
+ "numbers",
+ icon::NUMBERS,
+ G::Panels,
+ T::None,
+ R::No,
+ "times and memory over the canvas: pen to GPU, frame, compose, steps, drops",
+ ),
+ Cmd::BrushWindow => spec(
+ "panel.brush",
+ "edit the brush",
+ icon::BRUSH,
+ G::Panels,
+ T::Press(const { &[plain(Key::F5)] }),
+ R::No,
+ "tip, dual tip, texture, pressure and tilt, colour dynamics and wet paint, with a live sample; save it in this drawing",
+ ),
+ Cmd::Settings => spec(
+ "panel.settings",
+ "settings",
+ icon::SETTINGS,
+ G::Panels,
+ T::Press(const { &[cmd(Key::Comma)] }),
+ R::No,
+ "pen calibration and the layout",
+ ),
+ Cmd::MessageLog => spec(
+ "panel.log",
+ "message log",
+ icon::LOG,
+ G::Panels,
+ T::None,
+ R::No,
+ "the last 200 messages with their times",
+ ),
+ Cmd::Spin => spec(
+ "numbers.spin",
+ "spin the view",
+ icon::TURN,
+ G::Panels,
+ T::None,
+ R::No,
+ "turn and zoom the view every frame to measure the frame rate",
+ ),
+ Cmd::ResetNumbers => spec(
+ "numbers.reset",
+ "reset the numbers",
+ icon::NUMBERS,
+ G::Panels,
+ T::None,
+ R::No,
+ "start the measurements again",
+ ),
+ Cmd::FlipView => spec(
+ "view.flip",
+ "flip the view left-right",
+ icon::FLIP_H,
+ G::View,
+ T::Press(const { &[plain(Key::H)] }),
+ R::No,
+ "see the drawing mirrored to check it; the document does not change",
+ ),
+ Cmd::ResetRotation => spec(
+ "view.upright",
+ "turn the view upright",
+ icon::TURN,
+ G::View,
+ T::None,
+ R::No,
+ "rotation back to 0, about the middle of the window",
+ ),
+ Cmd::SwapColours => spec(
+ "colour.swap",
+ "swap the two colours",
+ icon::SWAP,
+ G::Colour,
+ T::Press(const { &[plain(Key::X)] }),
+ R::No,
+ "the current colour and the one before it change places",
+ ),
+ Cmd::SizeDrag => spec(
+ "brush.size-drag",
+ "change the brush size on the canvas",
+ icon::SIZE,
+ G::Tools,
+ T::Hold("hold cmd alt and drag sideways"),
+ R::No,
+ "the circle shows the size; let go to keep it",
+ ),
+ Cmd::TurnLeft90 => spec(
+ "edit.turn-left",
+ "turn the selection 90 degrees left",
+ icon::TURN_LEFT,
+ G::Edit,
+ T::None,
+ R::No,
+ "about the middle of the selected strokes or the shape",
+ ),
+ Cmd::TurnRight90 => spec(
+ "edit.turn-right",
+ "turn the selection 90 degrees right",
+ icon::TURN,
+ G::Edit,
+ T::None,
+ R::No,
+ "about the middle of the selected strokes or the shape",
+ ),
+ Cmd::DuplicateInPlace => spec(
+ "edit.duplicate",
+ "duplicate the selection in place",
+ icon::COPY,
+ G::Edit,
+ T::Press(const { &[cmd(Key::D)] }),
+ R::No,
+ "a copy of the selected strokes or shape right on top, selected",
+ ),
+ Cmd::NudgeLeft => spec(
+ "edit.nudge-left",
+ "nudge the selection left",
+ icon::LEFT,
+ G::Edit,
+ T::Press(const { &[symbol(Key::ArrowLeft)] }),
+ R::Yes,
+ "1 px, 10 px with shift; strokes, a shape or points",
+ ),
+ Cmd::NudgeRight => spec(
+ "edit.nudge-right",
+ "nudge the selection right",
+ icon::RIGHT,
+ G::Edit,
+ T::Press(const { &[symbol(Key::ArrowRight)] }),
+ R::Yes,
+ "1 px, 10 px with shift; strokes, a shape or points",
+ ),
+ Cmd::NudgeUp => spec(
+ "edit.nudge-up",
+ "nudge the selection up",
+ icon::UP,
+ G::Edit,
+ T::Press(const { &[symbol(Key::ArrowUp)] }),
+ R::Yes,
+ "1 px, 10 px with shift; strokes, a shape or points",
+ ),
+ Cmd::NewGroupLayer => spec(
+ "layer.new-group",
+ "new group",
+ icon::LAYERS,
+ G::Layers,
+ T::None,
+ R::No,
+ "an empty group above the active layer; drag layers into it",
+ ),
+ Cmd::DuplicateLayer => spec(
+ "layer.duplicate",
+ "duplicate the layer",
+ icon::COPY,
+ G::Layers,
+ T::None,
+ R::No,
+ "a copy of the active layer with its drawings, links and mask, above it",
+ ),
+ Cmd::DeleteLayer => spec(
+ "layer.delete",
+ "delete the layer",
+ icon::TRASH,
+ G::Layers,
+ T::None,
+ R::No,
+ "remove the active layer (cmd Z brings it back)",
+ ),
+ Cmd::GroupLayer => spec(
+ "layer.group",
+ "put the layer in a new group",
+ icon::LAYERS,
+ G::Layers,
+ T::None,
+ R::No,
+ "a new group in the active layer's place, holding it",
+ ),
+ Cmd::RenameLayer => spec(
+ "layer.rename",
+ "rename the layer",
+ icon::NOTE,
+ G::Layers,
+ T::None,
+ R::No,
+ "type the active layer's new name in its row",
+ ),
+ Cmd::MoveEarlier => spec(
+ "drawing.earlier",
+ "move the drawing a frame earlier",
+ icon::LEFT,
+ G::Frames,
+ T::Press(const { &[alt(Key::ArrowLeft)] }),
+ R::Yes,
+ "drawings in the way are pushed along",
+ ),
+ Cmd::MoveLater => spec(
+ "drawing.later",
+ "move the drawing a frame later",
+ icon::RIGHT,
+ G::Frames,
+ T::Press(const { &[alt(Key::ArrowRight)] }),
+ R::Yes,
+ "drawings in the way are pushed along",
+ ),
+ Cmd::CopyCells => spec(
+ "cells.copy",
+ "copy the selected cells",
+ icon::COPY,
+ G::Selected,
+ T::None,
+ R::No,
+ "the drawings and holds of the selected frames and rows (or the drawing under the playhead)",
+ ),
+ Cmd::PasteCells => spec(
+ "cells.paste",
+ "paste cells as copies",
+ icon::PASTE,
+ G::Selected,
+ T::None,
+ R::No,
+ "new drawings with the copied strokes, at the playhead, on the same layers",
+ ),
+ Cmd::PasteCellsLinked => spec(
+ "cells.paste-links",
+ "paste cells as links",
+ icon::LINK,
+ G::Selected,
+ T::None,
+ R::No,
+ "show the copied drawings again at the playhead; drawing on them changes the originals",
+ ),
+ Cmd::ClipSettings => spec(
+ "clip.settings",
+ "clip settings",
+ icon::CLIP_BAR,
+ G::Clips,
+ T::None,
+ R::No,
+ "name, loop, own fps, first and last frame, delete, export to Godot",
+ ),
+ Cmd::NewDocument => spec(
+ "file.new",
+ "new drawing",
+ icon::FILE_PLUS,
+ G::File,
+ T::Press(const { &[cmd(Key::N)] }),
+ R::No,
+ "a new .draw bundle: name, folder, size, background; this one stays saved",
+ ),
+ Cmd::OpenDocument => spec(
+ "file.open",
+ "open a drawing",
+ icon::FOLDER_OPEN,
+ G::File,
+ T::Press(const { &[cmd(Key::O)] }),
+ R::No,
+ "pick a .draw folder and switch to it; this one stays saved",
+ ),
+ Cmd::OpenRecent => spec(
+ "file.recent",
+ "open a recent drawing",
+ icon::HISTORY,
+ G::File,
+ T::None,
+ R::No,
+ "the drawings opened lately, with thumbnails",
+ ),
+ Cmd::About => spec(
+ "file.about",
+ "about klad and licences",
+ icon::INFO,
+ G::File,
+ T::None,
+ R::No,
+ "the version, the licence and every open source part it is built on",
+ ),
+ Cmd::CopyPath => spec(
+ "file.copy-path",
+ "copy this drawing's path",
+ icon::COPY,
+ G::File,
+ T::None,
+ R::No,
+ "puts the .draw folder's path on the clipboard, to hand to the agent",
+ ),
+ Cmd::NudgeDown => spec(
+ "edit.nudge-down",
+ "nudge the selection down",
+ icon::DOWN,
+ G::Edit,
+ T::Press(const { &[symbol(Key::ArrowDown)] }),
+ R::Yes,
+ "1 px, 10 px with shift; strokes, a shape or points",
+ ),
+ }
+ }
+
+ pub fn find(id: &str) -> Option<Cmd> {
+ Cmd::ALL.into_iter().find(|c| c.spec().id == id)
+ }
+}
+
+fn squash(text: &str) -> String {
+ text.to_lowercase().chars().filter(|c| *c != '-').collect()
+}
+
+fn subsequence(needle: &str, hay: &str) -> bool {
+ let mut rest = hay.chars();
+ needle.chars().all(|n| rest.any(|h| h == n))
+}
+
+pub fn score(query: &str, cmd: Cmd) -> Option<u32> {
+ let q = squash(query.trim());
+ if q.is_empty() {
+ return Some(5);
+ }
+ let s = cmd.spec();
+ let name = squash(s.name);
+ let words: Vec<&str> = name.split_whitespace().collect();
+ let key = s.key_label().to_lowercase();
+ if name.starts_with(&q) {
+ return Some(0);
+ }
+ if key == q || key.split(" or ").any(|k| k == q) {
+ return Some(1);
+ }
+ if words.iter().any(|w| w.starts_with(&q)) {
+ return Some(2);
+ }
+ if name.contains(&q) {
+ return Some(3);
+ }
+ if subsequence(&q, &name) {
+ return Some(4);
+ }
+ squash(s.group.name()).contains(&q).then_some(6)
+}
+
+pub fn rank(query: &str, recent: &[Cmd]) -> Vec<Cmd> {
+ let mut found: Vec<(u32, usize, usize, Cmd)> = Cmd::ALL
+ .into_iter()
+ .enumerate()
+ .filter(|(i, c)| Cmd::ALL[..*i].iter().all(|o| o != c))
+ .filter_map(|(i, c)| {
+ let used = recent.iter().position(|r| *r == c).unwrap_or(usize::MAX);
+ score(query, c).map(|s| (s, used, i, c))
+ })
+ .collect();
+ found.sort();
+ found.into_iter().map(|(_, _, _, c)| c).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::BTreeSet;
+
+ const INVENTORY: &[(&str, &str)] = &[
+ ("brush tool, B (M0)", "tool.brush"),
+ ("eraser, E (M2 batch 1)", "tool.eraser"),
+ ("fill tool, G (M2 batch 2)", "tool.fill"),
+ ("select shapes, V (M1 batch 3)", "tool.shapes"),
+ ("stroke select, S (M2 batch 3)", "tool.strokes"),
+ ("direct select, A (M2 batch 3)", "tool.points"),
+ ("pen, P (M4 test round 1)", "tool.pen"),
+ ("prepare frames (M4 test round 1)", "play.prepare"),
+ ("brush window, F5 (M5 batch 1)", "panel.brush"),
+ ("pin a note, N (M1 batch 3)", "tool.note"),
+ ("eyedropper, alt click (M2 batch 2)", "colour.pick"),
+ ("brush size, [ and ] (M0)", "brush.smaller"),
+ ("brush size up", "brush.bigger"),
+ ("pan, space or middle drag (M0)", "view.pan"),
+ ("zoom, pinch or cmd scroll (M0)", "view.zoom"),
+ ("fit, F (M0)", "view.fit"),
+ ("100%, 1 (M0)", "view.100"),
+ ("rotate the view, R and shift R (M0)", "view.turn-right"),
+ ("rotate the view left", "view.turn-left"),
+ ("undo, cmd Z (M1 batch 3)", "edit.undo"),
+ ("redo, shift cmd Z (M1 batch 3)", "edit.redo"),
+ ("delete the selection (M1 batch 3)", "edit.delete"),
+ ("clear the selection, Esc", "edit.deselect"),
+ ("copy strokes, cmd C (M3 batch 4)", "edit.copy"),
+ ("paste strokes, cmd V (M3 batch 4)", "edit.paste"),
+ ("select all on this layer (M2 batch 3)", "edit.select-all"),
+ ("a lasso cuts strokes at its edge (M2 batch 4)", "edit.cut-lasso"),
+ ("recolour (M2 batch 3)", "edit.recolour"),
+ ("thinner (M2 batch 3)", "edit.thinner"),
+ ("thicker (M2 batch 3)", "edit.thicker"),
+ ("flip left-right (M2 batch 4)", "edit.flip-h"),
+ ("flip up-down (M2 batch 4)", "edit.flip-v"),
+ ("corner points (M2 batch 3)", "points.corner"),
+ ("smooth points (M2 batch 3)", "points.smooth"),
+ ("simplify (M2 batch 3)", "points.simplify"),
+ ("make it a path (M2 batch 3)", "points.make-path"),
+ ("add a palette colour (M2 batch 2)", "colour.add"),
+ ("+ paint layer (M3 batch 1)", "layer.new-paint"),
+ ("+ vector layer (M3 batch 1)", "layer.new-vector"),
+ ("layer visibility (M1 batch 3)", "layer.visible"),
+ ("layer locked (M1 batch 3)", "layer.locked"),
+ ("clip to the layer below (M2 batch 4)", "layer.clip"),
+ ("lock alpha (M2 batch 4)", "layer.lock-alpha"),
+ ("add mask (M2 batch 4)", "mask.add"),
+ ("add mask hiding all (M2 batch 4)", "mask.add-hiding"),
+ ("paint on the mask (M2 batch 4)", "mask.paint"),
+ ("back to the layer (M2 batch 4)", "mask.back"),
+ ("remove mask (M2 batch 4)", "mask.remove"),
+ ("mask on (M2 batch 4)", "mask.on"),
+ ("show the mask in red (M2 batch 4)", "mask.tint"),
+ ("a layer's onion dot (M3 batch 2)", "onion.layer"),
+ ("step a frame, . and , (M3 batch 1)", "frame.next"),
+ ("step back", "frame.previous"),
+ ("next drawing, alt . (M3 batch 1)", "frame.next-drawing"),
+ ("previous drawing, alt , (M3 batch 1)", "frame.previous-drawing"),
+ ("first frame, Home (M3 batch 1)", "frame.first"),
+ ("last frame, End (M3 batch 1)", "frame.last"),
+ ("new drawing, K (M3 batch 1)", "drawing.new"),
+ ("new drawing after this one, shift K (M3 batch 2)", "drawing.new-after"),
+ ("duplicate to the next frame (M3 batch 1)", "drawing.duplicate"),
+ ("show a drawing here, link (M3 batch 1)", "drawing.link"),
+ ("unlink (M3 batch 1)", "drawing.unlink"),
+ ("delete a drawing (M3 batch 1)", "drawing.delete"),
+ ("hold longer, = (M3 batch 1)", "drawing.longer"),
+ ("hold shorter, - (M3 batch 1)", "drawing.shorter"),
+ ("insert a frame, I (M3 batch 1)", "frames.insert"),
+ (
+ "insert a frame in every layer, shift I (M3 batch 1)",
+ "frames.insert-all",
+ ),
+ ("remove a frame (M3 batch 1)", "frames.remove"),
+ ("remove a frame from every layer (M3 batch 1)", "frames.remove-all"),
+ ("shift K exposes on ones (M3 batch 2)", "expose.ones"),
+ ("on twos", "expose.twos"),
+ ("on threes", "expose.threes"),
+ ("flip, hold Q (M3 batch 2)", "frame.flip"),
+ ("roll, hold W (M3 batch 2)", "frame.roll"),
+ ("play and stop, Return (M3 batch 2)", "play.toggle"),
+ ("loop range (M3 batch 2)", "play.loop"),
+ ("onion skin, O (M3 batch 2)", "onion.toggle"),
+ ("onion settings (M3 batch 2)", "onion.settings"),
+ ("retime on ones (M3 batch 4)", "span.ones"),
+ ("retime on twos (M3 batch 4)", "span.twos"),
+ ("retime on threes (M3 batch 4)", "span.threes"),
+ ("fit into n frames (M3 batch 4)", "span.fit"),
+ ("reverse (M3 batch 4)", "span.reverse"),
+ ("ping-pong (M3 batch 4)", "span.pingpong"),
+ ("retime on every layer (M3 batch 4)", "span.every-layer"),
+ ("make the in-betweens (M3 batch 4)", "span.inbetween"),
+ ("redo the in-betweens (M3 batch 4)", "span.redo"),
+ ("new clip, a drag on the strip (M3 batch 3)", "clip.new"),
+ ("delete clip (M3 batch 3)", "clip.delete"),
+ ("clip loops (M3 batch 3)", "clip.loops"),
+ ("clip own fps (M3 batch 3)", "clip.fps"),
+ ("export to Godot (M3 batch 3)", "clip.godot"),
+ ("pen calibration (M2 batch 1)", "panel.settings"),
+ ("pen and performance numbers (M0)", "panel.numbers"),
+ ("spin, the fps test (M0)", "numbers.spin"),
+ ("reset numbers (M0)", "numbers.reset"),
+ ];
+
+ #[test]
+ fn every_editor_action_of_m1_to_m3_is_a_named_command() {
+ let missing: Vec<&str> = INVENTORY
+ .iter()
+ .filter(|(_, id)| Cmd::find(id).is_none())
+ .map(|(what, _)| *what)
+ .collect();
+ assert!(missing.is_empty(), "no command for {missing:?}");
+ let unique: BTreeSet<Cmd> = Cmd::ALL.into_iter().collect();
+ let ids: BTreeSet<&str> = unique.iter().map(|c| c.spec().id).collect();
+ assert_eq!(ids.len(), unique.len(), "two commands share an id");
+ unique.iter().for_each(|c| {
+ let s = c.spec();
+ assert!(
+ !s.name.is_empty() && !s.about.is_empty() && !s.icon.is_empty(),
+ "{c:?} needs a name, words and an icon"
+ );
+ });
+ }
+
+ #[test]
+ fn keys_rebind_refuse_a_key_in_use_and_survive_the_settings_file() {
+ Cmd::ALL.into_iter().for_each(|c| {
+ if let Trigger::Press(list) = c.spec().trigger {
+ list.iter().filter(|k| !k.any_shift).for_each(|k| {
+ assert_eq!(Keys::parse(&k.label()), Some(*k), "{}", k.label());
+ });
+ }
+ });
+ let mut b = Bindings::default();
+ let none = Modifiers::NONE;
+ assert_eq!(b.for_key(Key::B, none), Some(Cmd::Brush));
+ let taken = b.bind(Cmd::DuplicateLayer, Keys::parse("B").unwrap()).unwrap_err();
+ assert!(taken.contains("brush"), "{taken}");
+ assert!(
+ b.bind(Cmd::DuplicateLayer, Keys::parse("Q").unwrap())
+ .unwrap_err()
+ .contains("hold Q")
+ );
+ assert!(b.bind(Cmd::FlipFrames, Keys::parse("F9").unwrap()).is_err());
+ b.bind(Cmd::DuplicateLayer, Keys::parse("shift D").unwrap()).unwrap();
+ let shift = Modifiers { shift: true, ..none };
+ assert_eq!(b.for_key(Key::D, shift), Some(Cmd::DuplicateLayer));
+ assert_eq!(b.label(Cmd::DuplicateLayer), "shift D");
+ b.bind(Cmd::Brush, Keys::parse("Y").unwrap()).unwrap();
+ assert_eq!(b.for_key(Key::B, none), None);
+ assert_eq!(b.for_key(Key::Y, none), Some(Cmd::Brush));
+ b.bind(Cmd::DuplicateLayer, Keys::parse("B").unwrap()).unwrap();
+ let saved = b.to_settings();
+ assert_eq!(saved["layer.duplicate"], ["B"]);
+ let back = Bindings::from_settings(&saved);
+ assert_eq!(back, b);
+ let mut back = back;
+ back.reset(Cmd::Brush);
+ assert!(back.bind(Cmd::Brush, Keys::parse("B").unwrap()).is_err());
+ back.reset_all();
+ assert_eq!(back.for_key(Key::B, none), Some(Cmd::Brush));
+ assert!(Keys::parse("hyper B").is_none());
+ }
+
+ #[test]
+ fn no_key_runs_two_commands() {
+ let bound: Vec<(Keys, Cmd)> = Cmd::ALL
+ .into_iter()
+ .flat_map(|c| match c.spec().trigger {
+ Trigger::Press(list) => list.iter().map(|k| (*k, c)).collect(),
+ _ => Vec::new(),
+ })
+ .collect();
+ bound.iter().for_each(|(k, c)| {
+ let mods = |shift| Modifiers {
+ shift,
+ alt: k.alt,
+ command: k.command,
+ mac_cmd: k.command,
+ ctrl: false,
+ };
+ [k.shift, !k.shift]
+ .into_iter()
+ .filter(|shift| *shift == k.shift || k.any_shift)
+ .for_each(|shift| {
+ let runs: BTreeSet<Cmd> = bound
+ .iter()
+ .filter(|(o, _)| o.matches(k.key, mods(shift)))
+ .map(|(_, c)| *c)
+ .collect();
+ assert_eq!(runs.len(), 1, "{} runs {runs:?}", k.label());
+ assert_eq!(Bindings::default().for_key(k.key, mods(shift)), Some(*c));
+ });
+ });
+ let shifted = Modifiers {
+ shift: true,
+ ..Modifiers::NONE
+ };
+ assert_eq!(
+ Bindings::default().for_key(Key::K, Modifiers::NONE),
+ Some(Cmd::NewDrawing)
+ );
+ assert_eq!(Bindings::default().for_key(Key::K, shifted), Some(Cmd::NewDrawingAfter));
+ assert_eq!(Bindings::default().for_key(Key::Plus, shifted), Some(Cmd::HoldLonger));
+ assert_eq!(Bindings::default().for_key(Key::Z, Modifiers::COMMAND), Some(Cmd::Undo));
+ assert_eq!(
+ Bindings::default().for_key(Key::Comma, Modifiers::COMMAND),
+ Some(Cmd::Settings)
+ );
+ assert_eq!(
+ Bindings::default().for_key(Key::Comma, Modifiers::NONE),
+ Some(Cmd::PrevFrame)
+ );
+ assert_eq!(Bindings::default().for_key(Key::Q, Modifiers::NONE), None);
+ }
+
+ #[test]
+ fn the_palette_finds_what_is_typed_first() {
+ assert_eq!(rank("inb", &[])[0], Cmd::Inbetween);
+ assert_eq!(rank("in-b", &[])[0], Cmd::Inbetween);
+ assert_eq!(rank("undo", &[])[0], Cmd::Undo);
+ assert_eq!(rank("shift k", &[])[0], Cmd::NewDrawingAfter);
+ assert_eq!(rank("onion", &[])[..2], [Cmd::Onion, Cmd::OnionSettings]);
+ assert!(rank("ping", &[]).starts_with(&[Cmd::Pingpong]));
+ assert!(rank("godot", &[]).contains(&Cmd::ExportGodot));
+ assert!(rank("zzqx", &[]).is_empty());
+ let all = rank("", &[Cmd::ExportGodot, Cmd::Play]);
+ assert_eq!(all[..2], [Cmd::ExportGodot, Cmd::Play]);
+ assert_eq!(all.len(), Cmd::ALL.iter().collect::<BTreeSet<_>>().len());
+ assert_eq!(rank("new", &[Cmd::NewClip])[0], Cmd::NewClip);
+ }
+
+ #[test]
+ fn keys_read_the_way_the_docs_write_them() {
+ assert_eq!(Cmd::Redo.spec().key_label(), "shift cmd Z");
+ assert_eq!(Cmd::NextDrawing.spec().key_label(), "alt .");
+ assert_eq!(Cmd::Delete.spec().key_label(), "Delete or Backspace");
+ assert_eq!(Cmd::Play.spec().key_label(), "Return");
+ assert_eq!(
+ Cmd::Pan.spec().hint(),
+ "pan: hold space and drag, or drag with the middle button\nmove the view"
+ );
+ assert_eq!(
+ Cmd::Unlink.spec().hint(),
+ "unlink\nthe link at this frame becomes a drawing of its own"
+ );
+ assert_eq!(
+ Cmd::NewDrawing.spec().hint(),
+ "new drawing here (K)\na blank drawing at this frame on the active layer"
+ );
+ }
+}
diff --git a/crates/app/src/composite.rs b/crates/app/src/composite.rs
new file mode 100644
index 0000000..3264460
--- /dev/null
+++ b/crates/app/src/composite.rs
@@ -0,0 +1,4387 @@
+use crate::planes;
+use anyhow::{Context, Result, anyhow};
+use half::f16;
+use klad_brush::TILE;
+use klad_brush::brush::StrokeBlend;
+use klad_brush::cache::{CelCache, Write};
+use klad_brush::tiles::TILE_PX;
+use klad_brush::{BrushSet, CelReplay, Raster, StrokeBuffer};
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::doc::{Blend, Document, Kind, Layer, Loc, MASK, Node};
+use klad_core::fill::{Fill, FillRef};
+use klad_core::history::record;
+use klad_core::look::Effect;
+use klad_core::ops::{Applied, Op, apply_all};
+use klad_core::patch::{Patch, diff};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use klad_core::stroke::{Mark, Stroke, decode_cel, encode_cel, next_id};
+use klad_render::onion::{self, Ghost, Onion, Onions};
+use klad_render::{
+ Rasters, Swap, SwapTiles, TileItem, TileJob, compose_tile, fill_reference, flatten_with, rasterize_nodes,
+};
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::Path;
+
+const CACHE_BYTES: usize = 1 << 30;
+
+pub type Tiles = Vec<(usize, Vec<f16>)>;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Mix {
+ Over,
+ Multiply,
+ Screen,
+ Add,
+}
+
+impl Mix {
+ fn of(blend: Blend) -> Option<Self> {
+ match blend {
+ Blend::Normal => Some(Mix::Over),
+ Blend::Multiply => Some(Mix::Multiply),
+ Blend::Screen => Some(Mix::Screen),
+ Blend::Add => Some(Mix::Add),
+ _ => None,
+ }
+ }
+}
+
+pub struct Planes {
+ pub base: Tiles,
+ pub runs: Vec<(Mix, Tiles)>,
+ pub opacity: f32,
+}
+
+fn pure(doc: &Document, layer: &Layer) -> bool {
+ layer.blend == Blend::Normal
+ && doc.effects_of(layer).is_empty()
+ && !layer.reads_under()
+ && layer.children().iter().all(|c| pure(doc, c))
+}
+
+fn effect_reach(doc: &Document, layers: &[Layer]) -> i32 {
+ layers
+ .iter()
+ .filter(|l| l.visible)
+ .map(|l| klad_render::effects::margin(&doc.effects_of(l), 1.0) + effect_reach(doc, l.children()))
+ .max()
+ .unwrap_or(0)
+}
+
+fn dilate(tiles: &[usize], reach: i32, cols: usize, rows: usize) -> Vec<usize> {
+ let n = (reach.max(0) as usize).div_ceil(TILE) as i64;
+ if n == 0 {
+ return tiles.to_vec();
+ }
+ tiles
+ .iter()
+ .flat_map(|&i| {
+ let (x, y) = ((i % cols) as i64, (i / cols) as i64);
+ (-n..=n).flat_map(move |dy| (-n..=n).map(move |dx| (x + dx, y + dy)))
+ })
+ .filter(|(x, y)| *x >= 0 && *y >= 0 && (*x as usize) < cols && (*y as usize) < rows)
+ .map(|(x, y)| y as usize * cols + x as usize)
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect()
+}
+
+fn blends_through(layer: &Layer) -> bool {
+ layer.visible
+ && (layer.blend != Blend::Normal
+ || layer.reads_under()
+ || layer
+ .effects
+ .iter()
+ .any(|e| matches!(e, Effect::Glow(g) if g.blend != Blend::Normal))
+ || layer.children().iter().any(blends_through))
+}
+
+fn live_above(above: &[&Layer]) -> bool {
+ above.iter().any(|l| blends_through(l))
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct Stamp {
+ len: u64,
+ modified: Option<std::time::SystemTime>,
+ inode: u64,
+}
+
+fn stamp(path: &Path) -> Option<Stamp> {
+ use std::os::unix::fs::MetadataExt;
+ let meta = fs::metadata(path).ok()?;
+ Some(Stamp {
+ len: meta.len(),
+ modified: meta.modified().ok(),
+ inode: meta.ino(),
+ })
+}
+
+pub struct CelData {
+ pub replay: CelReplay,
+ file_hash: u64,
+}
+
+impl CelData {
+ pub fn marks(&self) -> &[Mark] {
+ self.replay.marks()
+ }
+}
+
+pub struct Preview<'a> {
+ pub buffer: &'a StrokeBuffer,
+ pub twin: Option<&'a StrokeBuffer>,
+ pub color: [f32; 4],
+ pub opacity: f32,
+ pub blend: StrokeBlend,
+}
+
+pub struct Scene {
+ pub bundle: Bundle,
+ pub active: Vec<usize>,
+ pub frame: u32,
+ rasters: Rasters,
+ cels: BTreeMap<String, CelData>,
+ vector_hash: BTreeMap<String, u64>,
+ memo: std::collections::VecDeque<(String, u64, Raster)>,
+ below: Raster,
+ above: Raster,
+ fast: bool,
+ unsaved: Patch,
+ pub tint_mask: bool,
+ used: BTreeMap<String, u64>,
+ tick: u64,
+ budget: usize,
+ pub stale: bool,
+ pub onion: Onion,
+ pub onion_on: bool,
+ pub onion_marked: BTreeSet<String>,
+ onions: Onions,
+ onion_key: u64,
+ hashes: BTreeMap<String, (Stamp, u64)>,
+ pub keep_after: std::time::Duration,
+ pub lean: bool,
+}
+
+pub type Plan = Vec<(String, Vec<Ghost>)>;
+
+pub struct FrameImage {
+ pub key: u64,
+ pub width: u32,
+ pub height: u32,
+ pub mips: Vec<Vec<u8>>,
+}
+
+impl FrameImage {
+ pub fn bytes(&self) -> usize {
+ self.mips.iter().map(Vec::len).sum()
+ }
+}
+
+pub struct FrameRequest {
+ pub frame: u32,
+ pub key: u64,
+ level: u32,
+ rev: u64,
+ bundle: Bundle,
+ rasters: Rasters,
+ paint: Vec<(String, String)>,
+ vector: Vec<(String, u64, Vec<Node>)>,
+ plan: Option<Plan>,
+ brushes: BrushSet,
+ disk: Option<std::path::PathBuf>,
+ keep_after: std::time::Duration,
+ planes: Option<PlanesAsk>,
+}
+
+#[derive(Clone)]
+pub struct PlanesAsk {
+ pub base: u64,
+ pub cels: Vec<(String, String)>,
+ pub dir: std::path::PathBuf,
+ pub active: Vec<usize>,
+}
+
+impl PlanesAsk {
+ fn key(&self, bundle: &Bundle, brushes: &BrushSet) -> u64 {
+ let cache = CelCache::new(bundle, brushes, Write::Never);
+ let keys: Vec<u64> = self
+ .cels
+ .par_iter()
+ .map(|(l, c)| cache.key(&fs::read(bundle.strokes_path(l, c)).unwrap_or_default()))
+ .collect();
+ planes::key(self.base, &keys)
+ }
+}
+
+fn thumbs_of(doc: &Document, frame: u32, rasters: &Rasters) -> planes::Thumbs {
+ let size = (doc.canvas.width, doc.canvas.height);
+ paint_cels(doc, frame)
+ .par_iter()
+ .filter_map(|(_, c)| rasters.get(c).map(|r| (c.clone(), thumbnail(r, size, THUMB))))
+ .collect()
+}
+
+pub struct FrameDone {
+ pub image: FrameImage,
+ rev: u64,
+ paint: Vec<Loaded>,
+ vector: Vec<(String, u64, Raster)>,
+}
+
+impl FrameDone {
+ pub fn loaded_bytes(&self) -> usize {
+ self.paint.iter().map(|(_, r, _)| r.bytes()).sum::<usize>()
+ + self.vector.iter().map(|(_, _, r)| r.bytes()).sum::<usize>()
+ }
+}
+
+fn image_at(raster: &Raster, level: u32) -> (u32, u32, Vec<u8>) {
+ let step = 1usize << level;
+ let (w, h) = (
+ (raster.width as usize).div_ceil(step),
+ (raster.height as usize).div_ceil(step),
+ );
+ let side = TILE / step;
+ let mut out = vec![0u8; w * h * 4];
+ let rows: Vec<(usize, Vec<u8>)> = (0..raster.rows)
+ .into_par_iter()
+ .map(|ty| {
+ let mut band = vec![0u8; w * side * 4];
+ (0..raster.cols).for_each(|tx| {
+ let Some(tile) = raster.at(ty * raster.cols + tx) else {
+ return;
+ };
+ (0..side).for_each(|y| {
+ (0..side).for_each(|x| {
+ let ox = tx * side + x;
+ if ox >= w {
+ return;
+ }
+ let mut sum = [0.0f32; 4];
+ (0..step).for_each(|dy| {
+ (0..step).for_each(|dx| {
+ let at = ((y * step + dy) * TILE + x * step + dx) * 4;
+ (0..4).for_each(|c| sum[c] += tile[at + c].to_f32());
+ })
+ });
+ let n = (step * step) as f32;
+ let to = (y * w + ox) * 4;
+ (0..4).for_each(|c| band[to + c] = ((sum[c] / n).clamp(0.0, 1.0) * 255.0).round() as u8);
+ })
+ });
+ });
+ (ty, band)
+ })
+ .collect();
+ rows.into_iter().for_each(|(ty, band)| {
+ let y0 = ty * side;
+ let lines = side.min(h.saturating_sub(y0));
+ out[y0 * w * 4..(y0 + lines) * w * 4].copy_from_slice(&band[..lines * w * 4]);
+ });
+ (w as u32, h as u32, out)
+}
+
+fn mip_chain(width: u32, height: u32, base: Vec<u8>) -> Vec<Vec<u8>> {
+ let levels = crate::gpu::levels_for((width, height));
+ let mut out = vec![base];
+ let (mut w, mut h) = (width as usize, height as usize);
+ while out.len() < levels as usize {
+ let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
+ let last = out.last().expect("a base level");
+ let next: Vec<u8> = (0..nw * nh * 4)
+ .map(|i| {
+ let (c, px) = (i % 4, i / 4);
+ let (x, y) = ((px % nw) * 2, (px / nw) * 2);
+ let at = |x: usize, y: usize| last[(y.min(h - 1) * w + x.min(w - 1)) * 4 + c] as u32;
+ ((at(x, y) + at(x + 1, y) + at(x, y + 1) + at(x + 1, y + 1) + 2) / 4) as u8
+ })
+ .collect();
+ out.push(next);
+ (w, h) = (nw, nh);
+ }
+ out
+}
+
+pub const THUMB: (u32, u32) = (40, 28);
+
+pub fn thumbnail(raster: &Raster, (cw, ch): (u32, u32), (tw, th): (u32, u32)) -> egui::ColorImage {
+ let scale = (cw as f32 / tw as f32).max(ch as f32 / th as f32).max(1e-3);
+ let (ox, oy) = (
+ (tw as f32 * scale - cw as f32) / 2.0,
+ (th as f32 * scale - ch as f32) / 2.0,
+ );
+ let step = ((scale / 12.0).ceil() as usize).max(1);
+ let texel = |px: usize, py: usize| -> [f32; 4] {
+ raster.get(px / TILE, py / TILE).map_or([0.0; 4], |t| {
+ let i = ((py % TILE) * TILE + px % TILE) * 4;
+ [t[i].to_f32(), t[i + 1].to_f32(), t[i + 2].to_f32(), t[i + 3].to_f32()]
+ })
+ };
+ let pixels = (0..th)
+ .flat_map(|y| (0..tw).map(move |x| (x, y)))
+ .map(|(x, y)| {
+ let checker = if (x / 4 + y / 4) % 2 == 0 { 0.82 } else { 0.66 };
+ let span = |t: u32, o: f32, size: u32| {
+ let a = ((t as f32 * scale - o).max(0.0) as usize).min(size as usize);
+ let b = (((t + 1) as f32 * scale - o).max(0.0) as usize).min(size as usize);
+ (a..b).step_by(step)
+ };
+ let (sum, n) = span(y, oy, ch)
+ .flat_map(|py| span(x, ox, cw).map(move |px| (px, py)))
+ .fold(([0.0f32; 4], 0usize), |(s, n), (px, py)| {
+ let t = texel(px, py);
+ ([s[0] + t[0], s[1] + t[1], s[2] + t[2], s[3] + t[3]], n + 1)
+ });
+ let mean = sum.map(|v| v / n.max(1) as f32);
+ let alpha = mean[3].clamp(0.0, 1.0);
+ let shown = alpha.sqrt();
+ let [r, g, b] = [0, 1, 2].map(|k| {
+ let straight = if alpha > 1e-4 { mean[k] / alpha } else { 0.0 };
+ ((straight * shown + checker * (1.0 - shown)).clamp(0.0, 1.0) * 255.0) as u8
+ });
+ egui::Color32::from_rgb(r, g, b)
+ })
+ .collect();
+ egui::ColorImage {
+ size: [tw as usize, th as usize],
+ source_size: egui::vec2(tw as f32, th as f32),
+ pixels,
+ }
+}
+
+const PICTURE: &[u8; 4] = b"DAP1";
+pub const PICTURES: u64 = 1 << 30;
+
+pub fn picture_path(dir: &Path, key: u64) -> std::path::PathBuf {
+ dir.join(format!("{key:016x}.pic"))
+}
+
+fn read_picture(dir: &Path, key: u64) -> Option<FrameImage> {
+ let path = picture_path(dir, key);
+ let bytes = fs::read(&path).ok()?;
+ let head = |i: usize| {
+ bytes
+ .get(4 + i * 4..8 + i * 4)
+ .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ };
+ let (engine, width, height) = (head(0)?, head(1)?, head(2)?);
+ if bytes.get(..4)? != PICTURE || engine != klad_brush::ENGINE_VERSION {
+ return None;
+ }
+ let base = zstd::decode_all(bytes.get(16..)?).ok()?;
+ if base.len() != width as usize * height as usize * 4 {
+ return None;
+ }
+ let _ = fs::File::options()
+ .write(true)
+ .open(&path)
+ .and_then(|f| f.set_modified(std::time::SystemTime::now()));
+ Some(FrameImage {
+ key,
+ width,
+ height,
+ mips: mip_chain(width, height, base),
+ })
+}
+
+fn write_picture(dir: &Path, image: &FrameImage) -> Result<()> {
+ fs::create_dir_all(dir)?;
+ let mut bytes = PICTURE.to_vec();
+ [klad_brush::ENGINE_VERSION, image.width, image.height]
+ .iter()
+ .for_each(|v| bytes.extend(v.to_le_bytes()));
+ bytes.extend(zstd::encode_all(&image.mips[0][..], 1)?);
+ write_atomic(&picture_path(dir, image.key), &bytes)?;
+ klad_brush::cache::prune(dir, PICTURES);
+ Ok(())
+}
+
+fn picture(
+ doc: &Document,
+ frame: u32,
+ key: u64,
+ level: u32,
+ rasters: &Rasters,
+ onions: Option<&Onions>,
+) -> Result<FrameImage> {
+ let layers: Vec<&Layer> = doc.layers.iter().collect();
+ let flat = flatten_with(
+ doc,
+ frame,
+ rasters,
+ &layers,
+ doc.canvas.background.as_deref(),
+ onions,
+ true,
+ )?;
+ let (width, height, base) = image_at(&flat, level);
+ Ok(FrameImage {
+ key,
+ width,
+ height,
+ mips: mip_chain(width, height, base),
+ })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Prepared {
+ Already,
+ Drawings(usize),
+ Frame(usize),
+}
+
+impl FrameRequest {
+ pub fn prepare(self) -> Result<Prepared> {
+ let dir = self
+ .disk
+ .clone()
+ .ok_or_else(|| anyhow!("no folder for frame pictures"))?;
+ let cache = CelCache::new(&self.bundle, &self.brushes, Write::Always);
+ let pictured = picture_path(&dir, self.key).exists();
+ let planes_key = self.planes.as_ref().map(|p| p.key(&self.bundle, &self.brushes));
+ let planned = self
+ .planes
+ .as_ref()
+ .zip(planes_key)
+ .is_none_or(|(p, key)| planes::path(&p.dir, key).exists());
+ let todo: Vec<&(String, String)> = self
+ .paint
+ .iter()
+ .filter(|(layer, cel)| !cache.holds(&self.bundle, layer, cel))
+ .collect();
+ if pictured && planned && todo.is_empty() {
+ return Ok(Prepared::Already);
+ }
+ if pictured && planned {
+ todo.par_iter()
+ .try_for_each(|(layer, cel)| cache.load(&self.bundle, &self.brushes, layer, cel, false).map(|_| ()))?;
+ return Ok(Prepared::Drawings(todo.len()));
+ }
+ let doc = &self.bundle.doc;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let mut rasters: Rasters = self
+ .paint
+ .par_iter()
+ .map(|(layer, cel)| {
+ cache
+ .load(&self.bundle, &self.brushes, layer, cel, false)
+ .map(|l| (cel.clone(), l.raster))
+ })
+ .collect::<Result<_>>()?;
+ let vectors = self
+ .vector
+ .par_iter()
+ .map(|(cel, _, nodes)| rasterize_nodes(nodes, w, h).map(|r| (cel.clone(), r)))
+ .collect::<Result<Vec<_>>>()?;
+ rasters.extend(vectors);
+ let onions = self.plan.as_ref().map(|plan| onion::build(doc, plan, &rasters));
+ if !pictured {
+ write_picture(
+ &dir,
+ &picture(doc, self.frame, self.key, self.level, &rasters, onions.as_ref())?,
+ )?;
+ }
+ if let (Some(p), Some(key), false) = (&self.planes, planes_key, planned)
+ && let Some((below, above)) = caches(doc, self.frame, &p.active, &rasters, &onions.unwrap_or_default())?
+ {
+ let thumbs = match !self.paint.is_empty() {
+ true => thumbs_of(doc, self.frame, &rasters),
+ false => Vec::new(),
+ };
+ planes::write(&p.dir, key, &below, &above, &thumbs)?;
+ }
+ Ok(match pictured {
+ true => Prepared::Drawings(todo.len()),
+ false => Prepared::Frame(todo.len()),
+ })
+ }
+
+ pub fn run(self) -> Result<FrameDone> {
+ if let Some(image) = self.disk.as_deref().and_then(|d| read_picture(d, self.key)) {
+ return Ok(FrameDone {
+ image,
+ rev: self.rev,
+ paint: Vec::new(),
+ vector: Vec::new(),
+ });
+ }
+ let start = std::time::Instant::now();
+ let doc = &self.bundle.doc;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let paint = self
+ .paint
+ .par_iter()
+ .map(|(layer, cel)| {
+ load_paint(&self.bundle, layer, cel, &self.brushes).with_context(|| format!("cel {cel}"))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let vector = self
+ .vector
+ .par_iter()
+ .map(|(cel, hash, nodes)| rasterize_nodes(nodes, w, h).map(|r| (cel.clone(), *hash, r)))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rasters = self.rasters;
+ paint.iter().for_each(|(id, raster, _)| {
+ rasters.insert(id.clone(), raster.clone());
+ });
+ vector.iter().for_each(|(id, _, raster)| {
+ rasters.insert(id.clone(), raster.clone());
+ });
+ let onions = self.plan.as_ref().map(|plan| onion::build(doc, plan, &rasters));
+ let image = picture(doc, self.frame, self.key, self.level, &rasters, onions.as_ref())?;
+ if let Some(dir) = self.disk.as_deref().filter(|_| start.elapsed() >= self.keep_after) {
+ write_picture(dir, &image)?;
+ }
+ let mut paint = paint;
+ paint.iter_mut().for_each(|(_, _, data)| data.replay.drop_checkpoints());
+ Ok(FrameDone {
+ image,
+ rev: self.rev,
+ paint,
+ vector,
+ })
+ }
+}
+
+pub struct FrameJob {
+ bundle: Bundle,
+ paint: Vec<(String, String)>,
+ vector: Vec<(String, u64, Vec<Node>)>,
+ brushes: BrushSet,
+}
+
+pub struct LoadedFrame {
+ paint: Vec<Loaded>,
+ vector: Vec<(String, u64, Raster)>,
+}
+
+pub struct CanvasRequest {
+ frame: u32,
+ active: Vec<usize>,
+ rev: u64,
+ bundle: Bundle,
+ rasters: Rasters,
+ paint: Vec<(String, String)>,
+ vector: Vec<(String, u64, Vec<Node>)>,
+ plan: Plan,
+ onion: bool,
+ lean: bool,
+ keep: Option<String>,
+ brushes: BrushSet,
+ planes: Option<PlanesAsk>,
+ picture: Option<(
+ u64,
+ u32,
+ std::path::PathBuf,
+ std::sync::Arc<std::sync::atomic::AtomicU64>,
+ )>,
+}
+
+pub struct CanvasDone {
+ pub frame: u32,
+ pub loaded: usize,
+ pub bytes: usize,
+ active: Vec<usize>,
+ rev: u64,
+ paint: Vec<Loaded>,
+ vector: Vec<(String, u64, Raster)>,
+ onions: Onions,
+ caches: Option<(Raster, Raster)>,
+ pub thumbs: Vec<(String, egui::ColorImage)>,
+ strokes: Vec<(String, CelData)>,
+}
+
+impl CanvasRequest {
+ pub fn with_picture(
+ self,
+ key: u64,
+ level: u32,
+ dir: std::path::PathBuf,
+ written: std::sync::Arc<std::sync::atomic::AtomicU64>,
+ ) -> Self {
+ Self {
+ picture: Some((key, level, dir, written)),
+ ..self
+ }
+ }
+
+ pub fn run(self) -> Result<CanvasDone> {
+ let doc = &self.bundle.doc;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let planes_key = self.planes.as_ref().map(|p| p.key(&self.bundle, &self.brushes));
+ let stored = self
+ .planes
+ .as_ref()
+ .zip(planes_key)
+ .and_then(|(p, key)| planes::read(&p.dir, key).ok());
+ let keep: BTreeSet<&str> = self
+ .keep
+ .iter()
+ .map(String::as_str)
+ .chain(
+ self.plan
+ .iter()
+ .flat_map(|(_, ghosts)| ghosts.iter().map(|g| g.cel.as_str())),
+ )
+ .collect();
+ let lean_hit = stored.is_some() && self.lean;
+ let records = CelCache::new(&self.bundle, &self.brushes, Write::Never);
+ let (wanted, strokes): Wanted = self
+ .paint
+ .par_iter()
+ .map(|pair| {
+ let (layer, cel) = pair;
+ match lean_hit && !keep.contains(cel.as_str()) {
+ true => match records.strokes(&self.bundle, layer, cel).ok().flatten() {
+ Some((replay, file_hash)) => (None, Some((cel.clone(), CelData { replay, file_hash }))),
+ None => (Some(pair), None),
+ },
+ false => (Some(pair), None),
+ }
+ })
+ .fold(
+ || (Vec::new(), Vec::new()),
+ |(mut w, mut s), (a, b)| {
+ w.extend(a);
+ s.extend(b);
+ (w, s)
+ },
+ )
+ .reduce(
+ || (Vec::new(), Vec::new()),
+ |(mut w, mut s), (a, b)| {
+ w.extend(a);
+ s.extend(b);
+ (w, s)
+ },
+ );
+ let mut paint = wanted
+ .par_iter()
+ .map(|(layer, cel)| {
+ load_paint(&self.bundle, layer, cel, &self.brushes).with_context(|| format!("cel {cel}"))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ paint
+ .iter_mut()
+ .filter(|(id, _, _)| Some(id) != self.keep.as_ref())
+ .for_each(|(_, _, data)| data.replay.drop_checkpoints());
+ let vector = self
+ .vector
+ .par_iter()
+ .map(|(cel, hash, nodes)| rasterize_nodes(nodes, w, h).map(|r| (cel.clone(), *hash, r)))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rasters = self.rasters;
+ paint.iter().for_each(|(id, raster, _)| {
+ rasters.insert(id.clone(), raster.clone());
+ });
+ vector.iter().for_each(|(id, _, raster)| {
+ rasters.insert(id.clone(), raster.clone());
+ });
+ let onions = onion::build(doc, &self.plan, &rasters);
+ let (caches, kept_thumbs) = match stored {
+ Some(stored) => (Some((stored.below, stored.above)), Some(stored.thumbs)),
+ None => (caches(doc, self.frame, &self.active, &rasters, &onions)?, None),
+ };
+ if let Some((key, level, dir, written)) = self
+ .picture
+ .filter(|(key, _, dir, _)| !picture_path(dir, *key).exists())
+ {
+ let (doc, frame, rasters) = (doc.clone(), self.frame, rasters.clone());
+ let onions = self.onion.then(|| onions.clone());
+ crate::background().spawn(move || {
+ if let Ok(image) = picture(&doc, frame, key, level, &rasters, onions.as_ref())
+ && write_picture(&dir, &image).is_ok()
+ {
+ written.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
+ });
+ }
+ let bytes = paint.iter().map(|(_, r, _)| r.bytes()).sum::<usize>()
+ + vector.iter().map(|(_, _, r)| r.bytes()).sum::<usize>();
+ let thumbs = match (kept_thumbs, self.lean || bytes > crate::frames::HEAVY) {
+ (Some(kept), _) => kept,
+ (None, true) => thumbs_of(doc, self.frame, &rasters),
+ (None, false) => Vec::new(),
+ };
+ if let (Some(p), Some(key), Some((below, above))) = (&self.planes, planes_key, &caches)
+ && !planes::path(&p.dir, key).exists()
+ {
+ let (dir, below, above, thumbs) = (p.dir.clone(), below.clone(), above.clone(), thumbs.clone());
+ crate::background().spawn(move || {
+ let _ = planes::write(&dir, key, &below, &above, &thumbs);
+ });
+ }
+ Ok(CanvasDone {
+ frame: self.frame,
+ loaded: paint.len() + vector.len(),
+ bytes,
+ thumbs,
+ active: self.active,
+ rev: self.rev,
+ paint,
+ vector,
+ onions,
+ caches,
+ strokes,
+ })
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn compose_items(
+ doc: &Document,
+ frame: u32,
+ rasters: &Rasters,
+ onions: Option<&Onions>,
+ items: &[&Layer],
+ index: usize,
+ background: Option<&str>,
+ under: Option<&[f16]>,
+) -> Result<Option<Vec<f16>>> {
+ let cols = (doc.canvas.width as usize).div_ceil(TILE);
+ if items.iter().all(|l| !l.visible) && background.is_none() && under.is_none() {
+ return Ok(None);
+ }
+ let visible: Vec<TileItem> = items
+ .iter()
+ .map(|l| TileItem::Layer(l))
+ .chain(under.map(|tile| TileItem::Pixels {
+ tile,
+ opacity: 1.0,
+ blend: Blend::Normal,
+ }))
+ .collect();
+ let job = TileJob {
+ frame,
+ rasters,
+ background,
+ tx: index % cols,
+ ty: index / cols,
+ swap: None,
+ onions,
+ doc,
+ references: true,
+ };
+ compose_tile(&visible, &job).map(Some)
+}
+
+fn fast_split<'a>(doc: &'a Document, active: &[usize]) -> Option<Split<'a>> {
+ let is_paint = doc
+ .locate_path(active)
+ .is_some_and(|l| l.kind() == Kind::Paint && doc.effects_of(l).is_empty());
+ split(doc, &doc.layers, active)
+ .filter(|_| is_paint)
+ .filter(|(_, _, through)| *through)
+}
+
+type Caches = Vec<(usize, Option<Vec<f16>>, Option<Vec<f16>>)>;
+
+fn cache_tiles(
+ doc: &Document,
+ frame: u32,
+ active: &[usize],
+ rasters: &Rasters,
+ onions: &Onions,
+ tiles: &[usize],
+) -> Result<Option<Caches>> {
+ let Some((below, above, _)) = fast_split(doc, active) else {
+ return Ok(None);
+ };
+ let id = doc.locate_path(active).map(|l| l.id.clone()).unwrap_or_default();
+ let background = doc.canvas.background.as_deref();
+ let map = (!onions.is_empty()).then_some(onions);
+ let live = live_above(&above);
+ tiles
+ .par_iter()
+ .map(|&i| {
+ let under = onions.get(&id).and_then(|r| r.at(i));
+ let upper = match live {
+ true => None,
+ false => compose_items(doc, frame, rasters, map, &above, i, None, None)?,
+ };
+ Ok((
+ i,
+ compose_items(doc, frame, rasters, map, &below, i, background, under)?,
+ upper,
+ ))
+ })
+ .collect::<Result<Vec<_>>>()
+ .map(Some)
+}
+
+fn caches(
+ doc: &Document,
+ frame: u32,
+ active: &[usize],
+ rasters: &Rasters,
+ onions: &Onions,
+) -> Result<Option<(Raster, Raster)>> {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let all: Vec<usize> = {
+ let r = Raster::new(w, h);
+ (0..r.cols * r.rows).collect()
+ };
+ let Some(fresh) = cache_tiles(doc, frame, active, rasters, onions, &all)? else {
+ return Ok(None);
+ };
+ let (mut below, mut above) = (Raster::new(w, h), Raster::new(w, h));
+ fresh.into_iter().for_each(|(i, b, a)| {
+ if let Some(b) = b {
+ below.put(i, b.into_boxed_slice());
+ }
+ if let Some(a) = a {
+ above.put(i, a.into_boxed_slice());
+ }
+ });
+ Ok(Some((below, above)))
+}
+
+impl FrameJob {
+ pub fn run(self) -> Result<LoadedFrame> {
+ let (w, h) = (self.bundle.doc.canvas.width, self.bundle.doc.canvas.height);
+ let paint = self
+ .paint
+ .par_iter()
+ .map(|(layer, cel)| {
+ load_paint(&self.bundle, layer, cel, &self.brushes).with_context(|| format!("cel {cel}"))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let vector = self
+ .vector
+ .par_iter()
+ .map(|(cel, hash, nodes)| rasterize_nodes(nodes, w, h).map(|r| (cel.clone(), *hash, r)))
+ .collect::<Result<Vec<_>>>()?;
+ Ok(LoadedFrame { paint, vector })
+ }
+}
+
+const MASK_TINT: [f32; 3] = [0.92, 0.16, 0.2];
+const MASK_TINT_STRENGTH: f32 = 0.45;
+
+fn tint(tile: &mut [f16], mask: &[f16]) {
+ tile.as_chunks_mut::<4>()
+ .0
+ .iter_mut()
+ .zip(mask.as_chunks::<4>().0)
+ .for_each(|(px, m)| {
+ let a = m[3].to_f32() * MASK_TINT_STRENGTH;
+ if a > 0.0 {
+ (0..3).for_each(|c| px[c] = f16::from_f32(MASK_TINT[c] * a + px[c].to_f32() * (1.0 - a)));
+ px[3] = f16::from_f32(a + px[3].to_f32() * (1.0 - a));
+ }
+ });
+}
+
+const MEMO_BYTES: usize = 256 << 20;
+
+type Loaded = (String, Raster, CelData);
+type Wanted<'a> = (Vec<&'a (String, String)>, Vec<(String, CelData)>);
+
+fn load_paint(bundle: &Bundle, layer: &str, cel: &str, brushes: &BrushSet) -> Result<Loaded> {
+ let load = CelCache::new(bundle, brushes, Write::WhenSlow).load(bundle, brushes, layer, cel, true)?;
+ Ok((
+ cel.to_string(),
+ load.raster,
+ CelData {
+ replay: load.replay,
+ file_hash: load.file_hash,
+ },
+ ))
+}
+
+fn paint_cels(doc: &Document, frame: u32) -> Vec<(String, String)> {
+ doc.paint_content_at(frame)
+ .iter()
+ .map(|(l, c)| (l.id.clone(), c.id.clone()))
+ .collect()
+}
+
+fn nodes_hash(nodes: &[Node]) -> u64 {
+ fnv(FNV_OFFSET, &serde_json::to_vec(nodes).unwrap_or_default())
+}
+
+fn vector_cels(doc: &Document, frame: u32) -> Vec<(String, u64)> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(frame))
+ .map(|c| (c.id.clone(), nodes_hash(&c.nodes)))
+ .collect()
+}
+
+fn vector_ids(doc: &Document, frame: u32) -> Vec<String> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(frame))
+ .map(|c| c.id.clone())
+ .collect()
+}
+
+fn cel_nodes<'a>(doc: &'a Document, cel: &str) -> Option<&'a [Node]> {
+ match doc.item(cel)? {
+ klad_core::doc::Item::Cel(_, c) => Some(&c.nodes),
+ _ => None,
+ }
+}
+
+fn drawings(doc: &Document) -> BTreeMap<String, (String, Kind)> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() != Kind::Group)
+ .flat_map(|l| {
+ l.cels()
+ .iter()
+ .filter(|c| c.link.is_none())
+ .map(move |c| (c.id.clone(), (l.id.clone(), l.kind())))
+ })
+ .collect()
+}
+
+fn nodes_of(doc: &Document, cel: &str) -> Vec<Node> {
+ match doc.locate(cel) {
+ Some(Loc::Cel(path, c)) => doc.layer_at(&path).cels()[c].nodes.clone(),
+ _ => Vec::new(),
+ }
+}
+
+fn structure(doc: &Document, frame: u32) -> u64 {
+ fn walk(layers: &[Layer], frame: u32, out: &mut Vec<u8>) {
+ layers.iter().for_each(|l| {
+ out.extend(l.id.as_bytes());
+ out.extend(l.kind().name().as_bytes());
+ out.extend(l.opacity.to_le_bytes());
+ out.push(l.blend as u8);
+ out.push(l.visible as u8);
+ out.push(l.clip as u8);
+ out.extend(serde_json::to_vec(&l.effects).unwrap_or_default());
+ out.extend(l.depth.unwrap_or(-1.0).to_le_bytes());
+ out.push(l.reference as u8);
+ if let Some(adjust) = l.adjustment() {
+ out.extend(serde_json::to_vec(adjust).unwrap_or_default());
+ }
+ out.extend(l.content_at(frame).map_or(&b"-"[..], |c| c.id.as_bytes()));
+ out.push(b'[');
+ walk(l.mask.as_deref().map_or(&[][..], std::slice::from_ref), frame, out);
+ out.push(b']');
+ out.push(b'(');
+ walk(l.children(), frame, out);
+ out.push(b')');
+ });
+ }
+ let mut bytes = Vec::new();
+ walk(&doc.layers, frame, &mut bytes);
+ bytes.extend(doc.canvas.background.as_deref().unwrap_or("").as_bytes());
+ bytes.extend(serde_json::to_vec(&doc.atmosphere).unwrap_or_default());
+ fnv(FNV_OFFSET, &bytes)
+}
+
+type Split<'a> = (Vec<&'a Layer>, Vec<&'a Layer>, bool);
+
+fn alone(layers: &[Layer], i: usize) -> bool {
+ let layer = &layers[i];
+ !layer.clip && layer.mask.is_none() && layers.get(i + 1).is_none_or(|next| !next.clip)
+}
+
+fn split<'a>(doc: &Document, layers: &'a [Layer], path: &[usize]) -> Option<Split<'a>> {
+ let (&i, rest) = path.split_first()?;
+ let target = layers.get(i)?;
+ let mut below: Vec<&Layer> = layers[..i].iter().collect();
+ let mut above: Vec<&Layer> = layers[i + 1..].iter().collect();
+ if rest.is_empty() {
+ return Some((below, above, alone(layers, i)));
+ }
+ let through = target.visible
+ && target.opacity >= 1.0
+ && target.blend == Blend::Normal
+ && doc.effects_of(target).is_empty()
+ && !target.children().iter().any(Layer::reads_under)
+ && alone(layers, i);
+ let (inner_below, inner_above, inner) = split(doc, target.children(), rest)?;
+ let joins = inner_below.first().is_some_and(|l| l.clip);
+ below.extend(inner_below);
+ above = inner_above.into_iter().chain(above).collect();
+ Some((below, above, through && inner && !joins))
+}
+
+fn occupied(raster: Option<&Raster>) -> impl Iterator<Item = usize> + '_ {
+ raster.into_iter().flat_map(|r| r.occupied().map(|(i, _)| i))
+}
+
+impl Scene {
+ #[cfg(test)]
+ pub fn open(path: &Path) -> Result<Self> {
+ Self::open_at(path, 0)
+ }
+
+ pub fn open_lazy(path: &Path) -> Result<Self> {
+ let bundle = Bundle::open(path)?;
+ let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ let mut scene = Self {
+ keep_after: klad_brush::cache::SLOW,
+ lean: false,
+ bundle,
+ active: Vec::new(),
+ frame: 0,
+ rasters: Rasters::new(),
+ cels: BTreeMap::new(),
+ vector_hash: BTreeMap::new(),
+ memo: std::collections::VecDeque::new(),
+ below: Raster::new(w, h),
+ above: Raster::new(w, h),
+ fast: false,
+ unsaved: Patch::default(),
+ tint_mask: true,
+ used: BTreeMap::new(),
+ tick: 0,
+ budget: CACHE_BYTES,
+ stale: true,
+ onion: Onion::default(),
+ onion_on: false,
+ onion_marked: BTreeSet::new(),
+ onions: Onions::new(),
+ onion_key: FNV_OFFSET,
+ hashes: BTreeMap::new(),
+ };
+ scene.active = scene.default_active();
+ Ok(scene)
+ }
+
+ pub fn open_at(path: &Path, frame: u32) -> Result<Self> {
+ let bundle = Bundle::open(path)?;
+ let brushes = &BrushSet::for_bundle(&bundle)?;
+ let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ let frame = frame.min(bundle.doc.timeline.frames - 1);
+ let paint = paint_cels(&bundle.doc, frame)
+ .par_iter()
+ .map(|(layer, cel)| load_paint(&bundle, layer, cel, brushes).with_context(|| format!("cel {cel}")))
+ .collect::<Result<Vec<_>>>()?;
+ let vectors = vector_cels(&bundle.doc, frame);
+ let rasterized = vectors
+ .par_iter()
+ .map(|(cel, _)| rasterize_nodes(&nodes_of(&bundle.doc, cel), w, h).map(|r| (cel.clone(), r)))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rasters = Rasters::new();
+ let mut cels = BTreeMap::new();
+ paint.into_iter().for_each(|(id, raster, data)| {
+ rasters.insert(id.clone(), raster);
+ cels.insert(id, data);
+ });
+ rasters.extend(rasterized);
+ let mut scene = Self {
+ keep_after: klad_brush::cache::SLOW,
+ lean: false,
+ bundle,
+ active: Vec::new(),
+ frame,
+ rasters,
+ cels,
+ vector_hash: vectors.into_iter().collect(),
+ memo: std::collections::VecDeque::new(),
+ below: Raster::new(w, h),
+ above: Raster::new(w, h),
+ fast: false,
+ unsaved: Patch::default(),
+ tint_mask: true,
+ used: BTreeMap::new(),
+ tick: 0,
+ budget: CACHE_BYTES,
+ stale: false,
+ onion: Onion::default(),
+ onion_on: false,
+ onion_marked: BTreeSet::new(),
+ onions: Onions::new(),
+ onion_key: FNV_OFFSET,
+ hashes: BTreeMap::new(),
+ };
+ scene.active = scene.default_active();
+ scene.trim();
+ scene.rebuild_caches(None)?;
+ Ok(scene)
+ }
+
+ fn default_active(&self) -> Vec<usize> {
+ self.bundle
+ .doc
+ .all_layers()
+ .into_iter()
+ .rev()
+ .filter(|l| l.kind() == Kind::Paint)
+ .find_map(|l| match self.bundle.doc.locate(&l.id) {
+ Some(Loc::Layer(path)) if path.last() != Some(&MASK) => Some(path),
+ _ => None,
+ })
+ .unwrap_or_default()
+ }
+
+ pub fn active_is_mask(&self) -> bool {
+ self.active.last() == Some(&MASK)
+ }
+
+ pub fn active_locks_alpha(&self) -> bool {
+ self.active_layer().is_some_and(|l| l.lock_alpha)
+ }
+
+ pub fn size(&self) -> (u32, u32) {
+ (self.bundle.doc.canvas.width, self.bundle.doc.canvas.height)
+ }
+
+ pub fn cols(&self) -> usize {
+ self.below.cols
+ }
+
+ pub fn all_tiles(&self) -> Vec<usize> {
+ (0..self.below.cols * self.below.rows).collect()
+ }
+
+ pub fn active_layer(&self) -> Option<&Layer> {
+ self.bundle.doc.locate_path(&self.active)
+ }
+
+ pub fn active_id(&self) -> Option<String> {
+ self.active_layer().map(|l| l.id.clone())
+ }
+
+ pub fn can_paint(&self) -> bool {
+ self.active_layer()
+ .is_some_and(|l| l.kind() == Kind::Paint && !l.locked)
+ }
+
+ pub fn active_cel(&self) -> Option<String> {
+ self.active_layer()
+ .filter(|l| l.kind() == Kind::Paint)
+ .and_then(|l| l.content_at(self.frame))
+ .map(|c| c.id.clone())
+ }
+
+ pub fn active_marks(&self) -> &[Mark] {
+ self.active_cel()
+ .and_then(|c| self.cels.get(&c))
+ .map_or(&[], |d| d.marks())
+ }
+
+ pub fn marks_of(&self, cel: &str) -> &[Mark] {
+ self.cels.get(cel).map_or(&[], |d| d.marks())
+ }
+
+ pub fn active_raster(&self) -> Option<&Raster> {
+ self.rasters.get(&self.active_cel()?)
+ }
+
+ pub fn active_replay(&self) -> Option<(&CelReplay, &Raster)> {
+ let cel = self.active_cel()?;
+ Some((&self.cels.get(&cel)?.replay, self.rasters.get(&cel)?))
+ }
+
+ pub fn marks_at(&self, at: (f32, f32), slack: f32) -> Option<(Vec<usize>, u32)> {
+ let doc = &self.bundle.doc;
+ let shown = |path: &[usize]| (1..=path.len()).all(|n| doc.locate_path(&path[..n]).is_some_and(|l| l.visible));
+ let others = doc
+ .all_layers()
+ .into_iter()
+ .rev()
+ .filter_map(|l| match doc.locate(&l.id) {
+ Some(Loc::Layer(path)) => Some(path),
+ _ => None,
+ });
+ std::iter::once(self.active.clone())
+ .chain(others)
+ .filter(|path| path.last() != Some(&MASK) && shown(path))
+ .find_map(|path| {
+ let layer = doc.locate_path(&path)?;
+ if layer.kind() != Kind::Paint || layer.locked {
+ return None;
+ }
+ let marks = self.cels.get(&layer.content_at(self.frame)?.id)?.marks();
+ klad_core::markedit::hit(marks, at, slack).map(|id| (path, id))
+ })
+ }
+
+ pub fn total_marks(&self) -> usize {
+ self.cels.values().map(|c| c.marks().len()).sum()
+ }
+
+ pub fn raster_of(&self, cel: &str) -> Option<&Raster> {
+ self.rasters.get(cel)
+ }
+
+ #[cfg(test)]
+ pub fn set_active(&mut self, path: Vec<usize>) -> Result<()> {
+ self.active = path;
+ self.rebuild_caches(None)
+ }
+
+ pub fn set_active_later(&mut self, path: Vec<usize>) {
+ if path != self.active {
+ self.active = path;
+ self.stale = true;
+ self.trim();
+ }
+ }
+
+ pub fn canvas_request(&self, brushes: &BrushSet) -> CanvasRequest {
+ let frame = self.frame;
+ let plan = self.onion_plan(frame);
+ let (paint, vector) = self.needs(frame, self.onion_on.then_some(&plan));
+ let doc = &self.bundle.doc;
+ let rasters: Rasters = paint
+ .iter()
+ .map(|(_, c)| c)
+ .filter(|c| self.has_pixels(c))
+ .chain(vector.iter().filter(|c| self.vector_loaded(c)))
+ .filter_map(|c| self.rasters.get(c).map(|r| (c.clone(), r.clone())))
+ .collect();
+ CanvasRequest {
+ frame,
+ active: self.active.clone(),
+ rev: doc.rev,
+ bundle: Bundle {
+ root: self.bundle.root.clone(),
+ doc: doc.clone(),
+ },
+ rasters,
+ paint: paint.into_iter().filter(|(_, c)| !self.has_pixels(c)).collect(),
+ vector: vector
+ .into_iter()
+ .filter(|c| !self.vector_loaded(c))
+ .map(|c| {
+ let nodes = nodes_of(doc, &c);
+ (c, nodes_hash(&nodes), nodes)
+ })
+ .collect(),
+ plan,
+ onion: self.onion_on,
+ lean: self.lean,
+ keep: self.active_cel(),
+ brushes: brushes.clone(),
+ planes: self.planes_ask(frame),
+ picture: None,
+ }
+ }
+
+ pub fn adopt(&mut self, done: CanvasDone, wanted: bool) -> bool {
+ if done.rev != self.bundle.doc.rev {
+ return false;
+ }
+ self.take_loaded(done.paint, done.vector);
+ done.strokes.into_iter().for_each(|(id, data)| {
+ if self.cels.get(&id).is_none_or(|d| d.file_hash != data.file_hash) {
+ self.cels.insert(id, data);
+ }
+ });
+ let fits = wanted && done.frame == self.frame && done.active == self.active;
+ if fits {
+ self.onions = done.onions;
+ self.onion_key = onion::plan_hash(&self.onion_plan(self.frame), |cel| self.loaded_version(cel));
+ let (w, h) = self.size();
+ (self.below, self.above, self.fast) = match done.caches {
+ Some((below, above)) => (below, above, true),
+ None => (Raster::new(w, h), Raster::new(w, h), false),
+ };
+ self.stale = false;
+ }
+ self.trim();
+ self.slim();
+ fits
+ }
+
+ fn has_pixels(&self, cel: &str) -> bool {
+ self.cels.contains_key(cel) && self.rasters.contains_key(cel)
+ }
+
+ fn slimmed(&self) -> bool {
+ self.lean
+ && paint_cels(&self.bundle.doc, self.frame)
+ .iter()
+ .any(|(_, c)| !self.rasters.contains_key(c))
+ }
+
+ fn slim(&mut self) {
+ if !(self.lean && self.fast && !self.stale) {
+ return;
+ }
+ let active = self.active_cel();
+ let garbage: Vec<Raster> = paint_cels(&self.bundle.doc, self.frame)
+ .into_iter()
+ .filter(|(_, c)| Some(c) != active.as_ref())
+ .filter_map(|(_, c)| self.rasters.remove(&c))
+ .collect();
+ if !garbage.is_empty() {
+ std::thread::spawn(move || drop(garbage));
+ }
+ }
+
+ fn onion_map(&self) -> Option<&Onions> {
+ (!self.onions.is_empty()).then_some(&self.onions)
+ }
+
+ fn onion_tile(&self, layer: &str, index: usize) -> Option<&[f16]> {
+ self.onions.get(layer).and_then(|r| r.at(index))
+ }
+
+ pub fn rebuild_caches(&mut self, tiles: Option<&[usize]>) -> Result<()> {
+ if self.slimmed() {
+ self.stale = true;
+ return Ok(());
+ }
+ let (w, h) = self.size();
+ let full = tiles.is_none() || !self.fast || self.stale;
+ let wanted: Vec<usize> = match tiles {
+ Some(t) if !full => dilate(
+ t,
+ effect_reach(&self.bundle.doc, &self.bundle.doc.layers),
+ self.cols(),
+ self.rows(),
+ ),
+ _ => self.all_tiles(),
+ };
+ let fresh = cache_tiles(
+ &self.bundle.doc,
+ self.frame,
+ &self.active,
+ &self.rasters,
+ &self.onions,
+ &wanted,
+ )?;
+ let Some(fresh) = fresh else {
+ self.fast = false;
+ self.stale = false;
+ self.below = Raster::new(w, h);
+ self.above = Raster::new(w, h);
+ return Ok(());
+ };
+ if full {
+ self.below = Raster::new(w, h);
+ self.above = Raster::new(w, h);
+ }
+ fresh.into_iter().for_each(|(i, b, a)| {
+ match b {
+ Some(b) => self.below.put(i, b.into_boxed_slice()),
+ None => self.below.clear(i),
+ }
+ match a {
+ Some(a) => self.above.put(i, a.into_boxed_slice()),
+ None => self.above.clear(i),
+ }
+ });
+ self.fast = true;
+ self.stale = false;
+ Ok(())
+ }
+
+ pub fn compose(&self, tiles: &[usize], preview: Option<&Preview>) -> Result<Vec<(usize, Vec<f16>)>> {
+ self.compose_painting(&[], tiles, preview)
+ }
+
+ fn active_reach(&self) -> i32 {
+ (1..=self.active.len())
+ .filter_map(|n| self.bundle.doc.locate_path(&self.active[..n]))
+ .map(|l| klad_render::effects::margin(&self.bundle.doc.effects_of(l), 1.0))
+ .sum()
+ }
+
+ pub fn compose_painting(
+ &self,
+ stroke: &[usize],
+ other: &[usize],
+ preview: Option<&Preview>,
+ ) -> Result<Vec<(usize, Vec<f16>)>> {
+ let (cols, rows) = (self.cols(), self.rows());
+ let doc = &self.bundle.doc;
+ let near = self.active_reach();
+ let tiles: Vec<usize> = dilate(stroke, near, cols, rows)
+ .into_iter()
+ .chain(dilate(other, effect_reach(doc, &doc.layers), cols, rows))
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ let cel = self.active_cel();
+ let owns: SwapTiles = match (preview, cel.as_deref()) {
+ (Some(p), Some(c)) => dilate(&tiles, near, cols, rows)
+ .into_par_iter()
+ .filter(|i| p.buffer.coverage(*i).is_some() || p.twin.is_some_and(|t| t.coverage(*i).is_some()))
+ .map(|i| {
+ let mut tile = self
+ .rasters
+ .get(c)
+ .and_then(|r| r.at(i))
+ .map_or_else(|| vec![f16::ZERO; TILE_PX * 4], <[f16]>::to_vec);
+ klad_brush::land_tile(&mut tile, p.buffer, i, p.color, p.opacity, p.blend);
+ if let Some(twin) = p.twin.filter(|t| t.coverage(i).is_some()) {
+ klad_brush::land_tile(&mut tile, twin, i, p.color, p.opacity, p.blend);
+ }
+ (i, Some(tile))
+ })
+ .collect(),
+ _ => SwapTiles::new(),
+ };
+ let split = self.fast.then(|| fast_split(doc, &self.active)).flatten();
+ let live: Option<Vec<&Layer>> = split
+ .filter(|(_, above, _)| live_above(above))
+ .map(|(_, above, _)| above);
+ tiles
+ .par_iter()
+ .map(|&i| Ok((i, self.compose_one(i, &owns, live.as_deref())?)))
+ .collect()
+ }
+
+ pub fn planes_job(&self) -> impl FnOnce() -> Result<Vec<(f32, egui::ColorImage)>> + Send + 'static {
+ let doc = self.bundle.doc.clone();
+ let rasters = self.rasters.clone();
+ let frame = self.frame;
+ move || {
+ let level = (doc.canvas.width.max(doc.canvas.height) as f32 / 1536.0)
+ .log2()
+ .ceil()
+ .max(0.0) as u32;
+ let background = doc.canvas.background.clone();
+ doc.layers
+ .iter()
+ .filter(|l| l.visible)
+ .enumerate()
+ .map(|(i, layer)| {
+ let back = if i == 0 { background.as_deref() } else { None };
+ let flat = klad_render::flatten_with(&doc, frame, &rasters, &[layer], back, None, true)?;
+ let (w, h, rgba) = image_at(&flat, level);
+ Ok((
+ layer.depth.unwrap_or(0.0),
+ egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &rgba),
+ ))
+ })
+ .collect()
+ }
+ }
+
+ pub fn preview_layer(&mut self, layer: Layer) -> Result<()> {
+ let Some(Loc::Layer(path)) = self.bundle.doc.locate(&layer.id) else {
+ return Err(anyhow!("no layer {}", layer.id));
+ };
+ *self.bundle.doc.layer_at_mut(&path) = layer;
+ self.rebuild_caches(None)
+ }
+
+ pub fn rows(&self) -> usize {
+ (self.bundle.doc.canvas.height as usize).div_ceil(TILE)
+ }
+
+ fn compose_one(&self, index: usize, owns: &SwapTiles, live: Option<&[&Layer]>) -> Result<Vec<f16>> {
+ let (tx, ty) = (index % self.cols(), index / self.cols());
+ let doc = &self.bundle.doc;
+ let cel = self.active_cel();
+ let own: Option<&[f16]> = match owns.get(&index) {
+ Some(tile) => tile.as_deref(),
+ None => cel.as_ref().and_then(|c| self.rasters.get(c)).and_then(|r| r.at(index)),
+ };
+ if self.fast
+ && let Some(active) = self.active_layer()
+ {
+ let flat = |tile| TileItem::Pixels {
+ tile,
+ opacity: 1.0,
+ blend: Blend::Normal,
+ };
+ let own_item = own.filter(|_| active.visible).map(|tile| TileItem::Pixels {
+ tile,
+ opacity: active.opacity,
+ blend: active.blend,
+ });
+ let upper: Vec<TileItem> = match live {
+ Some(layers) => layers.iter().map(|l| TileItem::Layer(l)).collect(),
+ None => self.above.at(index).map(flat).into_iter().collect(),
+ };
+ let items: Vec<TileItem> = self
+ .below
+ .at(index)
+ .map(flat)
+ .into_iter()
+ .chain(own_item)
+ .chain(upper)
+ .collect();
+ let job = TileJob {
+ frame: self.frame,
+ rasters: &self.rasters,
+ background: None,
+ tx,
+ ty,
+ swap: None,
+ onions: None,
+ doc,
+ references: true,
+ };
+ return compose_tile(&items, &job);
+ }
+ let items: Vec<TileItem> = doc.layers.iter().map(TileItem::Layer).collect();
+ let swap = cel.as_deref().filter(|_| !owns.is_empty()).map(|c| Swap {
+ cel: c,
+ cols: self.cols(),
+ rows: self.rows(),
+ tiles: owns,
+ });
+ let job = TileJob {
+ frame: self.frame,
+ rasters: &self.rasters,
+ background: doc.canvas.background.as_deref(),
+ tx,
+ ty,
+ swap,
+ onions: self.onion_map(),
+ doc,
+ references: true,
+ };
+ let mut tile = compose_tile(&items, &job)?;
+ if self.tint_mask
+ && self.active_is_mask()
+ && let Some(mask) = own
+ {
+ tint(&mut tile, mask);
+ }
+ Ok(tile)
+ }
+
+ fn ensure_active_cel(&mut self) -> Result<String> {
+ if let Some(cel) = self.active_cel() {
+ return Ok(cel);
+ }
+ let layer = self.active_id().ok_or_else(|| anyhow!("no active layer"))?;
+ let op = Op::AddCel {
+ cel: serde_json::json!({ "frame": self.frame }),
+ layer,
+ };
+ let (doc, applied) = apply_all(&self.bundle.doc, &[op])?;
+ let mut restore = diff(&doc, &self.bundle.doc)?;
+ restore.0.extend(std::mem::take(&mut self.unsaved).0);
+ self.unsaved = restore;
+ self.bundle.doc = doc;
+ let cel = applied
+ .added
+ .first()
+ .cloned()
+ .ok_or_else(|| anyhow!("no cel was added"))?;
+ let (w, h) = self.size();
+ self.rasters.insert(cel.clone(), Raster::new(w, h));
+ self.cels.insert(
+ cel.clone(),
+ CelData {
+ replay: CelReplay::new(w, h),
+ file_hash: fnv(FNV_OFFSET, &[]),
+ },
+ );
+ Ok(cel)
+ }
+
+ pub fn next_mark_id(&self) -> u32 {
+ next_id(self.active_marks())
+ }
+
+ pub fn commit_stroke(
+ &mut self,
+ stroke: Stroke,
+ buffer: &mut StrokeBuffer,
+ blend: StrokeBlend,
+ ) -> Result<Vec<usize>> {
+ let cel = self.ensure_active_cel()?;
+ let raster = self
+ .rasters
+ .get_mut(&cel)
+ .ok_or_else(|| anyhow!("cel {cel} has no pixels"))?;
+ let data = self
+ .cels
+ .get_mut(&cel)
+ .ok_or_else(|| anyhow!("cel {cel} has no strokes"))?;
+ Ok(data.replay.commit_stroke(raster, stroke, buffer, blend))
+ }
+
+ pub fn commit_fill(&mut self, fill: Fill, brushes: &BrushSet) -> Result<Vec<usize>> {
+ let cel = self.ensure_active_cel()?;
+ let raster = self
+ .rasters
+ .get_mut(&cel)
+ .ok_or_else(|| anyhow!("cel {cel} has no pixels"))?;
+ let data = self
+ .cels
+ .get_mut(&cel)
+ .ok_or_else(|| anyhow!("cel {cel} has no strokes"))?;
+ data.replay.paint(raster, Mark::Fill(fill), brushes)
+ }
+
+ pub fn fill_reference(&self, reference: &FillRef, brushes: &BrushSet) -> Result<Raster> {
+ let cel = self.active_cel().unwrap_or_default();
+ if *reference == FillRef::This || !self.slimmed() {
+ return fill_reference(&self.bundle.doc, self.frame, &self.rasters, &cel, reference);
+ }
+ let missing: Vec<(String, String)> = paint_cels(&self.bundle.doc, self.frame)
+ .into_iter()
+ .filter(|(_, c)| !self.rasters.contains_key(c))
+ .collect();
+ let loaded = missing
+ .par_iter()
+ .map(|(layer, cel)| load_paint(&self.bundle, layer, cel, brushes))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rasters = self.rasters.clone();
+ loaded.into_iter().for_each(|(id, raster, _)| {
+ rasters.insert(id, raster);
+ });
+ fill_reference(&self.bundle.doc, self.frame, &rasters, &cel, reference)
+ }
+
+ pub fn sample(&self, (x, y): (f32, f32), layer_only: bool) -> Result<Option<[f32; 4]>> {
+ let (w, h) = self.size();
+ if x < 0.0 || y < 0.0 || x >= w as f32 || y >= h as f32 {
+ return Ok(None);
+ }
+ let (x, y) = (x as usize, y as usize);
+ let index = (y / TILE) * self.cols() + x / TILE;
+ let at = ((y % TILE) * TILE + x % TILE) * 4;
+ let px: Option<[f32; 4]> = if layer_only {
+ self.active_cel()
+ .and_then(|c| self.rasters.get(&c))
+ .and_then(|r| r.at(index))
+ .map(|t| [t[at], t[at + 1], t[at + 2], t[at + 3]].map(f16::to_f32))
+ } else if self.slimmed() {
+ let composed = self.compose(&[index], None)?;
+ let tile = composed
+ .iter()
+ .find(|(i, _)| *i == index)
+ .map(|(_, t)| t)
+ .ok_or_else(|| anyhow!("tile {index} was not composed"))?;
+ Some([tile[at], tile[at + 1], tile[at + 2], tile[at + 3]].map(f16::to_f32))
+ } else {
+ let items: Vec<TileItem> = self.bundle.doc.layers.iter().map(TileItem::Layer).collect();
+ let tile = self.compose_with(&items, index, self.bundle.doc.canvas.background.as_deref(), false)?;
+ Some([tile[at], tile[at + 1], tile[at + 2], tile[at + 3]].map(f16::to_f32))
+ };
+ Ok(px.filter(|p| p[3] > 0.0).map(|[r, g, b, a]| {
+ let un = |c: f32| (c / a).clamp(0.0, 1.0);
+ [un(r), un(g), un(b), a.clamp(0.0, 1.0)]
+ }))
+ }
+
+ pub fn step(
+ &mut self,
+ stack: klad_core::history::Stack,
+ brushes: &BrushSet,
+ ) -> Result<Option<(String, Vec<usize>)>> {
+ let touched = klad_core::history::peek(&self.bundle, stack)?
+ .and_then(|(_, patch)| patch)
+ .and_then(|patch| patch.touched_cels(&self.bundle.doc));
+ let old = match touched {
+ Some(_) => None,
+ None => Some(self.bundle.doc.clone()),
+ };
+ let Some(entry) = klad_core::history::step(&mut self.bundle, stack)? else {
+ return Ok(None);
+ };
+ self.bundle.stamp("editor")?;
+ let dirty = match (old, touched) {
+ (Some(old), _) => self.sync(&old, brushes)?,
+ (None, Some(cels)) => self.sync_nodes(&cels, brushes)?,
+ (None, None) => unreachable!("one of the two is set"),
+ };
+ Ok(Some((entry.summary, dirty)))
+ }
+
+ pub fn onion_layers(&self) -> Vec<String> {
+ if !self.onion_on {
+ return Vec::new();
+ }
+ let active = self
+ .active_layer()
+ .filter(|l| matches!(l.kind(), Kind::Paint | Kind::Vector) && !self.active_is_mask())
+ .map(|l| l.id.clone());
+ active
+ .into_iter()
+ .chain(self.onion_marked.iter().cloned())
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect()
+ }
+
+ pub fn onion_plan(&self, frame: u32) -> Plan {
+ onion::plan(&self.bundle.doc, frame, &self.onion_layers(), &self.onion)
+ }
+
+ fn needs(&self, frame: u32, plan: Option<&Plan>) -> (Vec<(String, String)>, Vec<String>) {
+ let doc = &self.bundle.doc;
+ let ghosts = plan.map_or(Vec::new(), |p| onion::needed(doc, p));
+ let paint: BTreeSet<(String, String)> = paint_cels(doc, frame)
+ .into_iter()
+ .chain(
+ ghosts
+ .iter()
+ .filter(|(_, _, k)| *k == Kind::Paint)
+ .map(|(l, c, _)| (l.clone(), c.clone())),
+ )
+ .collect();
+ let vector: BTreeSet<String> = vector_ids(doc, frame)
+ .into_iter()
+ .chain(
+ ghosts
+ .iter()
+ .filter(|(_, _, k)| *k == Kind::Vector)
+ .map(|(_, c, _)| c.clone()),
+ )
+ .collect();
+ (paint.into_iter().collect(), vector.into_iter().collect())
+ }
+
+ fn vector_loaded(&self, cel: &str) -> bool {
+ self.vector_hash.contains_key(cel) && self.rasters.contains_key(cel)
+ }
+
+ pub fn has_frame(&self, frame: u32) -> bool {
+ let plan = self.onion_on.then(|| self.onion_plan(frame));
+ let (paint, vector) = self.needs(frame, plan.as_ref());
+ paint.iter().all(|(_, c)| self.has_pixels(c)) && vector.iter().all(|c| self.vector_loaded(c))
+ }
+
+ pub fn frame_job(&self, frame: u32, brushes: &BrushSet) -> Option<FrameJob> {
+ let doc = &self.bundle.doc;
+ let frame = frame.min(doc.timeline.frames - 1);
+ if self.has_frame(frame) {
+ return None;
+ }
+ let plan = self.onion_on.then(|| self.onion_plan(frame));
+ let (paint, vector) = self.needs(frame, plan.as_ref());
+ Some(FrameJob {
+ bundle: Bundle {
+ root: self.bundle.root.clone(),
+ doc: doc.clone(),
+ },
+ paint: paint.into_iter().filter(|(_, c)| !self.cels.contains_key(c)).collect(),
+ vector: vector
+ .into_iter()
+ .filter(|c| !self.vector_loaded(c))
+ .map(|c| {
+ let nodes = nodes_of(doc, &c);
+ (c, nodes_hash(&nodes), nodes)
+ })
+ .collect(),
+ brushes: brushes.clone(),
+ })
+ }
+
+ fn take_loaded(&mut self, paint: Vec<Loaded>, vector: Vec<(String, u64, Raster)>) {
+ paint.into_iter().for_each(|(id, raster, data)| {
+ self.rasters.entry(id.clone()).or_insert(raster);
+ if self.cels.get(&id).is_none_or(|d| d.file_hash != data.file_hash) {
+ self.cels.insert(id, data);
+ }
+ });
+ vector.into_iter().for_each(|(cel, hash, raster)| {
+ if !self.vector_loaded(&cel) {
+ self.rasters.insert(cel.clone(), raster);
+ self.vector_hash.insert(cel, hash);
+ }
+ });
+ }
+
+ #[cfg(test)]
+ pub fn set_frame(&mut self, frame: u32, brushes: &BrushSet) -> Result<Vec<usize>> {
+ self.move_to(frame);
+ self.refresh(brushes)?;
+ Ok(self.all_tiles())
+ }
+
+ pub fn move_to(&mut self, frame: u32) {
+ let frame = frame.min(self.bundle.doc.timeline.frames - 1);
+ if frame != self.frame {
+ self.frame = frame;
+ self.stale = true;
+ }
+ self.trim();
+ }
+
+ fn load_missing(&mut self, brushes: &BrushSet) -> Result<()> {
+ if let Some(job) = self.frame_job(self.frame, brushes) {
+ let loaded = job.run()?;
+ self.take_loaded(loaded.paint, loaded.vector);
+ }
+ Ok(())
+ }
+
+ pub fn refresh(&mut self, brushes: &BrushSet) -> Result<()> {
+ self.load_missing(brushes)?;
+ self.build_onions();
+ self.rebuild_caches(None)
+ }
+
+ fn build_onions(&mut self) -> Vec<usize> {
+ let plan = self.onion_plan(self.frame);
+ let key = onion::plan_hash(&plan, |cel| self.loaded_version(cel));
+ if key == self.onion_key {
+ return Vec::new();
+ }
+ let fresh = onion::build(&self.bundle.doc, &plan, &self.rasters);
+ let dirty: BTreeSet<usize> = self
+ .onions
+ .values()
+ .chain(fresh.values())
+ .flat_map(|r| r.occupied().map(|(i, _)| i))
+ .collect();
+ self.onions = fresh;
+ self.onion_key = key;
+ dirty.into_iter().collect()
+ }
+
+ #[cfg(test)]
+ pub fn refresh_onions(&mut self, brushes: &BrushSet) -> Result<Vec<usize>> {
+ self.load_missing(brushes)?;
+ let dirty = self.build_onions();
+ if !dirty.is_empty() {
+ self.rebuild_caches(Some(&dirty))?;
+ }
+ Ok(dirty)
+ }
+
+ fn loaded_version(&self, cel: &str) -> u64 {
+ match self.cels.get(cel) {
+ Some(data) => data.file_hash,
+ None => self.vector_hash.get(cel).copied().unwrap_or(0),
+ }
+ }
+
+ fn paint_version(&mut self, layer: &str, cel: &str) -> u64 {
+ if let Some(data) = self.cels.get(cel) {
+ return data.file_hash;
+ }
+ let path = self.bundle.strokes_path(layer, cel);
+ let now = stamp(&path);
+ if let (Some((was, hash)), Some(now)) = (self.hashes.get(cel), now)
+ && *was == now
+ {
+ return *hash;
+ }
+ let bytes = fs::read(&path).unwrap_or_default();
+ let hash = fnv(FNV_OFFSET, &bytes);
+ if let Some(now) = now {
+ self.hashes.insert(cel.to_string(), (now, hash));
+ }
+ hash
+ }
+
+ fn vector_version(&self, cel: &str) -> u64 {
+ match self.vector_loaded(cel) {
+ true => self.vector_hash[cel],
+ false => nodes_hash(&nodes_of(&self.bundle.doc, cel)),
+ }
+ }
+
+ pub fn frame_key(&mut self, frame: u32, onion: bool, level: u32, fingerprint: u64) -> u64 {
+ let plan = onion.then(|| self.onion_plan(frame));
+ let (paint, vector) = self.needs(frame, plan.as_ref());
+ let mut versions: BTreeMap<String, u64> = paint
+ .iter()
+ .map(|(layer, cel)| (cel.clone(), self.paint_version(layer, cel)))
+ .collect();
+ versions.extend(vector.iter().map(|cel| (cel.clone(), self.vector_version(cel))));
+ let mut hash = fnv(FNV_OFFSET, &structure(&self.bundle.doc, frame).to_le_bytes());
+ hash = versions
+ .iter()
+ .fold(hash, |h, (cel, v)| fnv(fnv(h, cel.as_bytes()), &v.to_le_bytes()));
+ if let Some(plan) = &plan {
+ let ghosts = onion::plan_hash(plan, |cel| versions.get(cel).copied().unwrap_or(0));
+ hash = fnv(fnv(hash, b"onion"), &ghosts.to_le_bytes());
+ }
+ fnv(hash, &[level as u64, fingerprint].map(u64::to_le_bytes).concat())
+ }
+
+ pub fn frame_request(&mut self, frame: u32, onion: bool, level: u32, brushes: &BrushSet) -> FrameRequest {
+ let key = self.frame_key(frame, onion, level, brushes.fingerprint());
+ let plan = onion.then(|| self.onion_plan(frame));
+ let (paint, vector) = self.needs(frame, plan.as_ref());
+ let doc = &self.bundle.doc;
+ let rasters: Rasters = paint
+ .iter()
+ .map(|(_, c)| c)
+ .filter(|c| self.cels.contains_key(*c))
+ .chain(vector.iter().filter(|c| self.vector_loaded(c)))
+ .filter_map(|c| self.rasters.get(c).map(|r| (c.clone(), r.clone())))
+ .collect();
+ FrameRequest {
+ frame,
+ key,
+ level,
+ rev: doc.rev,
+ bundle: Bundle {
+ root: self.bundle.root.clone(),
+ doc: doc.clone(),
+ },
+ rasters,
+ paint: paint.into_iter().filter(|(_, c)| !self.cels.contains_key(c)).collect(),
+ vector: vector
+ .into_iter()
+ .filter(|c| !self.vector_loaded(c))
+ .map(|c| {
+ let nodes = nodes_of(doc, &c);
+ (c, nodes_hash(&nodes), nodes)
+ })
+ .collect(),
+ plan,
+ brushes: brushes.clone(),
+ disk: Some(self.pictures()),
+ keep_after: self.keep_after,
+ planes: None,
+ }
+ }
+
+ pub fn prepare_request(&mut self, frame: u32, onion: bool, level: u32, brushes: &BrushSet) -> FrameRequest {
+ let key = self.frame_key(frame, onion, level, brushes.fingerprint());
+ let plan = onion.then(|| self.onion_plan(frame));
+ let (paint, vector) = self.needs(frame, plan.as_ref());
+ let doc = &self.bundle.doc;
+ FrameRequest {
+ frame,
+ key,
+ level,
+ rev: doc.rev,
+ bundle: Bundle {
+ root: self.bundle.root.clone(),
+ doc: doc.clone(),
+ },
+ rasters: Rasters::new(),
+ paint,
+ vector: vector
+ .into_iter()
+ .map(|c| {
+ let nodes = nodes_of(doc, &c);
+ (c, nodes_hash(&nodes), nodes)
+ })
+ .collect(),
+ plan,
+ brushes: brushes.clone(),
+ disk: Some(self.pictures()),
+ keep_after: std::time::Duration::ZERO,
+ planes: self.planes_ask(frame),
+ }
+ }
+
+ pub fn planes_ask(&self, frame: u32) -> Option<PlanesAsk> {
+ let doc = &self.bundle.doc;
+ fast_split(doc, &self.active)?;
+ let plan = self.onion_on.then(|| self.onion_plan(frame));
+ let ghosts = plan
+ .iter()
+ .flatten()
+ .flat_map(|(layer, ghosts)| ghosts.iter().map(move |g| (layer.clone(), g.cel.clone())));
+ let cels: Vec<(String, String)> = paint_cels(doc, frame)
+ .into_iter()
+ .chain(ghosts)
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ let path: Vec<u8> = self.active.iter().flat_map(|i| (*i as u64).to_le_bytes()).collect();
+ let base = vector_cels(doc, frame).iter().fold(
+ fnv(fnv(FNV_OFFSET, &structure(doc, frame).to_le_bytes()), &path),
+ |h, (cel, version)| fnv(fnv(h, cel.as_bytes()), &version.to_le_bytes()),
+ );
+ let base = match &plan {
+ Some(plan) => fnv(fnv(base, b"onion"), &onion::plan_hash(plan, |_| 0).to_le_bytes()),
+ None => base,
+ };
+ Some(PlanesAsk {
+ base,
+ cels,
+ dir: self.bundle.cache_dir().join("planes"),
+ active: self.active.clone(),
+ })
+ }
+
+ pub fn holding(&self) -> BTreeSet<String> {
+ self.cels
+ .keys()
+ .filter(|c| self.rasters.contains_key(*c))
+ .cloned()
+ .collect()
+ }
+
+ pub fn pictures(&self) -> std::path::PathBuf {
+ self.bundle.cache_dir().join("frames")
+ }
+
+ pub fn absorb(&mut self, done: FrameDone) -> FrameImage {
+ if done.rev == self.bundle.doc.rev {
+ self.take_loaded(done.paint, done.vector);
+ self.trim();
+ self.slim();
+ }
+ done.image
+ }
+
+ fn current(&self) -> BTreeSet<String> {
+ let doc = &self.bundle.doc;
+ paint_cels(doc, self.frame)
+ .into_iter()
+ .map(|(_, c)| c)
+ .chain(vector_ids(doc, self.frame))
+ .collect()
+ }
+
+ fn evict(&mut self, cel: &str) -> (Option<Raster>, Option<CelData>) {
+ let raster = match (self.rasters.remove(cel), self.vector_hash.remove(cel)) {
+ (Some(raster), Some(hash)) => {
+ self.retire(cel, hash, raster);
+ None
+ }
+ (raster, _) => raster,
+ };
+ self.used.remove(cel);
+ (raster, self.cels.remove(cel))
+ }
+
+ fn trim(&mut self) {
+ let current = self.current();
+ let ghosts: BTreeSet<String> = onion::needed(&self.bundle.doc, &self.onion_plan(self.frame))
+ .into_iter()
+ .map(|(_, c, _)| c)
+ .collect();
+ self.tick += 1;
+ let tick = self.tick;
+ current.iter().chain(&ghosts).for_each(|c| {
+ self.used.insert(c.clone(), tick);
+ });
+ let active = self.active_cel();
+ self.cels
+ .iter_mut()
+ .filter(|(id, _)| Some(*id) != active.as_ref())
+ .for_each(|(_, data)| data.replay.drop_checkpoints());
+ let mut others: Vec<(u64, String, usize)> = self
+ .rasters
+ .iter()
+ .filter(|(id, _)| !current.contains(*id) && !ghosts.contains(*id))
+ .map(|(id, r)| (self.used.get(id).copied().unwrap_or(0), id.clone(), r.bytes()))
+ .collect();
+ others.sort_by_key(|a| std::cmp::Reverse(a.0));
+ let mut total = 0usize;
+ let over: Vec<String> = others
+ .into_iter()
+ .filter(|(_, _, bytes)| {
+ total += bytes;
+ total > self.budget
+ })
+ .map(|(_, id, _)| id)
+ .collect();
+ let garbage: Vec<_> = over.iter().map(|id| self.evict(id)).collect();
+ if !garbage.is_empty() {
+ std::thread::spawn(move || drop(garbage));
+ }
+ }
+
+ #[cfg(test)]
+ fn paint_cel_count_at(&self, frame: u32) -> usize {
+ paint_cels(&self.bundle.doc, frame).len()
+ }
+
+ pub fn cache_bytes(&self) -> usize {
+ self.rasters.values().map(Raster::bytes).sum::<usize>()
+ + self.cels.values().map(|d| d.replay.checkpoint_bytes()).sum::<usize>()
+ + self.below.bytes()
+ + self.above.bytes()
+ }
+
+ fn forget_stale(
+ &mut self,
+ wanted: &[(String, String)],
+ old: Option<&Document>,
+ touched: Option<&BTreeSet<String>>,
+ ) {
+ let doc = &self.bundle.doc;
+ let drawings = drawings(doc);
+ let current: BTreeSet<String> = vector_ids(doc, self.frame).into_iter().collect();
+ let shown: BTreeSet<&String> = wanted.iter().map(|(_, c)| c).collect();
+ let stale: Vec<String> = self
+ .rasters
+ .keys()
+ .filter(|c| !shown.contains(c))
+ .filter(|c| match drawings.get(*c) {
+ None => true,
+ Some((layer, Kind::Paint)) => {
+ let bytes = fs::read(self.bundle.strokes_path(layer, c)).unwrap_or_default();
+ self.cels.get(*c).is_none_or(|d| d.file_hash != fnv(FNV_OFFSET, &bytes))
+ }
+ Some(_) if current.contains(*c) => false,
+ Some(_) => {
+ touched.is_some_and(|t| t.contains(*c))
+ || old.is_some_and(|old| cel_nodes(old, c) != cel_nodes(doc, c))
+ }
+ })
+ .cloned()
+ .collect();
+ let garbage: Vec<_> = stale.iter().map(|c| self.evict(c)).collect();
+ if !garbage.is_empty() {
+ std::thread::spawn(move || drop(garbage));
+ }
+ }
+
+ fn sync_nodes(&mut self, cels: &BTreeSet<String>, brushes: &BrushSet) -> Result<Vec<usize>> {
+ let (w, h) = self.size();
+ let mut dirty: BTreeSet<usize> = BTreeSet::new();
+ let wanted = paint_cels(&self.bundle.doc, self.frame);
+ wanted
+ .iter()
+ .try_for_each(|(layer, cel)| self.sync_paint(layer, cel, brushes, &mut dirty))?;
+ let current = self.current();
+ let doc = &self.bundle.doc;
+ let changed: Vec<(String, u64)> = cels
+ .iter()
+ .filter(|cel| self.vector_hash.contains_key(*cel) && current.contains(*cel))
+ .map(|cel| (cel.clone(), nodes_hash(&nodes_of(doc, cel))))
+ .filter(|(cel, hash)| self.vector_hash.get(cel) != Some(hash))
+ .collect();
+ changed.into_iter().try_for_each(|(cel, hash)| {
+ let raster = match self.recall(&cel, hash) {
+ Some(raster) => raster,
+ None => rasterize_nodes(&nodes_of(&self.bundle.doc, &cel), w, h)?,
+ };
+ self.swap_vector(cel.clone(), raster, &mut dirty);
+ self.vector_hash.insert(cel, hash);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ self.forget_stale(&wanted, None, Some(cels));
+ self.load_missing(brushes)?;
+ dirty.extend(self.build_onions());
+ let dirty: Vec<usize> = dirty.into_iter().collect();
+ self.rebuild_caches(Some(&dirty))?;
+ Ok(dirty)
+ }
+
+ pub fn save_active(&mut self, summary: &str) -> Result<usize> {
+ let Some(cel) = self.active_cel() else {
+ return Ok(0);
+ };
+ let layer = self.active_id().unwrap_or_default();
+ record(
+ &self.bundle,
+ &std::mem::take(&mut self.unsaved),
+ "editor",
+ &format!("{summary} on {layer}"),
+ &[self.bundle.strokes_path(&layer, &cel)],
+ )?;
+ let Some(data) = self.cels.get_mut(&cel) else {
+ return Ok(0);
+ };
+ self.bundle.embed_brushes_of(data.marks())?;
+ let bytes = encode_cel(data.marks())?;
+ write_atomic(&self.bundle.strokes_path(&layer, &cel), &bytes)?;
+ data.file_hash = fnv(FNV_OFFSET, &bytes);
+ self.bundle.save()?;
+ self.bundle.stamp("editor")?;
+ Ok(bytes.len())
+ }
+
+ pub fn disk_rev(&self) -> Option<u64> {
+ let text = fs::read_to_string(self.bundle.root.join("doc.json")).ok()?;
+ serde_json::from_str::<serde_json::Value>(&text).ok()?["rev"].as_u64()
+ }
+
+ pub fn reload(&mut self, brushes: &BrushSet) -> Result<Vec<usize>> {
+ let old = self.bundle.doc.clone();
+ self.bundle.reload()?;
+ self.unsaved = Patch::default();
+ self.sync(&old, brushes)
+ }
+
+ pub fn apply(&mut self, ops: &[Op], brushes: &BrushSet) -> Result<Vec<usize>> {
+ self.apply_with(ops, brushes).map(|(dirty, _)| dirty)
+ }
+
+ pub fn apply_with(&mut self, ops: &[Op], brushes: &BrushSet) -> Result<(Vec<usize>, Applied)> {
+ let old = self.bundle.doc.clone();
+ let applied = self.bundle.apply_as(ops, "editor")?;
+ self.bundle.stamp("editor")?;
+ Ok((self.sync(&old, brushes)?, applied))
+ }
+
+ fn retire(&mut self, cel: &str, hash: u64, raster: Raster) {
+ self.memo.retain(|(c, h, _)| !(c == cel && *h == hash));
+ self.memo.push_front((cel.to_string(), hash, raster));
+ let mut total = 0usize;
+ let keep = self
+ .memo
+ .iter()
+ .take_while(|(_, _, r)| {
+ total += r.bytes();
+ total <= MEMO_BYTES
+ })
+ .count()
+ .max(1);
+ self.memo.truncate(keep);
+ }
+
+ fn recall(&mut self, cel: &str, hash: u64) -> Option<Raster> {
+ let at = self.memo.iter().position(|(c, h, _)| c == cel && *h == hash)?;
+ self.memo.remove(at).map(|(_, _, r)| r)
+ }
+
+ fn swap_vector(&mut self, cel: String, raster: Raster, dirty: &mut BTreeSet<usize>) {
+ dirty.extend(occupied(self.rasters.get(&cel)).chain(occupied(Some(&raster))));
+ let previous = self.vector_hash.get(&cel).copied();
+ if let (Some(hash), Some(old)) = (previous, self.rasters.insert(cel.clone(), raster)) {
+ self.retire(&cel, hash, old);
+ }
+ }
+
+ pub fn apply_rendered(
+ &mut self,
+ ops: &[Op],
+ rendered: (String, u64, Raster),
+ brushes: &BrushSet,
+ ) -> Result<Vec<usize>> {
+ let old = self.bundle.doc.clone();
+ self.bundle.apply_as(ops, "editor")?;
+ self.bundle.stamp("editor")?;
+ let (cel, hash, raster) = rendered;
+ let mut extra = BTreeSet::new();
+ self.swap_vector(cel.clone(), raster, &mut extra);
+ self.vector_hash.insert(cel, hash);
+ let dirty = self.sync(&old, brushes)?;
+ if dirty.len() == self.all_tiles().len() {
+ return Ok(dirty);
+ }
+ let missing: Vec<usize> = extra.iter().copied().filter(|i| !dirty.contains(i)).collect();
+ self.rebuild_caches(Some(&missing))?;
+ extra.extend(dirty);
+ Ok(extra.into_iter().collect())
+ }
+
+ pub fn node_slot(&self, node: &str) -> Option<(Vec<usize>, String, usize, Vec<Node>)> {
+ match self.bundle.doc.locate(node)? {
+ Loc::Node(path, c, nodes) if nodes.len() == 1 => {
+ let layer = self.bundle.doc.layer_at(&path);
+ if layer.kind() != Kind::Vector || layer.locked {
+ return None;
+ }
+ let cel = &layer.cels()[c];
+ Some((path, cel.id.clone(), nodes[0], cel.nodes.clone()))
+ }
+ _ => None,
+ }
+ }
+
+ fn compose_with(
+ &self,
+ items: &[TileItem],
+ index: usize,
+ background: Option<&str>,
+ onions: bool,
+ ) -> Result<Vec<f16>> {
+ let job = TileJob {
+ frame: self.frame,
+ rasters: &self.rasters,
+ background,
+ tx: index % self.cols(),
+ ty: index / self.cols(),
+ swap: None,
+ onions: self.onion_map().filter(|_| onions),
+ doc: &self.bundle.doc,
+ references: true,
+ };
+ compose_tile(items, &job)
+ }
+
+ pub fn lift_planes(&self, layer: &[usize], lower: &Raster, upper: &Raster) -> Result<Option<Planes>> {
+ if self.slimmed() {
+ return Ok(None);
+ }
+ let doc = &self.bundle.doc;
+ let Some((below, above, through)) = split(doc, &doc.layers, layer) else {
+ return Ok(None);
+ };
+ let owner = doc.layer_at(layer);
+ if !through || owner.blend != Blend::Normal || !doc.effects_of(owner).is_empty() {
+ return Ok(None);
+ }
+ let units = above.into_iter().fold(Vec::<Vec<&Layer>>::new(), |mut out, l| {
+ match out.last_mut() {
+ Some(unit) if l.clip => unit.push(l),
+ _ => out.push(vec![l]),
+ }
+ out
+ });
+ let mut runs: Vec<(Mix, Vec<Vec<&Layer>>)> = Vec::new();
+ for unit in units.into_iter().filter(|u| u[0].visible) {
+ let Some(mix) = Mix::of(unit[0].blend) else {
+ return Ok(None);
+ };
+ if !unit
+ .iter()
+ .all(|l| doc.effects_of(l).is_empty() && !l.reads_under() && l.children().iter().all(|c| pure(doc, c)))
+ {
+ return Ok(None);
+ }
+ match runs.last_mut() {
+ Some((last, group)) if *last == mix => group.push(unit),
+ _ => runs.push((mix, vec![unit])),
+ }
+ }
+ fn own<'a>(raster: &'a Raster, index: usize, owner: &Layer) -> Option<TileItem<'a>> {
+ raster.at(index).filter(|_| owner.visible).map(|tile| TileItem::Pixels {
+ tile,
+ opacity: owner.opacity,
+ blend: Blend::Normal,
+ })
+ }
+ let background = doc.canvas.background.as_deref();
+ let tiles = self.all_tiles();
+ let base = tiles
+ .par_iter()
+ .map(|&i| {
+ let ghost = self.onion_tile(&owner.id, i).map(|tile| TileItem::Pixels {
+ tile,
+ opacity: 1.0,
+ blend: Blend::Normal,
+ });
+ let items: Vec<TileItem> = below
+ .iter()
+ .filter(|l| l.visible)
+ .map(|l| TileItem::Layer(l))
+ .chain(ghost)
+ .chain(own(lower, i, owner))
+ .collect();
+ Ok((i, self.compose_with(&items, i, background, true)?))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let planes = runs
+ .iter()
+ .enumerate()
+ .map(|(k, (mix, units))| {
+ let tiles = tiles
+ .par_iter()
+ .map(|&i| {
+ let tile = match mix {
+ Mix::Multiply => {
+ let mut factor = vec![f16::ONE; TILE_PX * 4];
+ units.iter().try_for_each(|unit| {
+ let items: Vec<TileItem> = unit.iter().map(|l| TileItem::Layer(l)).collect();
+ let t = self.compose_with(&items, i, None, true)?;
+ factor
+ .as_chunks_mut::<4>()
+ .0
+ .iter_mut()
+ .zip(t.as_chunks::<4>().0)
+ .for_each(|(f, s)| {
+ let a = s[3].to_f32();
+ (0..3).for_each(|c| {
+ f[c] = f16::from_f32(f[c].to_f32() * (1.0 - a + s[c].to_f32()));
+ });
+ });
+ Ok::<_, anyhow::Error>(())
+ })?;
+ factor
+ }
+ _ => {
+ let first = (k == 0).then(|| own(upper, i, owner)).flatten();
+ let items: Vec<TileItem> = first
+ .into_iter()
+ .chain(units.iter().flatten().map(|l| TileItem::Layer(l)))
+ .collect();
+ self.compose_with(&items, i, None, true)?
+ }
+ };
+ Ok((i, tile))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok((*mix, tiles))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Some(Planes {
+ base,
+ runs: planes,
+ opacity: if owner.visible { owner.opacity } else { 0.0 },
+ }))
+ }
+
+ fn vector_cels_since(&self, old: &Document) -> Vec<(String, u64)> {
+ let before: BTreeMap<&str, &Vec<Node>> = old
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(self.frame))
+ .map(|c| (c.id.as_str(), &c.nodes))
+ .collect();
+ self.bundle
+ .doc
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(self.frame))
+ .map(|c| {
+ let known = self
+ .vector_hash
+ .get(&c.id)
+ .filter(|_| before.get(c.id.as_str()) == Some(&&c.nodes));
+ let hash = known.copied().unwrap_or_else(|| nodes_hash(&c.nodes));
+ (c.id.clone(), hash)
+ })
+ .collect()
+ }
+
+ fn sync_paint(&mut self, layer: &str, cel: &str, brushes: &BrushSet, dirty: &mut BTreeSet<usize>) -> Result<()> {
+ let (w, h) = self.size();
+ let bytes = fs::read(self.bundle.strokes_path(layer, cel)).unwrap_or_default();
+ let hash = fnv(FNV_OFFSET, &bytes);
+ if self.cels.get(cel).is_some_and(|d| d.file_hash == hash) {
+ return Ok(());
+ }
+ if self.lean
+ && !self.rasters.contains_key(cel)
+ && let Some(data) = self.cels.get_mut(cel)
+ {
+ data.file_hash = 0;
+ self.stale = true;
+ return Ok(());
+ }
+ let marks = if bytes.is_empty() {
+ Vec::new()
+ } else {
+ decode_cel(&bytes)?
+ };
+ match (self.cels.get_mut(cel), self.rasters.get_mut(cel)) {
+ (Some(data), Some(raster)) => {
+ dirty.extend(data.replay.update(raster, marks, brushes)?.tiles);
+ data.file_hash = hash;
+ }
+ _ => {
+ let (replay, fresh, _) = CelReplay::replay(w, h, marks, brushes)?;
+ dirty.extend(occupied(self.rasters.get(cel)).chain(occupied(Some(&fresh))));
+ self.rasters.insert(cel.to_string(), fresh);
+ self.cels.insert(
+ cel.to_string(),
+ CelData {
+ replay,
+ file_hash: hash,
+ },
+ );
+ }
+ }
+ Ok(())
+ }
+
+ fn sync(&mut self, old: &Document, brushes: &BrushSet) -> Result<Vec<usize>> {
+ let (w, h) = self.size();
+ let active_id = old.locate_path(&self.active).map(|l| l.id.clone());
+ if (self.below.width, self.below.height) != (w, h) {
+ let kept = (
+ self.tint_mask,
+ self.onion.clone(),
+ self.onion_on,
+ std::mem::take(&mut self.onion_marked),
+ );
+ *self = Self::open_at(&self.bundle.root.clone(), self.frame)?;
+ (self.tint_mask, self.onion, self.onion_on, self.onion_marked) = kept;
+ self.refresh(brushes)?;
+ return Ok(self.all_tiles());
+ }
+ let last = self.bundle.doc.timeline.frames - 1;
+ let moved = self.frame > last;
+ self.frame = self.frame.min(last);
+ let mut dirty: BTreeSet<usize> = BTreeSet::new();
+ let wanted = paint_cels(&self.bundle.doc, self.frame);
+ wanted
+ .iter()
+ .try_for_each(|(layer, cel)| self.sync_paint(layer, cel, brushes, &mut dirty))?;
+ let vectors = self.vector_cels_since(old);
+ let changed: Vec<(String, u64)> = vectors
+ .iter()
+ .filter(|(cel, hash)| self.vector_hash.get(cel) != Some(hash))
+ .cloned()
+ .collect();
+ let vectors_changed = !changed.is_empty();
+ let (recalled, missing): (Vec<_>, Vec<_>) = changed
+ .iter()
+ .map(|(cel, hash)| (cel.clone(), self.recall(cel, *hash)))
+ .partition(|(_, raster)| raster.is_some());
+ let doc = &self.bundle.doc;
+ let fresh = missing
+ .par_iter()
+ .map(|(cel, _)| rasterize_nodes(&nodes_of(doc, cel), w, h).map(|r| (cel.clone(), r)))
+ .collect::<Result<Vec<_>>>()?;
+ recalled
+ .into_iter()
+ .filter_map(|(cel, raster)| raster.map(|r| (cel, r)))
+ .chain(fresh)
+ .for_each(|(cel, raster)| self.swap_vector(cel, raster, &mut dirty));
+ vectors.into_iter().for_each(|(cel, hash)| {
+ self.vector_hash.insert(cel, hash);
+ });
+ self.forget_stale(&wanted, Some(old), None);
+ self.trim();
+ self.active = active_id
+ .and_then(|id| match self.bundle.doc.locate(&id) {
+ Some(Loc::Layer(path)) => Some(path),
+ _ => None,
+ })
+ .unwrap_or_else(|| self.default_active());
+ self.load_missing(brushes)?;
+ let ghosts = self.build_onions();
+ let others = vectors_changed || !ghosts.is_empty();
+ dirty.extend(ghosts);
+ if moved || structure(old, self.frame) != structure(&self.bundle.doc, self.frame) {
+ self.rebuild_caches(None)?;
+ return Ok(self.all_tiles());
+ }
+ if self.slimmed() {
+ if self.stale || others {
+ self.stale = true;
+ return Ok(self.all_tiles());
+ }
+ return Ok(dirty.into_iter().collect());
+ }
+ let dirty: Vec<usize> = dirty.into_iter().collect();
+ self.rebuild_caches(Some(&dirty))?;
+ Ok(dirty)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_brush::StrokePainter;
+ use klad_core::doc::{Cel, Loc, Shape};
+ use klad_core::fill::{FillSource, Seed};
+ use klad_core::stroke::marks;
+ use klad_core::synth::Synth;
+ use klad_render::{View, compose};
+
+ struct Row {
+ id: String,
+ depth: usize,
+ strokes: usize,
+ fills: usize,
+ mask: bool,
+ clip: bool,
+ }
+
+ fn fills(data: &CelData) -> usize {
+ data.marks().iter().filter(|m| m.as_fill().is_some()).count()
+ }
+
+ fn rows(scene: &Scene) -> Vec<Row> {
+ fn row(scene: &Scene, layer: &Layer, path: &[usize]) -> Row {
+ let data = layer.content_at(scene.frame).and_then(|c| scene.cels.get(&c.id));
+ Row {
+ depth: path.iter().filter(|i| **i != MASK).count() - 1 + usize::from(path.last() == Some(&MASK)),
+ id: layer.id.clone(),
+ strokes: data.map_or(0, |d| d.marks().len() - fills(d)),
+ fills: data.map_or(0, fills),
+ mask: path.last() == Some(&MASK),
+ clip: layer.clip,
+ }
+ }
+ fn walk(scene: &Scene, layers: &[Layer], path: &mut Vec<usize>, out: &mut Vec<Row>) {
+ layers.iter().enumerate().rev().for_each(|(i, layer)| {
+ path.push(i);
+ out.push(row(scene, layer, path));
+ if let Some(mask) = layer.mask.as_deref() {
+ path.push(MASK);
+ out.push(row(scene, mask, path));
+ path.pop();
+ }
+ walk(scene, layer.children(), path, out);
+ path.pop();
+ });
+ }
+ let mut out = Vec::new();
+ walk(scene, &scene.bundle.doc.layers, &mut Vec::new(), &mut out);
+ out
+ }
+
+ fn bundle(name: &str, top_blend: Blend) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-scene-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(600, 300);
+ doc.canvas.background = Some("#ffffff".into());
+ let rect = Node::new(
+ "n1",
+ Shape::Rect {
+ x: 50.0,
+ y: 50.0,
+ w: 400.0,
+ h: 150.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#3366aa");
+ let mut top = Layer::paint("b", "b", "cb");
+ top.blend = top_blend;
+ top.opacity = 0.6;
+ doc.layers = vec![
+ Layer::vector("v", "v", "cv", vec![rect]),
+ Layer::group("g", "g", vec![Layer::paint("a", "a", "ca")]),
+ top,
+ ];
+ let b = Bundle::create(&dir, doc).unwrap();
+ b.write_marks("a", "ca", &marks(Synth::canvas(600.0, 300.0).strokes(30, 1)))
+ .unwrap();
+ b.write_marks("b", "cb", &marks(Synth::canvas(600.0, 300.0).strokes(30, 2)))
+ .unwrap();
+ dir
+ }
+
+ fn tile_rgb(scene: &Scene, x: usize, y: usize) -> [u8; 3] {
+ let index = (y / 256) * scene.cols() + x / 256;
+ let composed = scene.compose(&[index], None).unwrap();
+ let tile = &composed.iter().find(|(i, _)| *i == index).unwrap().1;
+ let at = ((y % 256) * 256 + x % 256) * 4;
+ let a = tile[at + 3].to_f32();
+ [0, 1, 2].map(|c| (tile[at + c].to_f32() / a * 255.0).round() as u8)
+ }
+
+ fn agrees(scene: &Scene) {
+ let paint: Rasters = scene
+ .rasters
+ .iter()
+ .filter(|(k, _)| scene.cels.contains_key(*k))
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ let full = compose(&scene.bundle.doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
+ [(60, 60), (300, 120), (520, 250), (10, 290)]
+ .iter()
+ .for_each(|&(x, y)| {
+ let reference = full.pixel(x as u32, y as u32);
+ let tiled = tile_rgb(scene, x, y);
+ assert!(
+ tiled.iter().zip(&reference[..3]).all(|(a, b)| a.abs_diff(*b) <= 2),
+ "({x},{y}) tiled {tiled:?} full {reference:?}"
+ );
+ });
+ }
+
+ fn looks(name: &str) -> Scene {
+ let brushes = BrushSet::presets();
+ let mut scene = Scene::open(&bundle(name, Blend::Normal)).unwrap();
+ let ops = klad_core::ops::parse_lines(
+ r##"{"op":"set","id":"v","effects":[{"glow":{"radius":10,"color":"#ffcc66"}},{"outline":{"width":3,"color":"#202020"}}]}"##,
+ )
+ .unwrap()
+ .into_iter()
+ .chain([Op::AddLayer {
+ layer: serde_json::json!({"kind": "adjust", "id": "k", "name": "dusk", "adjust": {"curves": {"points": [[0, 0], [0.5, 0.3], [1, 0.9]]}}}),
+ place: klad_core::ops::Place::default(),
+ }])
+ .collect::<Vec<_>>();
+ scene.apply(&ops, &brushes).unwrap();
+ scene
+ }
+
+ #[test]
+ fn effects_and_adjustments_compose_like_the_cli_on_every_path() {
+ let brushes = BrushSet::presets();
+ let mut scene = looks("looks");
+ scene.set_active(vec![1, 0]).unwrap();
+ assert!(scene.fast, "an adjustment above is composed live over the cached below");
+ agrees(&scene);
+ let edge = tile_rgb(&scene, 48, 125);
+ assert!(
+ edge[0] < 80 && edge[1] < 80,
+ "the outline shows past the rect: {edge:?}"
+ );
+ scene.set_active(vec![0]).unwrap();
+ assert!(!scene.fast);
+ agrees(&scene);
+ let glow = klad_core::ops::parse_lines(
+ r##"{"op":"set","id":"a","effects":[{"glow":{"radius":16,"blend":"normal","color":"#ff0000","strength":2}}]}"##,
+ )
+ .unwrap();
+ scene.apply(&glow, &brushes).unwrap();
+ scene.set_active(vec![1, 0]).unwrap();
+ assert!(!scene.fast, "a layer with effects is painted on the full path");
+ let brush = brushes.get("ink").unwrap();
+ let stroke = Stroke::new(scene.next_mark_id(), "ink", [0.1, 0.2, 0.9, 1.0], 16.0, 7)
+ .with_points(&[(190.0, 240.0, 1.0), (236.0, 240.0, 1.0)], 4.0);
+ let mut buffer = StrokeBuffer::new(600, 300);
+ let mut painter = StrokePainter::live(brush, &stroke);
+ stroke.samples.iter().for_each(|s| painter.push(s, &mut buffer));
+ let dirty = buffer.take_dirty();
+ assert_eq!(dirty, vec![0], "the stroke stays in the first tile");
+ let pixel = |tiles: &[(usize, Vec<f16>)], x: usize, y: usize| {
+ let index = (y / 256) * 3 + x / 256;
+ let tile = &tiles.iter().find(|(i, _)| *i == index).unwrap().1;
+ let at = ((y % 256) * 256 + x % 256) * 4;
+ [tile[at].to_f32(), tile[at + 1].to_f32(), tile[at + 2].to_f32()]
+ };
+ let before = scene.compose(&[1], None).unwrap();
+ let live = {
+ let preview = Preview {
+ twin: None,
+ buffer: &buffer,
+ color: stroke.color(),
+ opacity: 1.0,
+ blend: StrokeBlend::Normal,
+ };
+ scene.compose(&dirty, Some(&preview)).unwrap()
+ };
+ assert!(
+ live.iter().any(|(i, _)| *i == 1),
+ "the glow's reach brings in the next tile"
+ );
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ let after = scene.compose(&[1], None).unwrap();
+ let (b, l, a) = (
+ pixel(&before, 262, 240),
+ pixel(&live, 262, 240),
+ pixel(&after, 262, 240),
+ );
+ assert!(
+ a[1] < b[1] - 0.05,
+ "the committed glow spills over the tile edge: {b:?} {a:?}"
+ );
+ assert!(
+ l.iter().zip(&a).all(|(x, y)| (x - y).abs() < 0.01),
+ "live {l:?} committed {a:?}"
+ );
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app look_dab_timing -- --ignored --nocapture"]
+ fn look_dab_timing() {
+ use std::time::Instant;
+ let brushes = BrushSet::presets();
+ let dir = stress("look-dab-timing");
+ let mut scene = Scene::open(&dir).unwrap();
+ let layers = scene.bundle.doc.layers.len();
+ scene.set_active(vec![1]).unwrap();
+ let ops = vec![
+ Op::AddLayer {
+ layer: serde_json::json!({"kind": "adjust", "name": "dusk", "adjust": {"curves": {"points": [[0, 0], [0.5, 0.3], [1, 0.9]]}}}),
+ place: klad_core::ops::Place::default(),
+ },
+ Op::Set {
+ id: "l2".into(),
+ props: serde_json::from_str(r#"{"effects":[{"glow":{"radius":24}}]}"#).unwrap(),
+ },
+ ];
+ let pick: Vec<Op> = match std::env::var("LOOK").as_deref() {
+ Ok("curves") => ops[..1].to_vec(),
+ Ok("glow") => ops[1..].to_vec(),
+ _ => ops,
+ };
+ scene.apply(&pick, &brushes).unwrap();
+ let points: Vec<(f32, f32, f32)> = (0..240)
+ .map(|i| {
+ let t = i as f32 / 239.0;
+ (200.0 + 1600.0 * t, 1024.0 + 500.0 * (t * 9.0).sin(), 0.4 + 0.6 * t)
+ })
+ .collect();
+ let brush = brushes.get("ink").unwrap();
+ let stroke = Stroke::new(999, "ink", [0.1, 0.1, 0.1, 1.0], 24.0, 3).with_points(&points, 4.0);
+ let mut buffer = StrokeBuffer::new(2048, 2048);
+ let mut live = StrokePainter::live(brush, &stroke);
+ let times: Vec<f64> = stroke
+ .samples
+ .iter()
+ .map(|sample| {
+ let begin = Instant::now();
+ live.push(sample, &mut buffer);
+ let tiles = buffer.take_dirty();
+ let preview = Preview {
+ twin: None,
+ buffer: &buffer,
+ color: stroke.color(),
+ opacity: 1.0,
+ blend: StrokeBlend::Normal,
+ };
+ scene.compose_painting(&tiles, &[], Some(&preview)).unwrap();
+ begin.elapsed().as_secs_f64() * 1000.0
+ })
+ .collect();
+ println!(
+ "{layers} layers, a curves layer on top and a glow above the active layer: dab to composed tiles median {:.2} ms, p90 {:.2} ms, max {:.2} ms (fast path {})",
+ percentile(&times, 0.5),
+ percentile(&times, 0.9),
+ percentile(&times, 1.0),
+ scene.fast
+ );
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn tiles_agree_with_full_render_on_every_path() {
+ let mut fast = Scene::open(&bundle("fast", Blend::Normal)).unwrap();
+ assert!(fast.fast);
+ assert_eq!(fast.active, vec![2]);
+ agrees(&fast);
+ fast.set_active(vec![1, 0]).unwrap();
+ assert!(fast.fast);
+ agrees(&fast);
+ let mut slow = Scene::open(&bundle("slow", Blend::Multiply)).unwrap();
+ slow.set_active(vec![1, 0]).unwrap();
+ assert!(
+ slow.fast,
+ "a multiplied layer above is composed live over the cached below"
+ );
+ agrees(&slow);
+ let translucent = klad_core::ops::parse_lines(r#"{"op":"set","id":"g","opacity":0.8}"#).unwrap();
+ slow.apply(&translucent, &BrushSet::presets()).unwrap();
+ assert!(!slow.fast);
+ agrees(&slow);
+ assert_eq!(
+ rows(&slow).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
+ ["b", "g", "a", "v"]
+ );
+ }
+
+ fn animated(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-frames-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(600, 300);
+ doc.canvas.background = Some("#ffffff".into());
+ doc.timeline.frames = 6;
+ let rect = |x: f32| {
+ Node::new(
+ &format!("n{x}"),
+ Shape::Rect {
+ x,
+ y: 40.0,
+ w: 200.0,
+ h: 120.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#3366aa")
+ };
+ let mut vector = Layer::vector("v", "v", "v0", vec![rect(20.0)]);
+ let mut later = Cel::at("v2", 2);
+ later.nodes = vec![rect(300.0)];
+ vector.cels_mut().unwrap().push(later);
+ let mut lines = Layer::paint("a", "a", "a0");
+ lines.cels_mut().unwrap()[0].hold = Some(2);
+ lines.cels_mut().unwrap().extend([
+ Cel {
+ hold: Some(1),
+ ..Cel::at("a2", 2)
+ },
+ Cel {
+ link: Some("a0".into()),
+ ..Cel::at("a4", 4)
+ },
+ ]);
+ let mut top = Layer::paint("b", "b", "b0");
+ top.blend = Blend::Multiply;
+ doc.layers = vec![vector, lines, top];
+ doc.next_id = 100;
+ let b = Bundle::create(&dir, doc).unwrap();
+ let synth = Synth::canvas(600.0, 300.0);
+ b.write_marks("a", "a0", &marks(synth.strokes(20, 1))).unwrap();
+ b.write_marks("a", "a2", &marks(synth.strokes(20, 3))).unwrap();
+ b.write_marks("b", "b0", &marks(synth.strokes(10, 5))).unwrap();
+ dir
+ }
+
+ fn line_stroke(id: u32, from: (f32, f32), to: (f32, f32), brushes: &BrushSet) -> (Stroke, StrokeBuffer) {
+ let stroke = Stroke::new(id, "ink", [0.8, 0.1, 0.1, 1.0], 16.0, 7)
+ .with_points(&[(from.0, from.1, 1.0), (to.0, to.1, 1.0)], 5.0);
+ let mut buffer = StrokeBuffer::new(600, 300);
+ let mut live = StrokePainter::new(brushes.get("ink").unwrap(), &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ (stroke, buffer)
+ }
+
+ #[test]
+ fn frames_show_their_cels_and_paint_where_they_should() {
+ let brushes = BrushSet::presets();
+ let dir = animated("show");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![1]).unwrap();
+ agrees(&scene);
+ (0..6).for_each(|f| {
+ scene.set_frame(f, &brushes).unwrap();
+ assert_eq!(scene.frame, f);
+ agrees(&scene);
+ });
+ assert!(scene.has_frame(0) && scene.has_frame(2));
+ scene.set_frame(4, &brushes).unwrap();
+ assert_eq!(scene.active_cel().as_deref(), Some("a0"));
+ let before = scene.rasters["a0"].hash();
+ let (stroke, mut buffer) = line_stroke(50, (20.0, 280.0), (580.0, 20.0), &brushes);
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ assert_ne!(scene.rasters["a0"].hash(), before);
+ assert_eq!(scene.bundle.read_marks("a", "a0").unwrap().len(), 21);
+ scene.set_frame(0, &brushes).unwrap();
+ agrees(&scene);
+ scene.set_frame(3, &brushes).unwrap();
+ assert_eq!(scene.active_cel(), None);
+ let (stroke, mut buffer) = line_stroke(1, (20.0, 20.0), (580.0, 280.0), &brushes);
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ let layer = scene.bundle.doc.layer("a").unwrap();
+ let fresh = layer.cel_at(3).unwrap();
+ assert_eq!((fresh.frame, fresh.link.as_deref()), (3, None));
+ assert_eq!(layer.content_at(4).unwrap().id, "a0");
+ agrees(&scene);
+ let reopened = Scene::open_at(&dir, 3).unwrap();
+ assert_eq!(reopened.rasters[&fresh.id].hash(), scene.rasters[&fresh.id].hash());
+ }
+
+ #[test]
+ fn a_blink_made_from_the_timeline_paints_on_every_new_drawing() {
+ let brushes = BrushSet::presets();
+ let dir = animated("blink");
+ let mut scene = Scene::open(&dir).unwrap();
+ let add =
+ klad_core::ops::parse_lines(r#"{"op":"add","layer":{"kind":"paint","cels":[{"frame":0}]},"above":"b"}"#)
+ .unwrap();
+ let (_, applied) = scene.apply_with(&add, &brushes).unwrap();
+ let layer = applied.added[0].clone();
+ let Some(Loc::Layer(path)) = scene.bundle.doc.locate(&layer) else {
+ panic!()
+ };
+ scene.set_active(path).unwrap();
+ let paint = |scene: &mut Scene, y: f32| {
+ let (stroke, mut buffer) = line_stroke(scene.next_mark_id(), (40.0, y), (560.0, y), &brushes);
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ };
+ paint(&mut scene, 60.0);
+ let first = scene.active_cel().unwrap();
+ let hold = klad_core::ops::parse_lines(&format!(r#"{{"op":"set","id":"{first}","hold":4}}"#)).unwrap();
+ scene.apply_with(&hold, &brushes).unwrap();
+ [(4u32, 120.0f32), (5, 180.0)].iter().for_each(|&(frame, y)| {
+ scene.set_frame(frame, &brushes).unwrap();
+ if frame == 4 {
+ assert_eq!(scene.active_cel(), None, "frame 4 is blank on the new layer");
+ }
+ let new =
+ klad_core::ops::parse_lines(&format!(r#"{{"op":"cel","new":"{layer}","frame":{frame}}}"#)).unwrap();
+ let (_, applied) = scene.apply_with(&new, &brushes).unwrap();
+ let cel = applied.added[0].clone();
+ assert_eq!(scene.active_cel().as_deref(), Some(cel.as_str()));
+ paint(&mut scene, y);
+ assert_eq!(scene.bundle.read_marks(&layer, &cel).unwrap().len(), 1);
+ assert!(scene.rasters[&cel].occupied().count() > 0);
+ agrees(&scene);
+ });
+ let reopened = Scene::open_at(&dir, 5).unwrap();
+ assert_eq!(reopened.cels.len(), scene.paint_cel_count_at(5));
+ }
+
+ #[test]
+ fn a_frame_picture_seen_once_comes_back_from_disk_and_the_canvas_job_keeps_one_too() {
+ let brushes = BrushSet::presets();
+ let dir = animated("pictures");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.keep_after = std::time::Duration::ZERO;
+ let rendered = scene.frame_request(2, false, 0, &brushes).run().unwrap();
+ assert!(!rendered.paint.is_empty());
+ assert!(picture_path(&scene.pictures(), rendered.image.key).exists());
+ let mut fresh = Scene::open(&dir).unwrap();
+ let again = fresh.frame_request(2, false, 0, &brushes).run().unwrap();
+ assert!(again.paint.is_empty(), "read from disk, nothing loaded");
+ assert_eq!(again.image.key, rendered.image.key);
+ assert_eq!(again.image.mips, rendered.image.mips);
+ let ops = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","opacity":0.5}"#).unwrap();
+ fresh.apply(&ops, &brushes).unwrap();
+ let changed = fresh.frame_request(2, false, 0, &brushes).run().unwrap();
+ assert_ne!(changed.image.key, rendered.image.key);
+ let key = fresh.frame_key(0, false, 1, brushes.fingerprint());
+ let path = picture_path(&fresh.pictures(), key);
+ assert!(!path.exists());
+ fresh.move_to(0);
+ let done = fresh
+ .canvas_request(&brushes)
+ .with_picture(key, 1, fresh.pictures(), Default::default())
+ .run()
+ .unwrap();
+ assert!(fresh.adopt(done, true));
+ let start = std::time::Instant::now();
+ while !path.exists() && start.elapsed() < std::time::Duration::from_secs(10) {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ let kept = read_picture(&fresh.pictures(), key).expect("the canvas job wrote the frame's picture");
+ let made = fresh.frame_request(0, false, 1, &brushes);
+ assert_eq!(made.key, key);
+ let reference = picture(
+ &made.bundle.doc,
+ 0,
+ key,
+ 1,
+ &{
+ let mut all = made.rasters.clone();
+ made.paint.iter().for_each(|(l, c)| {
+ all.insert(c.clone(), load_paint(&made.bundle, l, c, &brushes).unwrap().1);
+ });
+ made.vector.iter().for_each(|(c, _, nodes)| {
+ all.insert(c.clone(), rasterize_nodes(nodes, 600, 300).unwrap());
+ });
+ all
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(kept.mips[0], reference.mips[0]);
+ }
+
+ fn layered(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-lean-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(600, 400);
+ doc.canvas.background = Some("#f4efe6".into());
+ ["p0", "p1", "p2", "p3"].iter().enumerate().for_each(|(i, id)| {
+ doc.layers.push(Layer::paint(id, id, &format!("c{i}")));
+ });
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let lines: Vec<String> = (0..4)
+ .flat_map(|i| {
+ (0..6).map(move |k| {
+ format!(
+ r#"{{"op":"stroke","layer":"p{i}","path":"M{} {} L{} {}","size":{},"color":"{}"}}"#,
+ 20 + k * 90 + i * 7,
+ 30 + i * 80,
+ 80 + k * 90,
+ 120 + i * 70,
+ 6 + i * 3,
+ ["#aa3322", "#2255aa", "#22aa55", "#555555"][i]
+ )
+ })
+ })
+ .collect();
+ bundle
+ .apply(&klad_core::ops::parse_lines(&lines.join("\n")).unwrap())
+ .unwrap();
+ dir
+ }
+
+ fn shown(scene: &Scene) -> Vec<u64> {
+ scene
+ .compose(&scene.all_tiles(), None)
+ .unwrap()
+ .into_iter()
+ .map(|(i, t)| fnv(i as u64, bytemuck::cast_slice(&t)))
+ .collect()
+ }
+
+ fn catch_up(scene: &mut Scene, brushes: &BrushSet) {
+ let done = scene.canvas_request(brushes).run().unwrap();
+ assert!(scene.adopt(done, true));
+ }
+
+ #[test]
+ fn planes_on_disk_bring_a_lean_frame_back_with_only_the_active_pixels() {
+ let brushes = BrushSet::presets();
+ let dir = layered("planes");
+ let full = Scene::open(&dir).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let cache = CelCache::new(&bundle, &brushes, Write::Always);
+ paint_cels(&bundle.doc, 0).iter().for_each(|(layer, cel)| {
+ cache.load(&bundle, &brushes, layer, cel, true).unwrap();
+ });
+ let mut first = Scene::open_lazy(&dir).unwrap();
+ first.lean = true;
+ let ask = first.planes_ask(0).unwrap();
+ let key = ask.key(&first.bundle, &brushes);
+ let made = first.canvas_request(&brushes).run().unwrap();
+ assert_eq!(made.paint.len(), 4, "the first visit loads every drawing");
+ let start = std::time::Instant::now();
+ while !planes::path(&ask.dir, key).exists() && start.elapsed() < std::time::Duration::from_secs(20) {
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ let stored = planes::read(&ask.dir, key).unwrap();
+ let (below, above) = made.caches.clone().unwrap();
+ let same = |a: &Raster, b: &Raster| (0..a.cols * a.rows).all(|i| a.at(i) == b.at(i));
+ assert!(
+ same(&below, &stored.below) && same(&above, &stored.above),
+ "planes read back as built"
+ );
+ assert_eq!(stored.thumbs.len(), made.thumbs.len());
+ let mut again = Scene::open_lazy(&dir).unwrap();
+ again.lean = true;
+ let back = again.canvas_request(&brushes).run().unwrap();
+ assert_eq!(back.paint.len(), 1, "a revisit loads only the active drawing's pixels");
+ assert_eq!(back.strokes.len(), 3, "and the others' strokes");
+ assert!(again.adopt(back, true));
+ assert!(again.fast && !again.stale);
+ assert_eq!(again.cels.len(), 4);
+ assert_eq!(shown(&again), shown(&full));
+ let ops = klad_core::ops::parse_lines(r##"{"op":"set","id":"c0:s1","color":"#ffcc00"}"##).unwrap();
+ let mut edited = Scene::open(&dir).unwrap();
+ edited.apply(&ops, &brushes).unwrap();
+ assert_ne!(
+ again.planes_ask(0).unwrap().key(&again.bundle, &brushes),
+ key,
+ "an edit changes the key"
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_lean_scene_keeps_only_the_active_pixels_and_shows_and_edits_the_same() {
+ let brushes = BrushSet::presets();
+ let dir = layered("lean");
+ let mut full = Scene::open(&dir).unwrap();
+ let mut lean = Scene::open_lazy(&dir).unwrap();
+ lean.lean = true;
+ catch_up(&mut lean, &brushes);
+ assert!(lean.fast && !lean.stale);
+ assert_eq!(lean.rasters.len(), 1, "only the active drawing keeps its pixels");
+ assert_eq!(lean.cels.len(), 4, "every drawing keeps its strokes");
+ assert_eq!(shown(&lean), shown(&full));
+ let ops = |line: &str| klad_core::ops::parse_lines(line).unwrap();
+ let recolour = ops(r##"{"op":"set","id":"c3:s1","color":"#ffcc00"}"##);
+ full.apply(&recolour, &brushes).unwrap();
+ lean.apply(&recolour, &brushes).unwrap();
+ assert!(!lean.stale, "an edit on the active drawing needs nothing reloaded");
+ assert_eq!(shown(&lean), shown(&full));
+ let at = (100.0, 70.0);
+ assert_eq!(lean.sample(at, false).unwrap(), full.sample(at, false).unwrap());
+ let all = klad_core::fill::FillRef::All;
+ assert_eq!(
+ lean.fill_reference(&all, &brushes).unwrap().hash(),
+ full.fill_reference(&all, &brushes).unwrap().hash()
+ );
+ full.set_active(vec![1]).unwrap();
+ lean.set_active_later(vec![1]);
+ assert!(lean.stale);
+ catch_up(&mut lean, &brushes);
+ assert_eq!(lean.rasters.len(), 1);
+ assert_eq!(shown(&lean), shown(&full));
+ let mut outside = Bundle::open(&dir).unwrap();
+ outside
+ .apply(&ops(
+ r#"{"op":"stroke","layer":"p3","path":"M10 380 L590 20","size":20}"#,
+ ))
+ .unwrap();
+ full.reload(&brushes).unwrap();
+ lean.reload(&brushes).unwrap();
+ assert!(
+ lean.stale,
+ "a dropped drawing that changed outside is reloaded by the canvas job"
+ );
+ catch_up(&mut lean, &brushes);
+ assert_eq!(shown(&lean), shown(&full));
+ assert_eq!(lean.cels["c3"].marks().len(), full.cels["c3"].marks().len());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn preparing_a_frame_writes_its_picture_and_drawings_once() {
+ let brushes = BrushSet::presets();
+ let dir = animated("prepare");
+ let mut scene = Scene::open_lazy(&dir).unwrap();
+ let request = scene.prepare_request(2, false, 0, &brushes);
+ let key = request.key;
+ assert!(request.rasters.is_empty() && !request.paint.is_empty());
+ assert!(matches!(request.prepare().unwrap(), Prepared::Frame(n) if n > 0));
+ assert!(picture_path(&scene.pictures(), key).exists());
+ let cache = CelCache::new(&scene.bundle, &brushes, Write::Never);
+ assert!(
+ paint_cels(&scene.bundle.doc, 2)
+ .iter()
+ .all(|(l, c)| cache.holds(&scene.bundle, l, c))
+ );
+ assert_eq!(
+ scene.prepare_request(2, false, 0, &brushes).prepare().unwrap(),
+ Prepared::Already
+ );
+ fs::remove_file(picture_path(&scene.pictures(), key)).unwrap();
+ assert!(matches!(
+ scene.prepare_request(2, false, 0, &brushes).prepare().unwrap(),
+ Prepared::Frame(0)
+ ));
+ let shown = scene.frame_request(2, false, 0, &brushes).run().unwrap();
+ assert!(shown.paint.is_empty(), "the prepared picture comes from disk");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn other_frames_reload_after_outside_edits_and_loads_go_stale() {
+ let brushes = BrushSet::presets();
+ let dir = animated("outside");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_frame(2, &brushes).unwrap();
+ scene.set_frame(0, &brushes).unwrap();
+ assert!(scene.cels.contains_key("a2"));
+ let mut outside = Bundle::open(&dir).unwrap();
+ let ops =
+ klad_core::ops::parse_lines(r#"{"op":"stroke","layer":"a","frame":2,"path":"M10 10 L200 100","size":12}"#)
+ .unwrap();
+ outside.apply(&ops).unwrap();
+ scene.reload(&brushes).unwrap();
+ assert!(!scene.cels.contains_key("a2"));
+ assert!(scene.frame_job(2, &brushes).is_some());
+ scene.set_frame(2, &brushes).unwrap();
+ assert_eq!(scene.cels["a2"].marks().len(), 21);
+ agrees(&scene);
+ let job = scene.frame_job(5, &brushes);
+ assert!(job.is_none(), "frame 5 shows a0 and v2, both loaded");
+ scene.set_frame(0, &brushes).unwrap();
+ let mut outside = Bundle::open(&dir).unwrap();
+ let ops = klad_core::ops::parse_lines(r##"{"op":"set","id":"n300","fill":"#aa3333"}"##).unwrap();
+ outside.apply(&ops).unwrap();
+ scene.reload(&brushes).unwrap();
+ assert!(!scene.rasters.contains_key("v2") && scene.rasters.contains_key("v0"));
+ scene.set_frame(2, &brushes).unwrap();
+ agrees(&scene);
+ scene.budget = 0;
+ scene.set_frame(0, &brushes).unwrap();
+ assert!(!scene.cels.contains_key("a2") && !scene.rasters.contains_key("v2"));
+ let done = scene.frame_request(2, false, 0, &brushes).run().unwrap();
+ let ops = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","opacity":0.5}"#).unwrap();
+ scene.apply(&ops, &brushes).unwrap();
+ scene.absorb(done);
+ assert!(!scene.has_frame(2), "drawings loaded before an edit are dropped");
+ scene.budget = CACHE_BYTES;
+ let done = scene.frame_request(2, false, 0, &brushes).run().unwrap();
+ scene.absorb(done);
+ assert!(scene.has_frame(2));
+ scene.set_frame(2, &brushes).unwrap();
+ agrees(&scene);
+ }
+
+ #[test]
+ fn stroke_undo_save_and_incremental_reload() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("edit", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ let before = scene.rasters["cb"].hash();
+ let stroke = Stroke::new(99, "ink", [0.0, 0.0, 0.0, 1.0], 20.0, 3)
+ .with_points(&[(10.0, 10.0, 1.0), (590.0, 290.0, 1.0)], 5.0);
+ let mut buffer = StrokeBuffer::new(600, 300);
+ let mut live = StrokePainter::new(brushes.get("ink").unwrap(), &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ assert!(
+ !scene
+ .commit_stroke(stroke, &mut buffer, StrokeBlend::Normal)
+ .unwrap()
+ .is_empty()
+ );
+ scene.save_active("stroke").unwrap();
+ let other = Scene::open(&dir).unwrap();
+ assert_eq!(other.rasters["cb"].hash(), scene.rasters["cb"].hash());
+ assert!(scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().is_some());
+ assert_eq!(scene.rasters["cb"].hash(), before);
+ let rev = scene.bundle.doc.rev;
+ let mut outside = Bundle::open(&dir).unwrap();
+ let ops =
+ klad_core::ops::parse_lines(r#"{"op":"stroke","layer":"a","path":"M10 10 L200 100","size":12}"#).unwrap();
+ outside.apply(&ops).unwrap();
+ assert_eq!(scene.disk_rev(), Some(rev + 1));
+ let dirty = scene.reload(&brushes).unwrap();
+ assert!(!dirty.is_empty() && dirty.len() < scene.all_tiles().len(), "{dirty:?}");
+ assert_eq!(scene.cels["ca"].marks().len(), 31);
+ let replayed = klad_brush::replay(600, 300, scene.cels["ca"].marks(), &brushes)
+ .unwrap()
+ .raster;
+ assert_eq!(replayed.hash(), scene.rasters["ca"].hash());
+ agrees(&scene);
+ }
+
+ #[test]
+ fn editor_ops_refresh_vector_tiles() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("ops", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ let ops = klad_core::ops::parse_lines(r##"{"op":"set","id":"n1","fill":"#ff0000","transform.x":40}"##).unwrap();
+ let dirty = scene.apply(&ops, &brushes).unwrap();
+ assert!(!dirty.is_empty());
+ agrees(&scene);
+ let log = klad_core::history::entries(&scene.bundle, klad_core::history::Stack::Undo).unwrap();
+ assert_eq!(log[0].author, "editor");
+ let hide = klad_core::ops::parse_lines(r#"{"op":"set","id":"v","visible":false}"#).unwrap();
+ assert_eq!(scene.apply(&hide, &brushes).unwrap().len(), scene.all_tiles().len());
+ agrees(&scene);
+ }
+
+ #[test]
+ #[ignore = "timing run: DRAW_BUNDLE=<bundle> cargo test --release -p klad-app timing -- --ignored --nocapture"]
+ fn timing() {
+ let path = std::env::var("DRAW_BUNDLE").expect("DRAW_BUNDLE");
+ let brushes = BrushSet::presets();
+ let start = std::time::Instant::now();
+ let mut scene = Scene::open(Path::new(&path)).unwrap();
+ println!(
+ "open, rasterize vectors, build caches: {:.0} ms",
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ let start = std::time::Instant::now();
+ let tiles = scene.compose(&scene.all_tiles(), None).unwrap();
+ println!(
+ "compose all {} tiles: {:.0} ms",
+ tiles.len(),
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ let target = scene.default_active();
+ let layer = scene.bundle.doc.layer_at(&target).id.clone();
+ let mut outside = Bundle::open(Path::new(&path)).unwrap();
+ let line =
+ format!(r#"{{"op":"stroke","layer":"{layer}","path":"M300 300 C 900 100 1400 900 2000 600","size":60}}"#);
+ outside.apply(&klad_core::ops::parse_lines(&line).unwrap()).unwrap();
+ let start = std::time::Instant::now();
+ let dirty = scene.reload(&brushes).unwrap();
+ let reload = start.elapsed().as_secs_f64() * 1000.0;
+ let start = std::time::Instant::now();
+ scene.compose(&dirty, None).unwrap();
+ println!(
+ "external stroke: reload {reload:.0} ms, {} tiles recomposed in {:.0} ms",
+ dirty.len(),
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ klad_core::history::step(&mut outside, klad_core::history::Stack::Undo).unwrap();
+ let scene = Scene::open(Path::new(&path)).unwrap();
+ for node in std::env::var("DRAW_NODES")
+ .unwrap_or_default()
+ .split(',')
+ .filter(|n| !n.is_empty())
+ {
+ let Some((layer, _, index, nodes)) = scene.node_slot(node) else {
+ continue;
+ };
+ let (w, h) = scene.size();
+ let start = std::time::Instant::now();
+ klad_render::rasterize_region(
+ &nodes[index..=index],
+ klad_render::vector::node_box(&nodes[index]).unwrap().unwrap(),
+ 4096,
+ 0.5,
+ )
+ .unwrap();
+ println!(
+ "lift {node}: lifted at half scale {:.0} ms",
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ let t = std::time::Instant::now();
+ let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
+ let lower_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let t = std::time::Instant::now();
+ let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
+ println!(
+ "lift {node}: index {index} of {}, lower {lower_ms:.0} ms, upper {:.0} ms",
+ nodes.len(),
+ t.elapsed().as_secs_f64() * 1000.0
+ );
+ let start = std::time::Instant::now();
+ let [x, y, bw, bh] = klad_render::vector::node_box(&nodes[index]).unwrap().unwrap();
+ let lifted = klad_render::rasterize_region(&nodes[index..=index], [x, y, bw, bh], 4096, 1.0).unwrap();
+ let prepare = start.elapsed().as_secs_f64() * 1000.0;
+ let start = std::time::Instant::now();
+ let planes = scene.lift_planes(&layer, &lower, &upper).unwrap();
+ let compose = start.elapsed().as_secs_f64() * 1000.0;
+ if let Some(planes) = &planes {
+ let worst = [(300usize, 900usize), (1000, 1100), (1700, 800), (600, 1250), (100, 300)]
+ .iter()
+ .map(|&(x, y)| {
+ let px = rebuilt(&scene, planes, &lifted, x, y);
+ let i = (y / 256) * scene.cols() + x / 256;
+ let reference = &scene.compose(&[i], None).unwrap()[0].1;
+ let o = ((y % 256) * 256 + x % 256) * 4;
+ (0..3)
+ .map(|c| (px[c] - reference[o + c].to_f32()).abs())
+ .fold(0.0f32, f32::max)
+ })
+ .fold(0.0f32, f32::max);
+ println!(
+ "lift {node}: {} planes {:?}, worst channel error {worst:.4}",
+ planes.runs.len(),
+ planes.runs.iter().map(|(m, _)| *m).collect::<Vec<_>>()
+ );
+ }
+ let mut moved = nodes.clone();
+ moved[index].transform.x += 25.0;
+ let raster = rasterize_nodes(&moved, w, h).unwrap();
+ let hash = fnv(FNV_OFFSET, &serde_json::to_vec(&moved).unwrap());
+ let cel = scene.node_slot(node).unwrap().1;
+ let mut editing = Scene::open(Path::new(&path)).unwrap();
+ let op = klad_core::ops::parse_lines(&format!(
+ r#"{{"op":"set","id":"{node}","transform.x":{}}}"#,
+ moved[index].transform.x
+ ))
+ .unwrap();
+ let start = std::time::Instant::now();
+ let dirty = editing.apply_rendered(&op, (cel, hash, raster), &brushes).unwrap();
+ println!(
+ "commit {node}: apply_rendered {:.0} ms, {} tiles",
+ start.elapsed().as_secs_f64() * 1000.0,
+ dirty.len()
+ );
+ let start = std::time::Instant::now();
+ let mut probe = Bundle::open(Path::new(&path)).unwrap();
+ let opened = start.elapsed().as_secs_f64() * 1000.0;
+ let start = std::time::Instant::now();
+ klad_core::history::step(&mut probe, klad_core::history::Stack::Undo).unwrap();
+ let io = start.elapsed().as_secs_f64() * 1000.0;
+ klad_core::history::step(&mut probe, klad_core::history::Stack::Redo).unwrap();
+ let start = std::time::Instant::now();
+ let step = editing
+ .step(klad_core::history::Stack::Undo, &brushes)
+ .unwrap()
+ .map(|(_, d)| d.len());
+ println!(
+ "undo {node}: open bundle {opened:.0} ms, history step io {io:.0} ms, editor undo total {:.0} ms ({step:?} tiles)",
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ let start = std::time::Instant::now();
+ let step = editing
+ .step(klad_core::history::Stack::Redo, &brushes)
+ .unwrap()
+ .map(|(_, d)| d.len());
+ println!(
+ "redo {node}: editor redo total {:.0} ms ({step:?} tiles)",
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ println!(
+ "lift {node}: background prepare {prepare:.0} ms ({}x{}), compose base and top {compose:.0} ms, live {}",
+ lifted.width,
+ lifted.height,
+ planes.is_some()
+ );
+ }
+ }
+
+ fn rebuilt(scene: &Scene, planes: &Planes, lifted: &klad_render::Lifted, x: usize, y: usize) -> [f32; 4] {
+ let i = (y / 256) * scene.cols() + x / 256;
+ let o = ((y % 256) * 256 + x % 256) * 4;
+ let pick = |tiles: &Tiles| -> [f32; 4] {
+ let t = &tiles.iter().find(|(k, _)| *k == i).unwrap().1;
+ [t[o].to_f32(), t[o + 1].to_f32(), t[o + 2].to_f32(), t[o + 3].to_f32()]
+ };
+ let [rx, ry, rw, rh] = lifted.rect;
+ let lx = ((x as f32 + 0.5 - rx) / rw * lifted.width as f32) as usize;
+ let ly = ((y as f32 + 0.5 - ry) / rh * lifted.height as f32) as usize;
+ let l: [f32; 4] = if lx < lifted.width as usize && ly < lifted.height as usize {
+ let at = (ly * lifted.width as usize + lx) * 4;
+ [0, 1, 2, 3].map(|c| lifted.pixels[at + c].to_f32() * planes.opacity)
+ } else {
+ [0.0; 4]
+ };
+ let base = pick(&planes.base);
+ let mut px: [f32; 4] = [0, 1, 2, 3].map(|c| l[c] + base[c] * (1.0 - l[3]));
+ planes.runs.iter().for_each(|(mix, tiles)| {
+ let t = pick(tiles);
+ px = match mix {
+ Mix::Over => [0, 1, 2, 3].map(|c| t[c] + px[c] * (1.0 - t[3])),
+ Mix::Multiply => [px[0] * t[0], px[1] * t[1], px[2] * t[2], px[3]],
+ Mix::Screen => [0, 1, 2, 3].map(|c| t[c] + px[c] * (1.0 - t[c])),
+ Mix::Add => [0, 1, 2, 3].map(|c| t[c] + px[c]),
+ };
+ });
+ px
+ }
+
+ #[test]
+ fn lifted_planes_rebuild_the_same_picture_under_blend_modes() {
+ [Blend::Normal, Blend::Multiply, Blend::Screen]
+ .iter()
+ .for_each(|&blend| {
+ let dir = bundle(&format!("lift-{blend:?}"), blend);
+ let scene = Scene::open(&dir).unwrap();
+ let (path, _, index, nodes) = scene.node_slot("n1").unwrap();
+ let (w, h) = scene.size();
+ let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
+ let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
+ let planes = scene.lift_planes(&path, &lower, &upper).unwrap().unwrap();
+ let lifted =
+ klad_render::rasterize_region(&nodes[index..=index], [48.0, 48.0, 404.0, 154.0], 4096, 1.0)
+ .unwrap();
+ let paint: Rasters = scene
+ .rasters
+ .iter()
+ .filter(|(k, _)| scene.cels.contains_key(*k))
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ let full = compose(&scene.bundle.doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
+ [(100usize, 100usize), (300, 60), (520, 250), (60, 190)]
+ .iter()
+ .for_each(|&(x, y)| {
+ let px = rebuilt(&scene, &planes, &lifted, x, y);
+ let got = [0, 1, 2].map(|c| (px[c] / px[3].max(1e-6) * 255.0).round() as i32);
+ let want = full.pixel(x as u32, y as u32);
+ assert!(
+ got.iter().zip(&want[..3]).all(|(a, b)| (a - *b as i32).abs() <= 3),
+ "{blend:?} at ({x},{y}): {got:?} vs {want:?}"
+ );
+ });
+ assert_eq!(planes.runs.len(), if blend == Blend::Normal { 1 } else { 2 });
+ });
+ let dir = bundle("lift-overlay", Blend::Overlay);
+ let scene = Scene::open(&dir).unwrap();
+ let (path, _, _, _) = scene.node_slot("n1").unwrap();
+ let (w, h) = scene.size();
+ let empty = Raster::new(w, h);
+ assert!(scene.lift_planes(&path, &empty, &empty).unwrap().is_none());
+ assert!(scene.node_slot("cv").is_none());
+ }
+
+ #[test]
+ fn undo_and_redo_reuse_remembered_vector_rasters() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("memo", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ let before = scene.rasters["cv"].hash();
+ let ops = klad_core::ops::parse_lines(r#"{"op":"set","id":"n1","transform.x":60}"#).unwrap();
+ scene.apply(&ops, &brushes).unwrap();
+ let after = scene.rasters["cv"].hash();
+ assert_ne!(before, after);
+ assert!(scene.memo.iter().any(|(c, _, r)| c == "cv" && r.hash() == before));
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().unwrap();
+ assert_eq!(scene.rasters["cv"].hash(), before);
+ assert!(scene.memo.iter().any(|(c, _, r)| c == "cv" && r.hash() == after));
+ scene.step(klad_core::history::Stack::Redo, &brushes).unwrap().unwrap();
+ assert_eq!(scene.rasters["cv"].hash(), after);
+ let fresh = rasterize_nodes(&nodes_of(&scene.bundle.doc, "cv"), 600, 300).unwrap();
+ assert_eq!(fresh.hash(), after);
+ agrees(&scene);
+ }
+
+ #[test]
+ fn editor_fills_use_the_scene_reference_save_and_reload_identically() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("fill", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![1, 0]).unwrap();
+ let reference = scene.fill_reference(&FillRef::Layer("v".into()), &brushes).unwrap();
+ let seed = Seed {
+ x: 100.0,
+ y: 100.0,
+ tolerance: 0.1,
+ gap: 0.0,
+ expand: 0.0,
+ };
+ let coverage = klad_brush::flood(&reference, &seed);
+ assert_eq!(coverage.pixels(), 400 * 150);
+ let fill = Fill::new(
+ scene.next_mark_id(),
+ [0.9, 0.7, 0.2, 1.0],
+ FillSource::Seed {
+ seed,
+ reference: FillRef::Layer("v".into()),
+ },
+ coverage,
+ );
+ let touched = scene.commit_fill(fill, &brushes).unwrap();
+ assert!(!touched.is_empty());
+ scene.save_active("fill").unwrap();
+ let other = Scene::open(&dir).unwrap();
+ assert_eq!(other.rasters["ca"].hash(), scene.rasters["ca"].hash());
+ assert_eq!(
+ rows(&other).iter().find(|r| r.id == "a").map(|r| (r.strokes, r.fills)),
+ Some((30, 1))
+ );
+ let image = scene.sample((300.0, 120.0), false).unwrap().unwrap();
+ let layer = scene.sample((300.0, 120.0), true).unwrap().unwrap();
+ assert!(
+ (layer[0] - 0.9).abs() < 0.01 && (layer[2] - 0.2).abs() < 0.01,
+ "{layer:?}"
+ );
+ assert!(image[3] > 0.99);
+ assert!(scene.sample((-5.0, 3.0), false).unwrap().is_none());
+ let undo = scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().unwrap();
+ assert!(undo.0.contains("fill"));
+ assert_eq!(fills(&scene.cels["ca"]), 0);
+ agrees(&scene);
+ }
+
+ fn onion_agrees(scene: &Scene) -> usize {
+ let doc = &scene.bundle.doc;
+ let paint: Rasters = scene
+ .rasters
+ .iter()
+ .filter(|(k, _)| scene.cels.contains_key(*k))
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ let plan = onion::plan(doc, scene.frame, &scene.onion_layers(), &scene.onion);
+ let onions = onion::build(doc, &plan, &scene.rasters);
+ let full = klad_render::compose_view(doc, scene.frame, &paint, View::scaled(1.0), None, Some(&onions)).unwrap();
+ let plain = compose(doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
+ let points: Vec<(usize, usize)> = (0..12)
+ .flat_map(|i| (0..6).map(move |j| (i * 50 + 7, j * 50 + 9)))
+ .collect();
+ points.iter().for_each(|&(x, y)| {
+ let reference = full.pixel(x as u32, y as u32);
+ let tiled = tile_rgb(scene, x, y);
+ assert!(
+ tiled.iter().zip(&reference[..3]).all(|(a, b)| a.abs_diff(*b) <= 2),
+ "({x},{y}) at frame {}: tiled {tiled:?} full {reference:?}",
+ scene.frame
+ );
+ });
+ points
+ .iter()
+ .filter(|&&(x, y)| full.pixel(x as u32, y as u32) != plain.pixel(x as u32, y as u32))
+ .count()
+ }
+
+ #[test]
+ fn the_editor_onion_matches_the_cli_on_every_path() {
+ let brushes = BrushSet::presets();
+ let dir = animated("onion");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![1]).unwrap();
+ scene.onion_on = true;
+ let clipped = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","clip":true}"#).unwrap();
+ scene.apply(&clipped, &brushes).unwrap();
+ scene.set_frame(2, &brushes).unwrap();
+ assert!(!scene.fast);
+ assert_eq!(
+ scene.onion_plan(2)[0]
+ .1
+ .iter()
+ .map(|g| g.cel.as_str())
+ .collect::<Vec<_>>(),
+ ["a0"]
+ );
+ assert!(onion_agrees(&scene) > 3, "the onion shows");
+ scene.onion_on = false;
+ assert!(!scene.refresh_onions(&brushes).unwrap().is_empty());
+ assert_eq!(onion_agrees(&scene), 0);
+ scene.onion_on = true;
+ scene.refresh_onions(&brushes).unwrap();
+ let normal = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","blend":"normal","clip":false}"#).unwrap();
+ scene.apply(&normal, &brushes).unwrap();
+ assert!(scene.fast, "the onion of the active layer rides in the cached below");
+ assert!(onion_agrees(&scene) > 3);
+ scene.set_active(vec![2]).unwrap();
+ scene.onion_marked.insert("a".into());
+ scene.refresh_onions(&brushes).unwrap();
+ assert!(scene.fast);
+ assert!(onion_agrees(&scene) > 3, "a marked layer keeps its onion");
+ (0..6).for_each(|f| {
+ scene.set_frame(f, &brushes).unwrap();
+ onion_agrees(&scene);
+ });
+ let before = scene.frame_key(5, true, 0, 1);
+ let stroke =
+ klad_core::ops::parse_lines(r#"{"op":"stroke","layer":"a","frame":2,"path":"M10 10 L200 100","size":12}"#)
+ .unwrap();
+ scene.apply(&stroke, &brushes).unwrap();
+ assert_ne!(scene.frame_key(5, true, 0, 1), before, "a2 is a ghost of frame 5");
+ let changed = scene.frame_job(scene.frame, &brushes);
+ assert!(changed.is_none(), "ghosts stay loaded after an edit");
+ }
+
+ #[test]
+ fn frame_keys_share_holds_and_links_and_follow_edits() {
+ let brushes = BrushSet::presets();
+ let dir = animated("keys");
+ let mut scene = Scene::open(&dir).unwrap();
+ let fp = brushes.fingerprint();
+ let keys: Vec<u64> = (0..6).map(|f| scene.frame_key(f, false, 0, fp)).collect();
+ assert_eq!(keys[0], keys[1], "a hold");
+ assert_ne!(keys[1], keys[2]);
+ assert_ne!(keys[2], keys[3]);
+ assert_eq!(keys[4], keys[5]);
+ assert_ne!(keys[0], keys[4], "the vector layer changed at frame 2");
+ assert_ne!(
+ scene.frame_key(0, false, 1, fp),
+ keys[0],
+ "the level is part of the key"
+ );
+ let stroke =
+ klad_core::ops::parse_lines(r#"{"op":"stroke","layer":"a","frame":2,"path":"M10 10 L200 100","size":12}"#)
+ .unwrap();
+ scene.apply(&stroke, &brushes).unwrap();
+ let after: Vec<u64> = (0..6).map(|f| scene.frame_key(f, false, 0, fp)).collect();
+ let moved: Vec<usize> = (0..6).filter(|&f| after[f] != keys[f]).collect();
+ assert_eq!(moved, [2], "only the frame showing a2 changed");
+ let clips = klad_core::ops::parse_lines(
+ "{\"op\":\"clip\",\"add\":\"run\",\"from\":0,\"to\":3,\"loop\":true,\"fps\":24}\n{\"op\":\"export\",\"godot\":\"game\"}",
+ )
+ .unwrap();
+ let (dirty, _) = scene.apply_with(&clips, &brushes).unwrap();
+ assert!(dirty.is_empty(), "clips and the export folder change no pixels");
+ let with_clip: Vec<u64> = (0..6).map(|f| scene.frame_key(f, false, 0, fp)).collect();
+ assert_eq!(with_clip, after, "so every cached frame stays");
+ assert_eq!(scene.bundle.doc.timeline.clip("run").map(|c| c.fps), Some(Some(24)));
+ }
+
+ #[test]
+ fn a_frame_job_composes_what_the_canvas_shows() {
+ let brushes = BrushSet::presets();
+ let dir = animated("job");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![1]).unwrap();
+ scene.onion_on = true;
+ let request = scene.frame_request(2, true, 0, &brushes);
+ assert_eq!(
+ request.paint,
+ [("a".to_string(), "a2".to_string())],
+ "a2 is not loaded yet"
+ );
+ let key = request.key;
+ let done = request.run().unwrap();
+ let image = scene.absorb(done);
+ assert_eq!(image.key, key);
+ assert_eq!((image.width, image.height), (600, 300));
+ assert_eq!(image.mips.len(), crate::gpu::levels_for((600, 300)) as usize);
+ assert_eq!(
+ image.mips.last().unwrap().len(),
+ 2 * 4,
+ "600x300 ends at 2x1, as wgpu sizes the levels"
+ );
+ assert!(scene.has_frame(2), "the job's drawings were kept");
+ scene.set_frame(2, &brushes).unwrap();
+ [(60usize, 60usize), (300, 120), (520, 250), (10, 290), (157, 33)]
+ .iter()
+ .for_each(|&(x, y)| {
+ let at = (y * 600 + x) * 4;
+ let got = &image.mips[0][at..at + 3];
+ let want = tile_rgb(&scene, x, y);
+ assert!(
+ got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 2),
+ "({x},{y}) {got:?} vs {want:?}"
+ );
+ });
+ let half = scene.frame_request(2, true, 1, &brushes).run().unwrap().image;
+ assert_eq!((half.width, half.height), (300, 150));
+ }
+
+ #[test]
+ fn painting_into_a_layer_without_a_cel_creates_one() {
+ let brushes = BrushSet::presets();
+ let dir = std::env::temp_dir().join(format!("draw-scene-empty-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(64, 64);
+ let mut layer = Layer::paint("p", "p", "c1");
+ layer.cels_mut().unwrap().clear();
+ doc.layers.push(layer);
+ Bundle::create(&dir, doc).unwrap();
+ let mut scene = Scene::open(&dir).unwrap();
+ assert!(scene.can_paint());
+ let stroke = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 8.0, 1).with_points(&[(32.0, 32.0, 1.0)], 0.0);
+ let mut buffer = StrokeBuffer::new(64, 64);
+ let mut live = StrokePainter::new(brushes.get("ink").unwrap(), &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ let reopened = Bundle::open(&dir).unwrap();
+ let cel = reopened.doc.layer("p").unwrap().cels()[0].id.clone();
+ assert_eq!(reopened.read_strokes("p", &cel).unwrap().len(), 1);
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().unwrap();
+ assert!(scene.bundle.doc.layer("p").unwrap().cels().is_empty());
+ assert!(!scene.bundle.strokes_path("p", &cel).exists());
+ scene.step(klad_core::history::Stack::Redo, &brushes).unwrap().unwrap();
+ assert_eq!(scene.active_marks().len(), 1);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app stroke_edit_timing -- --ignored --nocapture (DENSE=1 packs the strokes into 640 px)"]
+ fn stroke_edit_timing() {
+ let brushes = BrushSet::presets();
+ let dir = std::env::temp_dir().join(format!("draw-scene-edit-timing-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(2048, 2048);
+ doc.canvas.background = Some("#f4efe6".into());
+ doc.layers = vec![Layer::paint("ink", "ink", "c1")];
+ let b = Bundle::create(&dir, doc).unwrap();
+ let side = if std::env::var("DENSE").is_ok() { 640.0 } else { 2048.0 };
+ let mut synth = Synth::canvas(side, side);
+ synth.brushes = vec!["ink".into(), "pencil".into(), "marker".into()];
+ b.write_marks("ink", "c1", &marks(synth.strokes(1000, 3))).unwrap();
+ let mut scene = Scene::open(&dir).unwrap();
+ let ids: Vec<u32> = scene.active_marks().iter().map(Mark::id).collect();
+ let timed = |scene: &mut Scene, lines: String, what: &str| {
+ let start = std::time::Instant::now();
+ let dirty = scene
+ .apply(&klad_core::ops::parse_lines(&lines).unwrap(), &brushes)
+ .unwrap();
+ let applied = start.elapsed().as_secs_f64() * 1000.0;
+ scene.compose(&dirty, None).unwrap();
+ println!(
+ "{what}: applied {applied:.0} ms, visible after {:.0} ms ({} tiles)",
+ start.elapsed().as_secs_f64() * 1000.0,
+ dirty.len()
+ );
+ };
+ [0usize, 250, 500, 750, 990].iter().for_each(|&i| {
+ let line = format!(r##"{{"op":"set","id":"c1:s{}","color":"#c03020"}}"##, ids[i]);
+ timed(&mut scene, line, &format!("recolour stroke {}", i + 1));
+ });
+ let moved: Vec<String> = ids[940..990].iter().map(|id| format!("\"c1:s{id}\"")).collect();
+ let line = format!(r#"{{"op":"transform","ids":[{}],"x":40,"y":25}}"#, moved.join(","));
+ timed(&mut scene, line, "move 50 strokes");
+ let start = std::time::Instant::now();
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap();
+ println!("undo the move: {:.0} ms", start.elapsed().as_secs_f64() * 1000.0);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn stroke_edits_from_either_side_replay_in_place_and_share_history() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("strokes", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![1, 0]).unwrap();
+ let ids: Vec<u32> = scene.active_marks().iter().map(Mark::id).collect();
+ let cel = scene.active_cel().unwrap();
+ let edit = format!(
+ r##"{{"op":"set","id":"{cel}:s{}","color":"#ff0000","size":30}}
+{{"op":"transform","ids":["{cel}:s{}","{cel}:s{}"],"x":40,"rotate":10}}
+{{"op":"rm","id":"{cel}:s{}"}}"##,
+ ids[3], ids[10], ids[11], ids[20]
+ );
+ let dirty = scene
+ .apply(&klad_core::ops::parse_lines(&edit).unwrap(), &brushes)
+ .unwrap();
+ assert!(!dirty.is_empty());
+ let expected = |scene: &Scene| {
+ klad_brush::replay(600, 300, scene.active_marks(), &brushes)
+ .unwrap()
+ .raster
+ .hash()
+ };
+ assert_eq!(scene.active_marks().len(), ids.len() - 1);
+ assert_eq!(scene.rasters[&cel].hash(), expected(&scene));
+ agrees(&scene);
+ let mut outside = Bundle::open(&dir).unwrap();
+ let line = format!(r#"{{"op":"set","id":"{cel}:s{}","opacity":0.4}}"#, ids[5]);
+ outside.apply(&klad_core::ops::parse_lines(&line).unwrap()).unwrap();
+ scene.reload(&brushes).unwrap();
+ assert_eq!(scene.rasters[&cel].hash(), expected(&scene));
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().unwrap();
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap().unwrap();
+ assert_eq!(scene.active_marks().len(), ids.len());
+ assert_eq!(scene.rasters[&cel].hash(), expected(&scene));
+ agrees(&scene);
+ }
+
+ #[test]
+ fn clips_and_masks_compose_right_from_every_active_layer_and_lift_only_when_exact() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("clipmask", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.tint_mask = false;
+ let ops = klad_core::ops::parse_lines(
+ r#"{"op":"set","id":"b","clip":true,"blend":"multiply"}
+{"op":"add","mask":{"id":"m"},"in":"a"}
+{"op":"stroke","layer":"m","path":"M0 150 L600 150","size":60}"#,
+ )
+ .unwrap();
+ scene.apply(&ops, &brushes).unwrap();
+ assert!(
+ scene
+ .cels
+ .contains_key(&scene.bundle.doc.layer("m").unwrap().cels()[0].id)
+ );
+ assert_eq!(
+ rows(&scene)
+ .iter()
+ .map(|r| (r.id.as_str(), r.depth, r.mask, r.clip))
+ .collect::<Vec<_>>(),
+ [
+ ("b", 0, false, true),
+ ("g", 0, false, false),
+ ("a", 1, false, false),
+ ("m", 2, true, false),
+ ("v", 0, false, false)
+ ]
+ );
+ [vec![2], vec![1, 0], vec![1, 0, MASK], vec![0]]
+ .into_iter()
+ .for_each(|path| {
+ scene.set_active(path.clone()).unwrap();
+ assert!(!scene.fast, "{path:?}");
+ agrees(&scene);
+ });
+ let unclip = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","clip":false}"#).unwrap();
+ scene.apply(&unclip, &brushes).unwrap();
+ scene.set_active(vec![2]).unwrap();
+ assert!(scene.fast);
+ agrees(&scene);
+ let reclip = klad_core::ops::parse_lines(r#"{"op":"set","id":"b","clip":true}"#).unwrap();
+ scene.apply(&reclip, &brushes).unwrap();
+ assert!(!scene.fast);
+ agrees(&scene);
+ let (w, h) = scene.size();
+ let empty = Raster::new(w, h);
+ [vec![2], vec![1, 0], vec![1]].iter().for_each(|path| {
+ assert!(scene.lift_planes(path, &empty, &empty).unwrap().is_none(), "{path:?}");
+ });
+ let (path, _, index, nodes) = scene.node_slot("n1").unwrap();
+ let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
+ let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
+ let planes = scene.lift_planes(&path, &lower, &upper).unwrap().unwrap();
+ let lifted =
+ klad_render::rasterize_region(&nodes[index..=index], [48.0, 48.0, 404.0, 154.0], 4096, 1.0).unwrap();
+ let paint: Rasters = scene
+ .rasters
+ .iter()
+ .filter(|(k, _)| scene.cels.contains_key(*k))
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ let full = compose(&scene.bundle.doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
+ [(100usize, 100usize), (300, 60), (300, 150), (520, 250)]
+ .iter()
+ .for_each(|&(x, y)| {
+ let px = rebuilt(&scene, &planes, &lifted, x, y);
+ let got = [0, 1, 2].map(|c| (px[c] / px[3].max(1e-6) * 255.0).round() as i32);
+ let want = full.pixel(x as u32, y as u32);
+ assert!(
+ got.iter().zip(&want[..3]).all(|(a, b)| (a - *b as i32).abs() <= 3),
+ "({x},{y}): {got:?} vs {want:?}"
+ );
+ });
+ }
+
+ #[test]
+ fn painting_on_a_mask_hides_the_layer_live_and_after_commit() {
+ let brushes = BrushSet::presets();
+ let dir = bundle("maskpaint", Blend::Normal);
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.tint_mask = false;
+ let add = klad_core::ops::parse_lines(
+ r#"{"op":"add","mask":{"id":"m"},"in":"v"}
+{"op":"set","id":"g","visible":false}
+{"op":"set","id":"b","visible":false}"#,
+ )
+ .unwrap();
+ scene.apply(&add, &brushes).unwrap();
+ scene.set_active(vec![0, MASK]).unwrap();
+ assert!(scene.can_paint());
+ let before = tile_rgb(&scene, 250, 120);
+ assert_eq!(before, [0x33, 0x66, 0xaa]);
+ let stroke = Stroke::new(scene.next_mark_id(), "ink", [0.0, 0.0, 0.0, 1.0], 80.0, 3)
+ .with_points(&[(60.0, 120.0, 1.0), (440.0, 120.0, 1.0)], 5.0);
+ let mut buffer = StrokeBuffer::new(600, 300);
+ let mut live = StrokePainter::new(brushes.get("ink").unwrap(), &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ let index = 0;
+ let preview = Preview {
+ twin: None,
+ buffer: &buffer,
+ color: stroke.color(),
+ opacity: 1.0,
+ blend: StrokeBlend::Normal,
+ };
+ let shown = &scene.compose(&[index], Some(&preview)).unwrap()[0].1;
+ let at = (120 * 256 + 250) * 4;
+ let live_rgb = [0, 1, 2].map(|c| (shown[at + c].to_f32() / shown[at + 3].to_f32() * 255.0).round() as u8);
+ assert_ne!(live_rgb, before, "the live stroke on the mask changes nothing");
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ let after = tile_rgb(&scene, 250, 120);
+ assert_ne!(after, before, "the committed mask stroke changes nothing");
+ assert_eq!(after, live_rgb);
+ agrees(&scene);
+ let mut reopened = Scene::open(&dir).unwrap();
+ reopened.tint_mask = false;
+ assert_eq!(tile_rgb(&reopened, 250, 120), after);
+ reopened.set_active(vec![0, MASK]).unwrap();
+ let red = tile_rgb(&reopened, 250, 120);
+ reopened.tint_mask = true;
+ let tinted = tile_rgb(&reopened, 250, 120);
+ assert!(
+ tinted[1] + 60 < red[1] && tinted[0] > tinted[1] + 60,
+ "{tinted:?} vs {red:?}"
+ );
+ let clipped = klad_core::ops::parse_lines(
+ r#"{"op":"set","id":"g","visible":true}
+{"op":"set","id":"b","visible":true,"clip":true}
+{"op":"add","mask":{"id":"mb"},"in":"b"}
+{"op":"add","mask":{"id":"mg"},"in":"g"}"#,
+ )
+ .unwrap();
+ scene.apply(&clipped, &brushes).unwrap();
+ [vec![2, MASK], vec![1, MASK]].into_iter().for_each(|path| {
+ scene.set_active(path.clone()).unwrap();
+ let all = scene.all_tiles();
+ let before = scene.compose(&all, None).unwrap();
+ let stroke = Stroke::new(scene.next_mark_id(), "ink", [0.0, 0.0, 0.0, 1.0], 120.0, 5)
+ .with_points(&[(20.0, 150.0, 1.0), (580.0, 150.0, 1.0)], 5.0);
+ let mut buffer = StrokeBuffer::new(600, 300);
+ let mut live = StrokePainter::new(brushes.get("ink").unwrap(), &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ scene.commit_stroke(stroke, &mut buffer, StrokeBlend::Normal).unwrap();
+ scene.save_active("stroke").unwrap();
+ let after = scene.compose(&all, None).unwrap();
+ let changed = before
+ .iter()
+ .zip(&after)
+ .filter(|((_, a), (_, b))| a.iter().zip(b.iter()).any(|(x, y)| x != y))
+ .count();
+ assert!(changed > 0, "painting on the mask at {path:?} changed no tile");
+ agrees(&scene);
+ });
+ }
+
+ fn stress(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-scene-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(2048, 2048);
+ doc.canvas.background = Some("#f4efe6".into());
+ doc.timeline.frames = 48;
+ doc.timeline.fps = 24;
+ let ids: Vec<String> = (0..4).map(|i| format!("l{i}")).collect();
+ doc.layers = ids
+ .iter()
+ .map(|id| {
+ let mut layer = Layer::paint(id, id, &format!("{id}c0"));
+ *layer.cels_mut().unwrap() = (0..24).map(|k| Cel::at(&format!("{id}c{}", k * 2), k * 2)).collect();
+ layer
+ })
+ .collect();
+ let b = Bundle::create(&dir, doc).unwrap();
+ let synth = Synth::canvas(2048.0, 2048.0);
+ ids.iter().enumerate().for_each(|(i, id)| {
+ (0..24).for_each(|k| {
+ let strokes = synth.strokes(60, (i * 100 + k) as u64);
+ b.write_marks(id, &format!("{id}c{}", k * 2), &marks(strokes)).unwrap();
+ })
+ });
+ dir
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app frame_timing -- --ignored --nocapture"]
+ fn frame_timing() {
+ let brushes = BrushSet::presets();
+ let dir = stress("frames-timing");
+ let start = std::time::Instant::now();
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![3]).unwrap();
+ println!("open: {:.0} ms", start.elapsed().as_secs_f64() * 1000.0);
+ let all = scene.all_tiles();
+ let ms = |s: std::time::Instant| s.elapsed().as_secs_f64() * 1000.0;
+ let mut first = Vec::new();
+ (1..48).for_each(|f| {
+ let start = std::time::Instant::now();
+ let job = scene.frame_job(f, &brushes);
+ let loaded = job.map(|j| j.run().unwrap());
+ let load = ms(start);
+ let start = std::time::Instant::now();
+ if let Some(l) = loaded {
+ scene.take_loaded(l.paint, l.vector);
+ }
+ scene.set_frame(f, &brushes).unwrap();
+ scene.compose(&all, None).unwrap();
+ if f % 2 == 0 {
+ first.push((load, ms(start)));
+ }
+ });
+ let avg = |v: &[f64]| v.iter().sum::<f64>() / v.len() as f64;
+ let loads: Vec<f64> = first.iter().map(|(l, _)| *l).collect();
+ let shows: Vec<f64> = first.iter().map(|(_, s)| *s).collect();
+ println!(
+ "first visit: load {:.0} ms avg (max {:.0}), then show {:.0} ms avg (max {:.0})",
+ avg(&loads),
+ loads.iter().copied().fold(0.0, f64::max),
+ avg(&shows),
+ shows.iter().copied().fold(0.0, f64::max)
+ );
+ println!(
+ "memory after one pass: {} MB ({} drawings cached)",
+ scene.cache_bytes() >> 20,
+ scene.cels.len()
+ );
+ let steps: Vec<f64> = (0..3)
+ .flat_map(|_| (0..48).rev().collect::<Vec<u32>>())
+ .map(|f| {
+ let start = std::time::Instant::now();
+ scene.set_frame(f, &brushes).unwrap();
+ scene.compose(&all, None).unwrap();
+ ms(start)
+ })
+ .collect();
+ let mut sorted = steps.clone();
+ sorted.sort_by(f64::total_cmp);
+ println!(
+ "step back and forth (set frame, caches, compose all {} tiles): median {:.0} ms, p90 {:.0} ms, max {:.0} ms",
+ all.len(),
+ sorted[sorted.len() / 2],
+ sorted[sorted.len() * 9 / 10],
+ sorted[sorted.len() - 1]
+ );
+ println!(
+ "memory: {} MB ({} drawings cached)",
+ scene.cache_bytes() >> 20,
+ scene.cels.len()
+ );
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ fn percentile(values: &[f64], at: f64) -> f64 {
+ let mut sorted = values.to_vec();
+ sorted.sort_by(f64::total_cmp);
+ sorted[((sorted.len() - 1) as f64 * at).round() as usize]
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app playback_timing -- --ignored --nocapture"]
+ fn playback_timing() {
+ use crate::frames::{FrameCache, Player};
+ use std::time::{Duration, Instant};
+ let brushes = BrushSet::presets();
+ let dir = stress("playback-timing");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![3]).unwrap();
+ let mut cache = FrameCache::new(std::sync::Arc::new(|| {}));
+ let tick = Duration::from_micros(8333);
+ let fps = scene.bundle.doc.timeline.fps;
+ let loops = 4u32;
+ let start = Instant::now();
+ let mut player = Player::new(start, 0, (0, 47), fps, false);
+ let mut ui = Vec::new();
+ while start.elapsed() < Duration::from_secs_f64((48 * loops) as f64 / fps as f64) {
+ let begin = Instant::now();
+ cache.collect(&mut scene);
+ let now = Instant::now();
+ player.tick(now, |f| {
+ let key = cache.key(&mut scene, f, false, &brushes);
+ cache.has(key)
+ });
+ player
+ .ahead(now, 48)
+ .into_iter()
+ .try_for_each(|f| cache.request(&mut scene, f, false, &brushes, false).then_some(()));
+ cache.take();
+ cache.prune(&BTreeSet::new());
+ ui.push(begin.elapsed().as_secs_f64() * 1000.0);
+ std::thread::sleep(tick.saturating_sub(begin.elapsed()));
+ }
+ println!(
+ "playback at {fps} fps, 48 frames (24 distinct), {loops} loops: dropped per loop {:?}",
+ player.drops
+ );
+ println!(
+ "UI thread per tick: median {:.2} ms, p99 {:.2} ms, max {:.1} ms",
+ percentile(&ui, 0.5),
+ percentile(&ui, 0.99),
+ percentile(&ui, 1.0)
+ );
+ println!(
+ "memory: frame cache {} frames, {} MB; drawings {} MB ({} cached)",
+ cache.len(),
+ cache.bytes() >> 20,
+ scene.cache_bytes() >> 20,
+ scene.cels.len()
+ );
+ let steps: Vec<f64> = (0..3)
+ .flat_map(|_| (0..48u32).rev())
+ .map(|f| {
+ let begin = Instant::now();
+ scene.move_to(f);
+ let key = cache.key(&mut scene, f, false, &brushes);
+ assert!(cache.has(key));
+ cache.touch(key);
+ begin.elapsed().as_secs_f64() * 1000.0
+ })
+ .collect();
+ println!(
+ "step through the cache (UI work before the GPU shows it): median {:.3} ms, max {:.3} ms",
+ percentile(&steps, 0.5),
+ percentile(&steps, 1.0)
+ );
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app held_step_timing -- --ignored --nocapture"]
+ fn held_step_timing() {
+ use crate::frames::FrameCache;
+ use std::time::{Duration, Instant};
+ let brushes = BrushSet::presets();
+ let dir = stress("held-step-timing");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![3]).unwrap();
+ let mut cache = FrameCache::new(std::sync::Arc::new(|| {}));
+ let repeat = Duration::from_millis(33);
+ let start = Instant::now();
+ let mut next_repeat = start + repeat;
+ let mut stepped = start;
+ let mut shown: Vec<(u32, f64)> = vec![(0, 0.0)];
+ let mut ignored = 0;
+ while scene.frame < 47 || shown.last().map(|s| s.0) != Some(47) {
+ cache.collect(&mut scene);
+ let now = Instant::now();
+ let frame = scene.frame;
+ let key = cache.key(&mut scene, frame, false, &brushes);
+ let on_screen = shown.last().map(|s| s.0) == Some(frame);
+ if !on_screen && cache.has(key) {
+ shown.push((frame, now.duration_since(stepped).as_secs_f64() * 1000.0));
+ } else if !on_screen {
+ cache.request(&mut scene, frame, false, &brushes, true);
+ }
+ (1..=4).filter(|k| frame + k < 48).for_each(|k| {
+ cache.request(&mut scene, frame + k, false, &brushes, false);
+ });
+ if now >= next_repeat {
+ next_repeat += repeat;
+ match shown.last().map(|s| s.0) == Some(scene.frame) {
+ true => {
+ scene.move_to(scene.frame + 1);
+ stepped = now;
+ }
+ false => ignored += 1,
+ }
+ }
+ cache.take();
+ std::thread::sleep(Duration::from_micros(8333));
+ assert!(start.elapsed() < Duration::from_secs(60));
+ }
+ let frames: Vec<u32> = shown.iter().map(|s| s.0).collect();
+ assert_eq!(
+ frames,
+ (0..48).collect::<Vec<_>>(),
+ "every frame shows once, none skipped"
+ );
+ let waits: Vec<f64> = shown.iter().skip(1).map(|s| s.1).collect();
+ println!(
+ "held . from a cold start, key repeat every 33 ms: all 48 frames shown in {:.2} s, step to screen median {:.0} ms, p90 {:.0} ms, max {:.0} ms, {ignored} repeats ignored while a frame was loading",
+ start.elapsed().as_secs_f64(),
+ percentile(&waits, 0.5),
+ percentile(&waits, 0.9),
+ percentile(&waits, 1.0)
+ );
+ println!(
+ "drawings kept: {} ({} MB), frames cached: {} ({} MB)",
+ scene.cels.len(),
+ scene.cache_bytes() >> 20,
+ cache.len(),
+ cache.bytes() >> 20
+ );
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app onion_dab_timing -- --ignored --nocapture"]
+ fn onion_dab_timing() {
+ use std::time::Instant;
+ let brushes = BrushSet::presets();
+ let dir = stress("onion-dab-timing");
+ let mut scene = Scene::open(&dir).unwrap();
+ scene.set_active(vec![3]).unwrap();
+ scene.set_frame(10, &brushes).unwrap();
+ let points: Vec<(f32, f32, f32)> = (0..240)
+ .map(|i| {
+ let t = i as f32 / 239.0;
+ (200.0 + 1600.0 * t, 1024.0 + 500.0 * (t * 9.0).sin(), 0.4 + 0.6 * t)
+ })
+ .collect();
+ [false, true].iter().for_each(|&onion| {
+ scene.onion_on = onion;
+ let start = Instant::now();
+ scene.refresh_onions(&brushes).unwrap();
+ let loaded = start.elapsed().as_secs_f64() * 1000.0;
+ scene.onion_on = false;
+ scene.refresh_onions(&brushes).unwrap();
+ scene.onion_on = onion;
+ let start = Instant::now();
+ scene.refresh_onions(&brushes).unwrap();
+ let onions = start.elapsed().as_secs_f64() * 1000.0;
+ let brush = brushes.get("ink").unwrap();
+ let stroke = Stroke::new(999, "ink", [0.1, 0.1, 0.1, 1.0], 24.0, 3).with_points(&points, 4.0);
+ let mut buffer = StrokeBuffer::new(2048, 2048);
+ let mut live = StrokePainter::live(brush, &stroke);
+ let times: Vec<f64> = stroke
+ .samples
+ .iter()
+ .map(|sample| {
+ let begin = Instant::now();
+ live.push(sample, &mut buffer);
+ let tiles = buffer.take_dirty();
+ let preview = Preview {
+ twin: None,
+ buffer: &buffer,
+ color: stroke.color(),
+ opacity: 1.0,
+ blend: StrokeBlend::Normal,
+ };
+ scene.compose(&tiles, Some(&preview)).unwrap();
+ begin.elapsed().as_secs_f64() * 1000.0
+ })
+ .collect();
+ println!(
+ "onion {}: {} ghosts loaded and built in {loaded:.0} ms, built from loaded drawings in {onions:.0} ms; dab to composed tiles per sample: median {:.2} ms, p90 {:.2} ms, max {:.2} ms ({} samples, fast path {})",
+ if onion { "on (2 before, 2 after)" } else { "off" },
+ scene.onion_plan(10).iter().map(|(_, g)| g.len()).sum::<usize>(),
+ percentile(&times, 0.5),
+ percentile(&times, 0.9),
+ percentile(&times, 1.0),
+ times.len(),
+ scene.fast
+ );
+ });
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-app batch_four_timing -- --ignored --nocapture"]
+ fn batch_four_timing() {
+ let brushes = BrushSet::presets();
+ let dir = std::env::temp_dir().join(format!("draw-scene-b4-timing-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(2048, 2048);
+ doc.canvas.background = Some("#f4efe6".into());
+ let flats = Layer::vector(
+ "flats",
+ "flats",
+ "cf",
+ vec![
+ Node::new(
+ "n1",
+ Shape::Ellipse {
+ cx: 1024.0,
+ cy: 1024.0,
+ rx: 700.0,
+ ry: 600.0,
+ },
+ )
+ .filled("#d0a060"),
+ ],
+ );
+ let mut shade = Layer::paint("shade", "shade", "cs");
+ shade.clip = true;
+ shade.blend = Blend::Multiply;
+ doc.layers = vec![flats, shade, Layer::paint("ink", "ink", "c1")];
+ let b = Bundle::create(&dir, doc).unwrap();
+ let mut synth = Synth::canvas(2048.0, 2048.0);
+ synth.brushes = vec!["ink".into(), "pencil".into(), "marker".into()];
+ b.write_marks("ink", "c1", &marks(synth.strokes(1000, 3))).unwrap();
+ b.write_marks("shade", "cs", &marks(synth.strokes(200, 4))).unwrap();
+ let mut scene = Scene::open(&dir).unwrap();
+ let all = scene.all_tiles();
+ [vec![2], vec![1]].into_iter().for_each(|path| {
+ scene.set_active(path.clone()).unwrap();
+ let start = std::time::Instant::now();
+ scene.compose(&all[..16], None).unwrap();
+ println!(
+ "compose 16 tiles with {} active ({}): {:.1} ms",
+ scene.active_id().unwrap(),
+ if scene.fast {
+ "cached below and above"
+ } else {
+ "whole stack"
+ },
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ });
+ scene.set_active(vec![2]).unwrap();
+ let line = r#"{"op":"lasso","layer":"ink","polygon":[[600,600],[1400,560],[1450,1300],[640,1380]],"cut":true,"x":40,"y":-25}"#;
+ let start = std::time::Instant::now();
+ let dirty = scene
+ .apply(&klad_core::ops::parse_lines(line).unwrap(), &brushes)
+ .unwrap();
+ let applied = start.elapsed().as_secs_f64() * 1000.0;
+ scene.compose(&dirty, None).unwrap();
+ println!(
+ "cut lasso and move in a 1,000-stroke cel: applied {applied:.0} ms, visible after {:.0} ms ({} tiles)",
+ start.elapsed().as_secs_f64() * 1000.0,
+ dirty.len()
+ );
+ let start = std::time::Instant::now();
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap();
+ println!("undo the cut: {:.0} ms", start.elapsed().as_secs_f64() * 1000.0);
+ let small = r#"{"op":"lasso","layer":"ink","polygon":[[900,900],[1200,880],[1220,1180],[920,1200]],"cut":true,"x":40,"y":-25}"#;
+ let start = std::time::Instant::now();
+ let applied = scene
+ .apply(&klad_core::ops::parse_lines(small).unwrap(), &brushes)
+ .unwrap();
+ println!(
+ "a 300 px cut lasso: {:.0} ms ({} tiles)",
+ start.elapsed().as_secs_f64() * 1000.0,
+ applied.len()
+ );
+ scene.step(klad_core::history::Stack::Undo, &brushes).unwrap();
+ let whole = line.replace(r#""cut":true,"#, "");
+ let start = std::time::Instant::now();
+ scene
+ .apply(&klad_core::ops::parse_lines(&whole).unwrap(), &brushes)
+ .unwrap();
+ println!(
+ "the same lasso without cut (whole strokes only): {:.0} ms",
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
new file mode 100644
index 0000000..9500a1d
--- /dev/null
+++ b/crates/app/src/editor.rs
@@ -0,0 +1,4045 @@
+mod between;
+mod brushwin;
+mod buffer;
+mod cells;
+mod clips;
+mod commands;
+mod copy;
+mod depth;
+mod history;
+mod layers;
+mod look;
+mod make;
+mod options;
+mod panels;
+mod pins;
+mod prefs;
+mod selection;
+mod timeline;
+mod tweens;
+#[cfg(test)]
+mod ui_tests;
+
+use crate::color::{self, Hsva};
+use crate::commands::Cmd;
+use crate::composite::{Planes, Preview, Scene};
+use crate::frames::FrameCache;
+use crate::gpu::{CanvasPaint, QuadDraw, quad_uniform};
+use crate::jobs::Jobs;
+use crate::lift::{self, Prepared};
+use crate::messages::{Messages, Tone};
+use crate::pen::{self, Pen, PenEvent, Phase, device_key};
+use crate::settings::{self, Settings};
+use crate::stats::{Stats, lock};
+use crate::sync::{Watch, watch};
+use crate::theme::Hint;
+use crate::view::View;
+use anyhow::{Result, anyhow};
+use egui::{Color32, Key, Pos2, Rect, Sense, Vec2, vec2};
+use klad_brush::{
+ Brush, BrushSet, PressureCurve, Raster, Raw, Recorder, StrokeBuffer, StrokePainter, flood, needs_repaint, polygon,
+ stroke_blend,
+};
+use klad_core::brushes::{BrushDef, Curve, TipDef, pick_id};
+use klad_core::bundle::now_ms;
+use klad_core::color::parse_hex;
+use klad_core::doc::{Item, Kind, Linear, Loc, Node, Paint, Radial, Shape, Stop};
+use klad_core::fill::{self, Fill, FillRef, FillSource, Seed};
+use klad_core::history::Stack;
+use klad_core::markedit::{self, LassoAction, MarkTransform, address, apply_affine, invert};
+use klad_core::notes::{self, Note};
+use klad_core::ops::{LassoSpec, Op, apply_all};
+use klad_core::pathedit::{self, PathEdit, Side, Subpath};
+use klad_core::rng::{FNV_OFFSET, Rng, fnv};
+use klad_core::stroke::{Mark, Stroke, encode_cel};
+use klad_render::{overlay, vector};
+use serde_json::{Map, Value, json};
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::ops::RangeInclusive;
+use std::path::{Path, PathBuf};
+use std::sync::mpsc::Receiver;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+const HANDLE: f32 = 12.0;
+const REFILL_MS: f64 = 8.0;
+const KNOB: f32 = 30.0;
+const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
+
+fn raw_of(e: &PenEvent, c: Vec2, dt_ms: f32) -> Raw {
+ Raw {
+ x: c.x,
+ y: c.y,
+ pressure: e.recorded_pressure(),
+ tilt: e.tilt,
+ dt_ms,
+ }
+}
+
+fn to_canvas(m: [f32; 6], p: [f32; 2]) -> Vec2 {
+ let (x, y) = apply_affine(m, (p[0], p[1]));
+ vec2(x, y)
+}
+
+fn to_local(m: [f32; 6], c: Vec2) -> [f32; 2] {
+ invert(m).map_or([c.x, c.y], |inverse| {
+ let (x, y) = apply_affine(inverse, (c.x, c.y));
+ [x, y]
+ })
+}
+
+fn ms(start: Instant) -> f64 {
+ start.elapsed().as_secs_f64() * 1000.0
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Tool {
+ Brush,
+ Fill,
+ Select,
+ Strokes,
+ Direct,
+ Pen,
+ Shape,
+ Note,
+}
+
+struct PenPath {
+ anchors: Vec<pathedit::Anchor>,
+ dragging: bool,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct Part {
+ layer: String,
+ cel: String,
+ ids: Vec<u32>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct Picked {
+ cel: String,
+ ids: Vec<u32>,
+ cut: Option<Vec<[f32; 2]>>,
+ more: Vec<Part>,
+}
+
+type PartMarks<'a> = (String, String, &'a [Mark], &'a [u32]);
+
+impl Picked {
+ fn whole(cel: String, ids: Vec<u32>) -> Self {
+ Self {
+ cel,
+ ids,
+ cut: None,
+ more: Vec::new(),
+ }
+ }
+
+ fn key(&self) -> String {
+ let list = |cel: &str, ids: &[u32]| {
+ let ids: Vec<String> = ids.iter().map(u32::to_string).collect();
+ format!("{cel}:{}", ids.join(","))
+ };
+ let base = std::iter::once(list(&self.cel, &self.ids))
+ .chain(self.more.iter().map(|p| list(&p.cel, &p.ids)))
+ .collect::<Vec<_>>()
+ .join(";");
+ match &self.cut {
+ Some(polygon) => {
+ let bytes: Vec<u8> = polygon.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
+ format!("{base}:cut{:x}", fnv(FNV_OFFSET, &bytes))
+ }
+ None => base,
+ }
+ }
+
+ fn addresses(&self) -> Vec<String> {
+ self.ids
+ .iter()
+ .map(|id| address(&self.cel, *id))
+ .chain(
+ self.more
+ .iter()
+ .flat_map(|p| p.ids.iter().map(|id| address(&p.cel, *id))),
+ )
+ .collect()
+ }
+
+ fn count(&self) -> usize {
+ self.ids.len() + self.more.iter().map(|p| p.ids.len()).sum::<usize>()
+ }
+}
+
+fn union_box(a: Option<[f32; 4]>, b: Option<[f32; 4]>) -> Option<[f32; 4]> {
+ match (a, b) {
+ (Some(a), Some(b)) => Some([a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]),
+ (a, b) => a.or(b),
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct Direct {
+ node: String,
+ points: BTreeSet<usize>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum PointGrab {
+ Anchors,
+ Handle(usize, Side),
+ Marquee { on_shape: bool },
+}
+
+#[derive(Clone, Copy, Debug)]
+struct PointDrag {
+ grab: PointGrab,
+ start: Vec2,
+ now: Vec2,
+ free: bool,
+}
+
+struct PathCommit {
+ job: Receiver<Result<(u64, Raster)>>,
+ ops: Vec<Op>,
+ cel: String,
+ preview: Vec<Subpath>,
+ node: String,
+}
+
+struct Shaped {
+ node: String,
+ rev: u64,
+ subs: Vec<Subpath>,
+ matrix: [f32; 6],
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct FillTool {
+ reference: FillRef,
+ tolerance: f32,
+ gap: f32,
+ expand: f32,
+ opacity: f32,
+}
+
+impl Default for FillTool {
+ fn default() -> Self {
+ Self {
+ reference: FillRef::This,
+ tolerance: fill::TOLERANCE,
+ gap: 4.0,
+ expand: fill::EXPAND,
+ opacity: 1.0,
+ }
+ }
+}
+
+struct Lasso {
+ points: Vec<Vec2>,
+ start: Pos2,
+ far: bool,
+}
+
+struct CutView {
+ key: String,
+ rev: u64,
+ marks: Vec<Mark>,
+ lassoed: Vec<u32>,
+ chosen: Vec<u32>,
+ more: Vec<PartView>,
+}
+
+struct PartView {
+ layer: String,
+ cel: String,
+ marks: Vec<Mark>,
+ lassoed: Vec<u32>,
+ chosen: Vec<u32>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Grab {
+ Move,
+ Scale,
+ Rotate,
+ Stretch(usize),
+}
+
+fn grab(screen: [Pos2; 4], pos: Pos2, edges: bool) -> Option<Grab> {
+ let reach = crate::theme::GRAB;
+ let top = screen[0].lerp(screen[1], 0.5);
+ let center = screen.iter().fold(Vec2::ZERO, |a, p| a + p.to_vec2()) / 4.0;
+ let knob = top + (top.to_vec2() - center).normalized() * KNOB;
+ if pos.distance(knob) <= reach {
+ return Some(Grab::Rotate);
+ }
+ if screen.iter().any(|c| pos.distance(*c) <= reach) {
+ return Some(Grab::Scale);
+ }
+ let flat = screen.map(|p| p.to_vec2());
+ if let Some(side) = (0..4).find(|&side| edges && pos.distance(edge(&flat, side).to_pos2()) <= reach) {
+ return Some(Grab::Stretch(side));
+ }
+ let (min, max) = screen
+ .iter()
+ .fold((screen[0], screen[0]), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ Rect::from_min_max(min, max).contains(pos).then_some(Grab::Move)
+}
+
+fn edge(corners: &[Vec2; 4], side: usize) -> Vec2 {
+ (corners[side] + corners[(side + 1) % 4]) / 2.0
+}
+
+struct Drag {
+ grab: Grab,
+ node: String,
+ strokes: bool,
+ fresh: bool,
+ copy: bool,
+ start: Vec2,
+ now: Vec2,
+ center: Vec2,
+ corners: [Vec2; 4],
+}
+
+impl Drag {
+ fn scale(&self) -> f32 {
+ if self.grab != Grab::Scale {
+ return 1.0;
+ }
+ ((self.now - self.center).length() / (self.start - self.center).length().max(1.0)).clamp(0.02, 50.0)
+ }
+
+ fn angle(&self) -> f32 {
+ if self.grab != Grab::Rotate {
+ return 0.0;
+ }
+ (self.now - self.center).angle() - (self.start - self.center).angle()
+ }
+
+ fn stretch(&self) -> Option<(usize, Vec2, f32)> {
+ let Grab::Stretch(side) = self.grab else {
+ return None;
+ };
+ let pivot = edge(&self.corners, (side + 2) % 4);
+ let axis = if side % 2 == 0 { 1 } else { 0 };
+ let span = self.start[axis] - pivot[axis];
+ let k = if span.abs() < 1.0 {
+ 1.0
+ } else {
+ (self.now[axis] - pivot[axis]) / span
+ };
+ let k = if k.abs() < 0.02 {
+ 0.02f32.copysign(k)
+ } else {
+ k.clamp(-50.0, 50.0)
+ };
+ Some((axis, pivot, k))
+ }
+
+ fn affine(&self) -> [f32; 6] {
+ let c = self.center;
+ if let Some((axis, pivot, k)) = self.stretch() {
+ return match axis {
+ 0 => [k, 0.0, 0.0, 1.0, pivot.x * (1.0 - k), 0.0],
+ _ => [1.0, 0.0, 0.0, k, 0.0, pivot.y * (1.0 - k)],
+ };
+ }
+ match self.grab {
+ Grab::Move => {
+ let d = self.now - self.start;
+ [1.0, 0.0, 0.0, 1.0, d.x, d.y]
+ }
+ Grab::Scale => {
+ let k = self.scale();
+ [k, 0.0, 0.0, k, c.x * (1.0 - k), c.y * (1.0 - k)]
+ }
+ Grab::Rotate => {
+ let (s, k) = self.angle().sin_cos();
+ [k, -s, s, k, c.x - k * c.x + s * c.y, c.y - s * c.x - k * c.y]
+ }
+ Grab::Stretch(_) => IDENTITY,
+ }
+ }
+
+ fn preview(&self) -> [Vec2; 4] {
+ let a = self.affine();
+ self.corners.map(|c| {
+ let (x, y) = lift::affine_apply(a, (c.x, c.y));
+ vec2(x, y)
+ })
+ }
+
+ fn moved(&self) -> bool {
+ (self.now - self.start).length() > 0.5
+ }
+
+ fn mark_transform(&self) -> MarkTransform {
+ let pivot = Some([self.center.x, self.center.y]);
+ if let Some((axis, at, k)) = self.stretch() {
+ return MarkTransform {
+ sx: if axis == 0 { k } else { 1.0 },
+ sy: if axis == 1 { k } else { 1.0 },
+ pivot: Some([at.x, at.y]),
+ ..Default::default()
+ };
+ }
+ match self.grab {
+ Grab::Move => {
+ let d = self.now - self.start;
+ MarkTransform {
+ x: d.x,
+ y: d.y,
+ ..Default::default()
+ }
+ }
+ Grab::Scale => MarkTransform {
+ sx: self.scale(),
+ sy: self.scale(),
+ pivot,
+ ..Default::default()
+ },
+ Grab::Rotate => MarkTransform {
+ rotate: self.angle().to_degrees(),
+ pivot,
+ ..Default::default()
+ },
+ Grab::Stretch(_) => MarkTransform::default(),
+ }
+ }
+}
+
+struct Commit {
+ job: Receiver<Result<(u64, Raster)>>,
+ ops: Vec<Op>,
+ affine: [f32; 6],
+}
+
+struct LiftState {
+ key: String,
+ rev: u64,
+ job: Option<Receiver<Result<Prepared>>>,
+ ready: Option<(Prepared, Planes)>,
+ stage: usize,
+ commit: Option<Commit>,
+}
+
+struct Live {
+ stroke: Stroke,
+ painter: StrokePainter,
+ brush: Brush,
+ recorder: Recorder,
+ last_at: Instant,
+ twin: Option<(f32, Stroke, StrokePainter)>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Tuning {
+ hardness: Option<f32>,
+ size_min: f32,
+ size_gamma: f32,
+ taper: [f32; 2],
+ stabilizer: f32,
+ smoothing: f32,
+}
+
+impl Tuning {
+ fn of(def: &BrushDef) -> Self {
+ let curve = def.dynamics.size.pressure.unwrap_or(Curve {
+ min: 1.0,
+ max: 1.0,
+ gamma: 1.0,
+ });
+ Self {
+ hardness: def.hardness(),
+ size_min: curve.min,
+ size_gamma: curve.gamma,
+ taper: def.taper,
+ stabilizer: def.stabilizer,
+ smoothing: def.smoothing,
+ }
+ }
+
+ fn shape(&self, base: &BrushDef) -> BrushDef {
+ let mut def = base.clone();
+ if let (Some(hardness), TipDef::Round { .. }) = (self.hardness, &def.tip) {
+ def.tip = TipDef::Round { hardness };
+ }
+ let old = Tuning::of(base);
+ if (self.size_min, self.size_gamma) != (old.size_min, old.size_gamma) {
+ def.dynamics.size.pressure = Some(Curve {
+ min: self.size_min,
+ max: 1.0,
+ gamma: self.size_gamma,
+ });
+ }
+ def
+ }
+}
+
+#[derive(Default)]
+struct Readout {
+ pressure: f32,
+ device: u64,
+ tilt: (f32, f32),
+ eraser: bool,
+ tablet: bool,
+ samples: VecDeque<Instant>,
+}
+
+#[derive(Default)]
+struct Windows {
+ settings: bool,
+ brush: bool,
+ log: bool,
+ onion: bool,
+ link: bool,
+ clip: bool,
+ between: bool,
+ import: bool,
+ about: bool,
+}
+
+#[derive(Default)]
+struct PaletteState {
+ query: String,
+ selected: usize,
+ opened: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Want {
+ New,
+ Open,
+ Recent,
+}
+
+pub(crate) struct Editor {
+ pub(crate) scene: Scene,
+ brushes: BrushSet,
+ embedded: BTreeMap<String, BrushDef>,
+ buffer: StrokeBuffer,
+ live: Option<Live>,
+ tool: Tool,
+ brush: String,
+ previous_brush: String,
+ tuning: Tuning,
+ size: f32,
+ color: [f32; 4],
+ hsva: Hsva,
+ swatch_name: String,
+ fill: FillTool,
+ lasso: Option<Lasso>,
+ modifiers: egui::Modifiers,
+ opacity: f32,
+ flow: f32,
+ pub(crate) settings: Settings,
+ pub(crate) settings_path: Option<PathBuf>,
+ pub(crate) settings_dirty: bool,
+ pub(crate) wants: Option<Want>,
+ view: Option<View>,
+ canvas_rect: Rect,
+ navigating: bool,
+ focused: bool,
+ pen: Option<Pen>,
+ readout: Readout,
+ dirty: BTreeSet<usize>,
+ pending: Option<Instant>,
+ stats: Arc<Mutex<Stats>>,
+ watch: Option<Watch>,
+ external: Option<u64>,
+ rng: Rng,
+ spin: bool,
+ messages: Messages,
+ measured: BTreeMap<&'static str, String>,
+ pointer: Option<Pos2>,
+ jobs: Jobs,
+ windows: Windows,
+ palette: Option<PaletteState>,
+ queued: Vec<Cmd>,
+ tabs: Vec<bool>,
+ themed: bool,
+ lift_since: Instant,
+ key_shift: bool,
+ held: selection::Held,
+ sizing: Option<(f32, f32, Pos2)>,
+ second: [f32; 4],
+ samples: options::Samples,
+ swatch_drag: Option<usize>,
+ renaming: Option<layers::Rename>,
+ queued_activate: Option<Vec<usize>>,
+ layer_drag: Option<(layers::LayerRow, layers::Where)>,
+ canvas_wait: Option<timeline::CanvasWait>,
+ canvas_gen: u64,
+ buffering: buffer::BufferState,
+ custom: Option<BrushDef>,
+ brush_window: brushwin::BrushWindow,
+ look: look::LookState,
+ shapes: make::ShapeTool,
+ mirror: Option<f32>,
+ mirror_buffer: StrokeBuffer,
+ typing: BTreeMap<String, String>,
+ import_path: String,
+ depth: depth::Parallax,
+ batch: usize,
+ pen_path: Option<PenPath>,
+ pen_fill: bool,
+ pen_stroke: bool,
+ pen_width: f32,
+ thumbs: layers::Thumbs,
+ between: between::Between,
+ bindings: crate::commands::Bindings,
+ capturing: Option<Cmd>,
+ key_filter: String,
+ selection: Option<String>,
+ drag: Option<Drag>,
+ edits: BTreeMap<String, f32>,
+ texts: BTreeMap<String, String>,
+ pins: Vec<Note>,
+ note_at: Option<Vec2>,
+ note_text: String,
+ note_open: Option<u32>,
+ note_edit: String,
+ history: Option<(u64, Vec<history::Row>)>,
+ shared: (Option<String>, Vec<String>, u32),
+ ctx: egui::Context,
+ sel_box: Option<(String, u64, [Vec2; 4])>,
+ lift: Option<LiftState>,
+ zoom_px: f32,
+ picked: Option<Picked>,
+ also: Vec<String>,
+ direct: Option<Direct>,
+ shaped: Option<Shaped>,
+ point_drag: Option<PointDrag>,
+ path_commit: Option<PathCommit>,
+ simplify_px: f32,
+ under: Vec<String>,
+ cut_lasso: bool,
+ cut_view: Option<CutView>,
+ timeline: timeline::Timeline,
+ frames: FrameCache,
+ clipboard: Option<copy::Copied>,
+}
+
+fn hex_of(c: Color32) -> String {
+ let [r, g, b, a] = c.to_srgba_unmultiplied();
+ if a == 255 {
+ format!("#{r:02x}{g:02x}{b:02x}")
+ } else {
+ format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
+ }
+}
+
+fn color_of(hex: &str) -> Option<Color32> {
+ let [r, g, b, a] = parse_hex(hex).ok()?.map(|v| (v * 255.0).round() as u8);
+ Some(Color32::from_rgba_unmultiplied(r, g, b, a))
+}
+
+impl Editor {
+ pub(crate) fn open(ctx: egui::Context, path: &Path) -> Result<Self> {
+ let start = Instant::now();
+ let scene = Scene::open_lazy(path)?;
+ let brushes = BrushSet::for_bundle(&scene.bundle)?;
+ let embedded = scene.bundle.brushes()?;
+ let tuning = Tuning::of(brushes.def("ink").ok_or_else(|| anyhow!("no ink brush"))?);
+ let settings_path = settings::default_path();
+ let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();
+ let open = format!(
+ "{} layers, opened in {:.0} ms",
+ scene.bundle.doc.all_layers().len(),
+ ms(start)
+ );
+ let size = scene.size();
+ let watch = watch(path, ctx.clone());
+ let mut messages = Messages::default();
+ if let Err(e) = &watch {
+ messages.say(
+ Tone::Error,
+ format!("not watching the bundle, so agent edits will not show: {e}"),
+ None,
+ Instant::now(),
+ );
+ }
+ let measured = BTreeMap::from([("open", open)]);
+ let pins = notes::read(&scene.bundle);
+ let repaint = ctx.clone();
+ let mut frames = FrameCache::new(Arc::new(move || repaint.request_repaint()));
+ frames.disk = Some(scene.pictures());
+ let mut editor = Self {
+ dirty: scene.all_tiles().into_iter().collect(),
+ buffer: StrokeBuffer::new(size.0, size.1),
+ scene,
+ brushes,
+ embedded,
+ live: None,
+ tool: Tool::Brush,
+ brush: "ink".into(),
+ previous_brush: "ink".into(),
+ tuning,
+ size: 12.0,
+ color: [0.08, 0.08, 0.1, 1.0],
+ hsva: Hsva::from_rgba([0.08, 0.08, 0.1, 1.0], 0.0),
+ swatch_name: String::new(),
+ fill: FillTool::default(),
+ lasso: None,
+ modifiers: egui::Modifiers::default(),
+ opacity: 1.0,
+ flow: 1.0,
+ settings,
+ settings_path,
+ settings_dirty: false,
+ wants: None,
+ view: None,
+ canvas_rect: Rect::NOTHING,
+ navigating: false,
+ focused: false,
+ pen: Pen::install(),
+ readout: Readout::default(),
+ pending: None,
+ stats: Arc::default(),
+ watch: watch.ok(),
+ external: None,
+ rng: Rng::new(now_ms()),
+ spin: false,
+ messages,
+ measured,
+ pointer: None,
+ jobs: Jobs::default(),
+ windows: Windows::default(),
+ palette: None,
+ queued: Vec::new(),
+ tabs: Vec::new(),
+ themed: false,
+ lift_since: Instant::now(),
+ key_shift: false,
+ held: selection::Held::default(),
+ sizing: None,
+ second: [1.0, 1.0, 1.0, 1.0],
+ samples: options::Samples::default(),
+ swatch_drag: None,
+ renaming: None,
+ queued_activate: None,
+ layer_drag: None,
+ canvas_wait: None,
+ canvas_gen: 0,
+ buffering: buffer::BufferState::default(),
+ custom: None,
+ brush_window: brushwin::BrushWindow::default(),
+ look: look::LookState::default(),
+ shapes: make::ShapeTool::default(),
+ mirror: None,
+ mirror_buffer: StrokeBuffer::new(size.0, size.1),
+ typing: BTreeMap::new(),
+ import_path: String::new(),
+ depth: depth::Parallax::default(),
+ batch: timeline::FILL,
+ pen_path: None,
+ pen_fill: true,
+ pen_stroke: true,
+ pen_width: 3.0,
+ thumbs: layers::Thumbs::default(),
+ between: between::Between::default(),
+ bindings: crate::commands::Bindings::default(),
+ capturing: None,
+ key_filter: String::new(),
+ selection: None,
+ drag: None,
+ edits: BTreeMap::new(),
+ texts: BTreeMap::new(),
+ pins,
+ note_at: None,
+ note_text: String::new(),
+ note_open: None,
+ note_edit: String::new(),
+ history: None,
+ shared: (None, Vec::new(), 0),
+ ctx,
+ sel_box: None,
+ lift: None,
+ zoom_px: 1.0,
+ picked: None,
+ also: Vec::new(),
+ direct: None,
+ shaped: None,
+ point_drag: None,
+ path_commit: None,
+ simplify_px: 1.5,
+ under: Vec::new(),
+ cut_lasso: true,
+ cut_view: None,
+ clipboard: None,
+ timeline: timeline::Timeline::default(),
+ frames,
+ };
+ editor.use_defaults();
+ editor.request_canvas();
+ editor.tend_canvas(timeline::OPEN_WAIT)?;
+ Ok(editor)
+ }
+
+ pub(super) fn use_defaults(&mut self) {
+ let d = self.settings.defaults.clone();
+ if let Some(brush) = d.brush.filter(|b| self.brushes.def(b).is_some()) {
+ self.brush = brush;
+ }
+ if let Some(size) = d.size {
+ self.size = size.clamp(0.5, 500.0);
+ }
+ self.timeline.on = d.exposure.clamp(1, 8);
+ self.scene.onion.before = d.onion_before;
+ self.scene.onion.after = d.onion_after;
+ self.scene.onion.opacity = d.onion_opacity.clamp(0.05, 1.0);
+ self.bindings = crate::commands::Bindings::from_settings(&self.settings.keys);
+ }
+
+ pub(super) fn capture_key(&mut self, ui: &egui::Ui) {
+ let Some(cmd) = self.capturing else {
+ return;
+ };
+ let pressed = ui.input(|i| {
+ i.events.iter().find_map(|e| match e {
+ egui::Event::Key {
+ key,
+ pressed: true,
+ modifiers,
+ ..
+ } => Some((*key, *modifiers)),
+ _ => None,
+ })
+ });
+ let Some((key, modifiers)) = pressed else {
+ return;
+ };
+ self.capturing = None;
+ if key == egui::Key::Escape {
+ self.say(Tone::Info, "the key stays as it was");
+ return;
+ }
+ let keys = crate::commands::Keys::pressed(key, modifiers);
+ match self.bindings.bind(cmd, keys) {
+ Ok(()) => {
+ self.settings.keys = self.bindings.to_settings();
+ self.settings_dirty = true;
+ self.say(Tone::Done, format!("{} is now {}", cmd.spec().name, keys.label()));
+ }
+ Err(why) => self.say(Tone::Refused, why),
+ }
+ }
+
+ fn canvas_size(&self) -> Vec2 {
+ let (w, h) = self.scene.size();
+ vec2(w as f32, h as f32)
+ }
+
+ fn say(&mut self, tone: Tone, text: impl Into<String>) {
+ let anchor = self.pointer;
+ self.messages.say(tone, text, anchor, Instant::now());
+ self.ctx.request_repaint();
+ }
+
+ pub(crate) fn error(&mut self, e: impl std::fmt::Display) {
+ self.say(Tone::Error, format!("{e:#}"));
+ }
+
+ fn measure(&mut self, key: &'static str, text: String) {
+ self.measured.insert(key, text);
+ }
+
+ fn share_selection(&mut self) {
+ let items: Vec<String> = self
+ .selection
+ .iter()
+ .chain(self.direct.as_ref().map(|d| &d.node))
+ .cloned()
+ .chain(self.picked.iter().flat_map(Picked::addresses))
+ .collect();
+ let now = (self.scene.active_id(), items, self.scene.frame);
+ if now != self.shared {
+ let nodes = now.1.clone();
+ if let Err(e) = notes::write_selection(&self.scene.bundle, now.0.clone(), nodes, self.scene.frame) {
+ self.error(e);
+ }
+ self.shared = now;
+ }
+ }
+
+ fn sync(&mut self) -> Result<()> {
+ if let Some(first) = self.watch.as_ref().and_then(|w| w.events.try_iter().min()) {
+ self.external.get_or_insert(first);
+ self.pins = notes::read(&self.scene.bundle);
+ }
+ let committing = self.lift.as_ref().is_some_and(|l| l.commit.is_some()) || self.path_commit.is_some();
+ if self.live.is_some()
+ || self.drag.is_some()
+ || self.point_drag.is_some()
+ || committing
+ || self.external.is_none()
+ {
+ return Ok(());
+ }
+ if self.scene.disk_rev() == Some(self.scene.bundle.doc.rev) {
+ self.external = None;
+ return Ok(());
+ }
+ self.reload()
+ }
+
+ fn reload(&mut self) -> Result<()> {
+ let seen = self.external.take();
+ let start = Instant::now();
+ self.brushes.refresh(&self.scene.bundle)?;
+ self.embedded = self.scene.bundle.brushes()?;
+ let dirty = self.scene.reload(&self.brushes)?;
+ let (w, h) = self.scene.size();
+ if (self.buffer.grid().width, self.buffer.grid().height) != (w, h) {
+ self.buffer = StrokeBuffer::new(w, h);
+ self.mirror_buffer = StrokeBuffer::new(w, h);
+ self.view = None;
+ }
+ let tiles = dirty.len();
+ self.dirty.extend(dirty);
+ self.forget_missing_selection();
+ let took = ms(start);
+ let text = match self.scene.bundle.read_stamp() {
+ Some(s) => format!(
+ "rev {} by {}\nfile event after {} ms\n{tiles} tiles refreshed after {} ms ({took:.0} ms to reload)",
+ s.rev,
+ s.author,
+ seen.map_or(-1, |t| t as i64 - s.at_ms as i64),
+ now_ms() as i64 - s.at_ms as i64
+ ),
+ None => format!("{tiles} tiles refreshed in {took:.0} ms"),
+ };
+ self.measure("sync", text);
+ Ok(())
+ }
+
+ fn forget_missing_selection(&mut self) {
+ let doc = &self.scene.bundle.doc;
+ if self
+ .selection
+ .as_ref()
+ .is_some_and(|id| !matches!(doc.item(id), Some(Item::Node(..))))
+ {
+ self.selection = None;
+ }
+ let gone = |id: &str| match markedit::parse_address(id) {
+ Some((cel, mark)) => {
+ self.scene.active_cel().as_deref() != Some(cel)
+ || !self.scene.active_marks().iter().any(|m| m.id() == mark)
+ }
+ None => !matches!(doc.item(id), Some(Item::Node(..))),
+ };
+ if self.direct.as_ref().is_some_and(|d| gone(&d.node)) {
+ self.direct = None;
+ }
+ let active = self.scene.active_cel();
+ let active_id = self.scene.active_id();
+ let present: BTreeSet<u32> = self.scene.active_marks().iter().map(Mark::id).collect();
+ let frame = self.scene.frame;
+ let scene = &self.scene;
+ let shown = |layer: &str| {
+ scene
+ .bundle
+ .doc
+ .layer(layer)
+ .and_then(|l| l.content_at(frame))
+ .map(|c| c.id.clone())
+ };
+ self.picked = self.picked.take().and_then(|mut p| {
+ p.ids.retain(|id| present.contains(id));
+ let cut = p.cut.is_some();
+ p.more.retain_mut(|part| {
+ if shown(&part.layer).as_deref() != Some(part.cel.as_str()) {
+ return false;
+ }
+ let have: BTreeSet<u32> = scene.marks_of(&part.cel).iter().map(Mark::id).collect();
+ part.ids.retain(|id| have.contains(id));
+ !part.ids.is_empty() || cut
+ });
+ (Some(&p.cel) == active.as_ref() && (!p.ids.is_empty() || cut || !p.more.is_empty())).then_some(p)
+ });
+ self.also.retain(|id| {
+ Some(id) != active_id.as_ref() && scene.bundle.doc.layer(id).is_some_and(|l| l.kind() == Kind::Paint)
+ });
+ }
+
+ fn apply(&mut self, ops: Vec<Op>) -> Result<()> {
+ if ops.is_empty() {
+ return Ok(());
+ }
+ self.end_look_preview()?;
+ let start = Instant::now();
+ let dirty = self.scene.apply(&ops, &self.brushes)?;
+ self.measure(
+ "edit",
+ format!("edit applied, {} tiles refreshed in {:.0} ms", dirty.len(), ms(start)),
+ );
+ self.dirty.extend(dirty);
+ self.forget_missing_selection();
+ Ok(())
+ }
+
+ fn set(&mut self, id: &str, props: Vec<(String, Value)>) -> Result<()> {
+ if props.is_empty() {
+ return Ok(());
+ }
+ self.apply(vec![Op::Set {
+ id: id.to_string(),
+ props: props.into_iter().collect::<Map<String, Value>>(),
+ }])
+ }
+
+ fn step(&mut self, stack: Stack) -> Result<()> {
+ if self.live.is_some() || self.drag.is_some() || self.point_drag.is_some() || self.path_commit.is_some() {
+ return Ok(());
+ }
+ let start = Instant::now();
+ let word = if stack == Stack::Undo { "undid" } else { "redid" };
+ match self.scene.step(stack, &self.brushes)? {
+ Some((summary, dirty)) => {
+ let text = format!("{word} {summary} in {:.0} ms", ms(start));
+ self.measure("undo", text.clone());
+ self.say(Tone::Info, text);
+ self.dirty.extend(dirty);
+ self.forget_missing_selection();
+ }
+ None => self.say(
+ Tone::Refused,
+ format!("nothing to {}", if stack == Stack::Undo { "undo" } else { "redo" }),
+ ),
+ }
+ Ok(())
+ }
+
+ fn refresh_box(&mut self) {
+ let rev = self.scene.bundle.doc.rev;
+ let Some(id) = self.selection.clone() else {
+ self.sel_box = None;
+ return;
+ };
+ if self.sel_box.as_ref().is_some_and(|(s, r, _)| *s == id && *r == rev) {
+ return;
+ }
+ self.sel_box = overlay::node_world_box(&self.scene.bundle.doc, &id)
+ .ok()
+ .flatten()
+ .map(|[x, y, w, h]| {
+ (
+ id,
+ rev,
+ [vec2(x, y), vec2(x + w, y), vec2(x + w, y + h), vec2(x, y + h)],
+ )
+ });
+ }
+
+ fn selection_corners(&self) -> Option<(String, [Vec2; 4])> {
+ let (id, _, corners) = self.sel_box.as_ref()?;
+ (self.selection.as_ref() == Some(id)).then(|| (id.clone(), *corners))
+ }
+
+ fn refresh_cut(&mut self) {
+ let rev = self.scene.bundle.doc.rev;
+ let Some((key, polygon, ids, more)) = self.picked.as_ref().and_then(|p| {
+ p.cut
+ .clone()
+ .map(|polygon| (p.key(), polygon, p.ids.clone(), p.more.clone()))
+ }) else {
+ self.cut_view = None;
+ return;
+ };
+ if self.cut_view.as_ref().is_some_and(|v| v.key == key && v.rev == rev) {
+ return;
+ }
+ let split = |source: &[Mark], ids: Vec<u32>| {
+ let mut marks = source.to_vec();
+ let lassoed = markedit::split(&mut marks, &polygon, true);
+ let chosen: Vec<u32> = lassoed
+ .iter()
+ .copied()
+ .chain(ids.into_iter().filter(|id| !lassoed.contains(id)))
+ .collect();
+ (marks, lassoed, chosen)
+ };
+ let (marks, lassoed, chosen) = split(self.scene.active_marks(), ids);
+ let more = more
+ .into_iter()
+ .map(|p| {
+ let (marks, lassoed, chosen) = split(self.scene.marks_of(&p.cel), p.ids);
+ PartView {
+ layer: p.layer,
+ cel: p.cel,
+ marks,
+ lassoed,
+ chosen,
+ }
+ })
+ .collect();
+ self.cut_view = Some(CutView {
+ key,
+ rev,
+ marks,
+ lassoed,
+ chosen,
+ more,
+ });
+ }
+
+ fn picked_parts(&self) -> Vec<PartMarks<'_>> {
+ let Some(picked) = self.picked.as_ref() else {
+ return Vec::new();
+ };
+ let view = self
+ .cut_view
+ .as_ref()
+ .filter(|v| picked.cut.is_some() && v.key == picked.key());
+ if picked.cut.is_some() && view.is_none() {
+ return Vec::new();
+ }
+ let active = self.scene.active_id().unwrap_or_default();
+ let first: PartMarks = match view {
+ Some(v) => (active, picked.cel.clone(), &v.marks[..], &v.chosen[..]),
+ None => (active, picked.cel.clone(), self.scene.active_marks(), &picked.ids[..]),
+ };
+ std::iter::once(first)
+ .chain(
+ picked
+ .more
+ .iter()
+ .enumerate()
+ .map(|(k, p)| match view.and_then(|v| v.more.get(k)) {
+ Some(pv) => (p.layer.clone(), p.cel.clone(), &pv.marks[..], &pv.chosen[..]),
+ None => (p.layer.clone(), p.cel.clone(), self.scene.marks_of(&p.cel), &p.ids[..]),
+ }),
+ )
+ .collect()
+ }
+
+ fn picked_corners(&self) -> Option<(String, [Vec2; 4])> {
+ let picked = self.picked.as_ref()?;
+ let [x0, y0, x1, y1] = self
+ .picked_parts()
+ .iter()
+ .map(|(_, _, marks, ids)| markedit::bounds_of(marks, ids))
+ .fold(None, union_box)?;
+ Some((picked.key(), [vec2(x0, y0), vec2(x1, y0), vec2(x1, y1), vec2(x0, y1)]))
+ }
+
+ fn across(&self, action: LassoAction) -> LassoAction {
+ let spans = self.picked.as_ref().is_some_and(|p| !p.more.is_empty());
+ match action {
+ LassoAction::Transform(t) if spans && t.pivot.is_none() => {
+ let pivot = self
+ .picked_corners()
+ .map(|(_, c)| [(c[0].x + c[2].x) / 2.0, (c[0].y + c[2].y) / 2.0]);
+ LassoAction::Transform(MarkTransform { pivot, ..t })
+ }
+ other => other,
+ }
+ }
+
+ fn picked_ops(&self, action: LassoAction) -> Option<(Vec<Op>, Option<Picked>)> {
+ let picked = self.picked.clone()?;
+ let action = self.across(action);
+ let Some(polygon) = picked.cut.clone() else {
+ return Some(match action {
+ LassoAction::Transform(transform) => (
+ vec![Op::Transform {
+ ids: picked.addresses(),
+ transform,
+ }],
+ Some(picked),
+ ),
+ LassoAction::Remove => (
+ vec![Op::Remove {
+ ids: picked.addresses(),
+ }],
+ None,
+ ),
+ });
+ };
+ let view = self.cut_view.as_ref().filter(|v| v.key == picked.key())?;
+ let layer = self.scene.active_id()?;
+ let frame = self.scene.frame;
+ let views: Vec<(String, &str, &[u32], &[u32])> =
+ std::iter::once((layer, picked.cel.as_str(), &view.lassoed[..], &view.chosen[..]))
+ .chain(
+ view.more
+ .iter()
+ .map(|v| (v.layer.clone(), v.cel.as_str(), &v.lassoed[..], &v.chosen[..])),
+ )
+ .collect();
+ let lassos: Vec<Op> = views
+ .iter()
+ .filter(|(_, _, lassoed, _)| !lassoed.is_empty())
+ .map(|(layer, ..)| {
+ Op::Lasso(LassoSpec {
+ layer: layer.clone(),
+ frame,
+ polygon: polygon.clone(),
+ cut: true,
+ action: action.clone(),
+ })
+ })
+ .collect();
+ let extras: Vec<String> = views
+ .iter()
+ .flat_map(|(_, cel, lassoed, chosen)| {
+ chosen
+ .iter()
+ .filter(|id| !lassoed.contains(id))
+ .map(|id| address(cel, *id))
+ })
+ .collect();
+ let rest = (!extras.is_empty()).then_some(match &action {
+ LassoAction::Transform(transform) => Op::Transform {
+ ids: extras,
+ transform: *transform,
+ },
+ LassoAction::Remove => Op::Remove { ids: extras },
+ });
+ let after = match action {
+ LassoAction::Remove => None,
+ LassoAction::Transform(_) => Some(Picked {
+ cel: picked.cel.clone(),
+ ids: view.chosen.clone(),
+ cut: None,
+ more: view
+ .more
+ .iter()
+ .map(|v| Part {
+ layer: v.layer.clone(),
+ cel: v.cel.clone(),
+ ids: v.chosen.clone(),
+ })
+ .collect(),
+ }),
+ };
+ Some((lassos.into_iter().chain(rest).collect(), after))
+ }
+
+ fn edit_picked(&mut self, action: LassoAction) -> Result<()> {
+ let Some((ops, after)) = self.picked_ops(action) else {
+ return Ok(());
+ };
+ self.apply(ops)?;
+ self.picked = after;
+ self.forget_missing_selection();
+ Ok(())
+ }
+
+ fn on_marks(&self) -> bool {
+ match self.tool {
+ Tool::Strokes => true,
+ Tool::Select => self.selection.is_none() && self.picked.is_some(),
+ _ => false,
+ }
+ }
+
+ fn handles(&self) -> Option<(String, [Vec2; 4])> {
+ match self.tool {
+ Tool::Direct => None,
+ _ if self.on_marks() => self.picked_corners(),
+ _ => self.selection_corners(),
+ }
+ }
+
+ fn lift_key(&self) -> Option<String> {
+ match self.tool {
+ Tool::Direct => None,
+ _ if self.on_marks() => self.picked.as_ref().map(Picked::key),
+ _ => self.selection.clone(),
+ }
+ }
+
+ fn lift_job(&self, key: String, rev: u64) -> Option<lift::Job> {
+ let canvas = self.scene.size();
+ let scale = self.zoom_px.clamp(0.25, 1.0);
+ if self.on_marks() {
+ let picked = self.picked.as_ref().filter(|p| p.more.is_empty())?;
+ let (replay, raster) = self.scene.active_replay()?;
+ let (marks, ids) = match &picked.cut {
+ Some(_) => {
+ let view = self.cut_view.as_ref().filter(|v| v.key == key)?;
+ (Some(view.marks.clone()), view.chosen.clone())
+ }
+ None => (None, picked.ids.clone()),
+ };
+ let order = marks.as_deref().unwrap_or(replay.marks());
+ let first = order.iter().position(|m| ids.contains(&m.id()))?;
+ if order[first..].iter().any(Mark::locked) {
+ return None;
+ }
+ return Some(lift::Job {
+ key,
+ rev,
+ cel: picked.cel.clone(),
+ layer: self.scene.active.clone(),
+ source: lift::Source::Marks {
+ ids,
+ marks,
+ replay: Box::new(replay.clone()),
+ raster: raster.clone(),
+ brushes: Box::new(self.brushes.clone()),
+ },
+ canvas,
+ scale,
+ });
+ }
+ let (layer, cel, index, nodes) = self.scene.node_slot(&key)?;
+ Some(lift::Job {
+ key,
+ rev,
+ cel,
+ layer,
+ source: lift::Source::Node { index, nodes },
+ canvas,
+ scale,
+ })
+ }
+
+ fn drop_lift(&mut self) {
+ self.lift = None;
+ }
+
+ fn tend_lift(&mut self) -> Result<()> {
+ let rev = self.scene.bundle.doc.rev;
+ let busy = self.drag.is_some() || self.lift.as_ref().is_some_and(|l| l.commit.is_some());
+ let key = self.lift_key();
+ let stale = self
+ .lift
+ .as_ref()
+ .is_some_and(|l| Some(&l.key) != key.as_ref() || l.rev != rev);
+ if stale && !busy {
+ self.drop_lift();
+ }
+ if self.lift.is_none()
+ && !busy
+ && let Some(key) = key.clone()
+ && let Some(job) = self.lift_job(key.clone(), rev)
+ {
+ self.lift_since = Instant::now();
+ self.lift = Some(LiftState {
+ key,
+ rev,
+ job: Some(lift::prepare(job, self.ctx.clone())),
+ ready: None,
+ stage: 0,
+ commit: None,
+ });
+ }
+ let prepared = self
+ .lift
+ .as_mut()
+ .and_then(|l| l.job.as_ref().and_then(|rx| rx.try_recv().ok()));
+ if let Some(result) = prepared {
+ match result {
+ Ok(p) if p.rev == rev && Some(&p.key) == key.as_ref() => {
+ let planes = self.scene.lift_planes(&p.layer, &p.lower, &p.upper)?;
+ if let Some(l) = self.lift.as_mut() {
+ l.job = None;
+ l.ready = planes.map(|planes| (p, planes));
+ }
+ }
+ Ok(_) => self.lift = None,
+ Err(e) => {
+ self.error(format!("preparing the selection: {e:#}"));
+ if let Some(l) = self.lift.as_mut() {
+ l.job = None;
+ }
+ }
+ }
+ }
+ let finished = self
+ .lift
+ .as_mut()
+ .and_then(|l| l.commit.as_ref().and_then(|c| c.job.try_recv().ok()));
+ if let Some(result) = finished {
+ let Some(mut state) = self.lift.take() else {
+ return Ok(());
+ };
+ let commit = state.commit.take().ok_or_else(|| anyhow!("commit vanished"))?;
+ let start = Instant::now();
+ match (result, state.ready.as_ref()) {
+ (Ok((hash, raster)), Some((p, _))) => {
+ self.scene
+ .apply_rendered(&commit.ops, (p.cel.clone(), hash, raster), &self.brushes)?;
+ }
+ _ => {
+ self.scene.apply(&commit.ops, &self.brushes)?;
+ }
+ }
+ self.measure("transform", format!("transform written in {:.0} ms", ms(start)));
+ self.dirty.extend(self.scene.all_tiles());
+ self.forget_missing_selection();
+ }
+ Ok(())
+ }
+
+ fn screen(&self, view: View, rect: Rect, c: Vec2) -> Pos2 {
+ rect.min + view.to_screen(c, rect.size())
+ }
+
+ fn edges(&self) -> bool {
+ match self.tool {
+ _ if self.on_marks() => true,
+ Tool::Select => self
+ .selection
+ .as_ref()
+ .and_then(|id| match self.scene.bundle.doc.item(id) {
+ Some(Item::Node(_, _, node)) => Some(lift::square(node)),
+ _ => None,
+ })
+ .unwrap_or(false),
+ _ => false,
+ }
+ }
+
+ fn grab_at(&self, view: View, rect: Rect, pos: Pos2) -> Option<(String, Grab, [Vec2; 4])> {
+ let (id, corners) = self.handles()?;
+ let screen = corners.map(|c| self.screen(view, rect, c));
+ grab(screen, pos, self.edges()).map(|g| (id, g, corners))
+ }
+
+ fn start_drag(&mut self, id: String, grab: Grab, corners: [Vec2; 4], at: Vec2, fresh: bool) {
+ let strokes = self.on_marks();
+ if !strokes && !matches!(self.scene.bundle.doc.item(&id), Some(Item::Node(..))) {
+ return;
+ }
+ let center = corners.iter().fold(Vec2::ZERO, |a, c| a + *c) / 4.0;
+ self.drag = Some(Drag {
+ grab,
+ node: id,
+ strokes,
+ fresh,
+ copy: grab == Grab::Move && self.modifiers.alt,
+ start: at,
+ now: at,
+ center,
+ corners,
+ });
+ }
+
+ fn select_at(&mut self, at: Vec2, cycle: bool) -> Result<()> {
+ let hits = overlay::hits(&self.scene.bundle.doc, self.scene.frame, (at.x, at.y))?;
+ let current = self
+ .selection
+ .as_ref()
+ .and_then(|id| hits.iter().position(|(n, _)| n == id));
+ let next = match (current, cycle) {
+ (Some(i), true) => hits.get((i + 1) % hits.len().max(1)),
+ _ => hits.first(),
+ };
+ self.selection = next.map(|(n, _)| n.clone());
+ self.refresh_box();
+ Ok(())
+ }
+
+ fn finish_drag(&mut self) -> Result<()> {
+ let Some(drag) = self.drag.take() else {
+ return Ok(());
+ };
+ if drag.strokes {
+ return self.finish_stroke_drag(&drag);
+ }
+ if !drag.moved() {
+ if drag.grab == Grab::Move && !drag.fresh {
+ self.select_at(drag.start, true)?;
+ }
+ return Ok(());
+ }
+ let affine = drag.affine();
+ let node = match self.scene.bundle.doc.item(&drag.node) {
+ Some(Item::Node(_, _, node)) => node.clone(),
+ _ => return Ok(()),
+ };
+ let t = match drag.stretch() {
+ Some((axis, _, k)) => lift::stretched(&node, affine, axis, k)?,
+ None => lift::committed(&node, affine, drag.scale(), drag.angle().to_degrees())?,
+ };
+ let props: Map<String, Value> = [
+ ("transform.x", json!(t.x)),
+ ("transform.y", json!(t.y)),
+ ("transform.rotate", json!(t.rotate)),
+ ("transform.sx", json!(t.sx)),
+ ("transform.sy", json!(t.sy)),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v))
+ .collect();
+ let ops = vec![Op::Set {
+ id: drag.node.clone(),
+ props,
+ }];
+ let canvas = self.scene.size();
+ let staged = |l: &LiftState| l.ready.as_ref().is_some_and(|(_, p)| l.stage >= p.runs.len() + 2);
+ match self.lift.as_mut().filter(|l| staged(l) && l.key == drag.node) {
+ Some(state) => {
+ let (p, _) = state
+ .ready
+ .as_ref()
+ .ok_or_else(|| anyhow!("lift without preparation"))?;
+ let job = lift::finish(p.nodes.clone(), p.index, t, canvas, self.ctx.clone());
+ state.commit = Some(Commit { job, ops, affine });
+ Ok(())
+ }
+ None => self.apply(ops),
+ }
+ }
+
+ fn grab_under(&mut self, c: Vec2, pos: Pos2) -> Result<()> {
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ let slack = 5.0 / zoom;
+ let on_picked = self.picked.as_ref().is_some_and(|p| !p.more.is_empty())
+ && self
+ .picked_parts()
+ .iter()
+ .any(|(_, _, marks, ids)| markedit::hit(marks, (c.x, c.y), slack).is_some_and(|id| ids.contains(&id)));
+ if on_picked && let Some((key, corners)) = self.picked_corners() {
+ self.selection = None;
+ self.start_drag(key, Grab::Move, corners, c, true);
+ return Ok(());
+ }
+ let on_active = self
+ .scene
+ .active_cel()
+ .filter(|_| markedit::hit(self.scene.active_marks(), (c.x, c.y), slack).is_some());
+ if on_active.is_none() {
+ self.select_at(c, false)?;
+ if let Some((id, corners)) = self.selection_corners() {
+ self.picked = None;
+ self.start_drag(id, Grab::Move, corners, c, true);
+ return Ok(());
+ }
+ }
+ self.selection = None;
+ let Some((path, id)) = self.scene.marks_at((c.x, c.y), slack) else {
+ self.lasso = Some(Lasso {
+ points: vec![c],
+ start: pos,
+ far: false,
+ });
+ return Ok(());
+ };
+ if path != self.scene.active {
+ self.activate(path)?;
+ let name = self.scene.active_layer().map(|l| l.name.clone()).unwrap_or_default();
+ self.say(Tone::Info, format!("on layer {name}"));
+ if !self.ensure_canvas()? {
+ self.say(Tone::Info, format!("{name} is still loading; press again in a moment"));
+ return Ok(());
+ }
+ }
+ let Some(cel) = self.scene.active_cel() else {
+ return Ok(());
+ };
+ let held: Vec<u32> = self
+ .picked
+ .as_ref()
+ .filter(|p| p.cel == cel && p.cut.is_none())
+ .map_or(Vec::new(), |p| p.ids.clone());
+ let ids = match (self.modifiers.shift, held.contains(&id)) {
+ (true, true) => held.into_iter().filter(|x| *x != id).collect(),
+ (true, false) => held.into_iter().chain([id]).collect(),
+ (false, true) => held,
+ (false, false) => vec![id],
+ };
+ self.picked = (!ids.is_empty()).then(|| Picked::whole(cel, ids));
+ if let Some((key, corners)) = self.picked_corners() {
+ self.start_drag(key, Grab::Move, corners, c, true);
+ }
+ Ok(())
+ }
+
+ fn copy_for_drag(&mut self) -> Result<()> {
+ let Some(drag) = self.drag.as_mut().filter(|d| d.copy && d.moved()) else {
+ return Ok(());
+ };
+ drag.copy = false;
+ let strokes = drag.strokes;
+ self.drop_lift();
+ self.duplicate_in_place()?;
+ if !strokes && let (Some(drag), Some(id)) = (self.drag.as_mut(), self.selection.clone()) {
+ drag.node = id;
+ }
+ Ok(())
+ }
+
+ fn finish_stroke_drag(&mut self, drag: &Drag) -> Result<()> {
+ let Some(picked) = self.picked.clone() else {
+ return Ok(());
+ };
+ if !drag.moved() && drag.fresh {
+ return Ok(());
+ }
+ if !drag.moved() {
+ self.lasso = Some(Lasso {
+ points: vec![drag.start],
+ start: Pos2::ZERO,
+ far: false,
+ });
+ return self.finish_pick();
+ }
+ let start = Instant::now();
+ self.edit_picked(LassoAction::Transform(drag.mark_transform()))?;
+ let text = format!(
+ "{} strokes and fills {} and redrawn in {:.0} ms",
+ self.picked.as_ref().map_or(0, Picked::count),
+ if picked.cut.is_some() { "cut, moved" } else { "moved" },
+ ms(start)
+ );
+ self.measure("strokes", text);
+ Ok(())
+ }
+
+ fn also_cels(&self) -> Vec<(String, String)> {
+ let doc = &self.scene.bundle.doc;
+ self.also
+ .iter()
+ .filter_map(|id| doc.layer(id))
+ .filter(|l| l.kind() == Kind::Paint && l.visible && !l.locked)
+ .filter_map(|l| l.content_at(self.scene.frame).map(|c| (l.id.clone(), c.id.clone())))
+ .collect()
+ }
+
+ fn finish_pick(&mut self) -> Result<()> {
+ let Some(lasso) = self.lasso.take() else {
+ return Ok(());
+ };
+ let Some(cel) = self.scene.active_cel() else {
+ self.say(Tone::Refused, "make a paint layer active to select its strokes");
+ return Ok(());
+ };
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ let at = lasso.points[0];
+ let polygon: Option<Vec<[f32; 2]>> =
+ (lasso.far && lasso.points.len() >= 3).then(|| lasso.points.iter().map(|p| [p.x, p.y]).collect());
+ let pick = |marks: &[Mark]| -> (Vec<u32>, bool) {
+ match &polygon {
+ Some(polygon) => {
+ let sides = markedit::sides(marks, polygon);
+ let crossing = sides.iter().any(|(_, side)| *side == markedit::Side::Crossing);
+ let inside = sides
+ .into_iter()
+ .filter(|(_, side)| *side == markedit::Side::Inside)
+ .map(|(id, _)| id)
+ .collect();
+ (inside, crossing)
+ }
+ None => (
+ markedit::hit(marks, (at.x, at.y), 5.0 / zoom).into_iter().collect(),
+ false,
+ ),
+ }
+ };
+ let (found, crossing) = pick(self.scene.active_marks());
+ let others: Vec<(String, String, Vec<u32>, bool)> = self
+ .also_cels()
+ .into_iter()
+ .map(|(layer, cel)| {
+ let (ids, crossing) = pick(self.scene.marks_of(&cel));
+ (layer, cel, ids, crossing)
+ })
+ .collect();
+ let adding = self.modifiers.shift;
+ let previous = self.picked.clone().filter(|p| adding && p.cel == cel);
+ let crossed = crossing || others.iter().any(|o| o.3);
+ let cut = polygon
+ .clone()
+ .filter(|_| self.cut_lasso && crossed)
+ .or_else(|| previous.as_ref().and_then(|p| p.cut.clone()));
+ let merge = |held: Vec<u32>, found: &[u32]| {
+ found.iter().fold(held, |mut ids, id| {
+ if adding && !lasso.far && ids.contains(id) {
+ ids.retain(|x| x != id);
+ } else if !ids.contains(id) {
+ ids.push(*id);
+ }
+ ids
+ })
+ };
+ let ids = merge(previous.as_ref().map_or(Vec::new(), |p| p.ids.clone()), &found);
+ let more: Vec<Part> = others
+ .into_iter()
+ .filter_map(|(layer, cel, found, crossing)| {
+ let held = previous
+ .as_ref()
+ .and_then(|p| p.more.iter().find(|q| q.cel == cel))
+ .map_or(Vec::new(), |q| q.ids.clone());
+ let ids = merge(held, &found);
+ (!ids.is_empty() || (cut.is_some() && crossing)).then_some(Part { layer, cel, ids })
+ })
+ .collect();
+ self.picked = (!ids.is_empty() || cut.is_some() || !more.is_empty()).then_some(Picked { cel, ids, cut, more });
+ Ok(())
+ }
+
+ fn refresh_shape(&mut self) {
+ let rev = self.scene.bundle.doc.rev;
+ let Some(id) = self.direct.as_ref().map(|d| d.node.clone()) else {
+ self.shaped = None;
+ return;
+ };
+ if self.shaped.as_ref().is_some_and(|s| s.node == id && s.rev == rev) {
+ return;
+ }
+ if let Some(subs) = self.stroke_path(&id) {
+ self.shaped = Some(Shaped {
+ node: id,
+ rev,
+ subs,
+ matrix: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
+ });
+ return;
+ }
+ let doc = &self.scene.bundle.doc;
+ self.shaped = match doc.item(&id) {
+ Some(Item::Node(_, _, node)) => pathedit::from_shape(&node.shape)
+ .ok()
+ .zip(overlay::local_to_canvas(doc, &id).ok().flatten())
+ .map(|(subs, matrix)| Shaped {
+ node: id,
+ rev,
+ subs,
+ matrix,
+ }),
+ _ => None,
+ };
+ }
+
+ fn point_edit(&self, drag: &PointDrag) -> Option<PathEdit> {
+ let shaped = self.shaped.as_ref()?;
+ let direct = self.direct.as_ref()?;
+ let (a, b) = (to_local(shaped.matrix, drag.start), to_local(shaped.matrix, drag.now));
+ match drag.grab {
+ PointGrab::Anchors => Some(PathEdit::Move {
+ points: direct.points.iter().copied().collect(),
+ by: [b[0] - a[0], b[1] - a[1]],
+ }),
+ PointGrab::Handle(point, side) => Some(PathEdit::Handle {
+ point,
+ side,
+ to: b,
+ free: drag.free,
+ }),
+ PointGrab::Marquee { .. } => None,
+ }
+ }
+
+ fn shown_subs(&self) -> Option<Vec<Subpath>> {
+ if let Some(commit) = self.path_commit.as_ref() {
+ return Some(commit.preview.clone());
+ }
+ let mut subs = self.shaped.as_ref()?.subs.clone();
+ if let Some(edit) = self.point_drag.as_ref().and_then(|d| self.point_edit(d)) {
+ let _ = edit.apply(&mut subs);
+ }
+ Some(subs)
+ }
+
+ fn direct_down(&mut self, view: View, rect: Rect, pos: Pos2, c: Vec2) -> Result<()> {
+ let (alt, shift) = (self.modifiers.alt, self.modifiers.shift);
+ enum Action {
+ Handle(usize, Side),
+ Anchor(usize, bool),
+ Insert(usize, f32),
+ Elsewhere,
+ }
+ let action = match self.shaped.as_ref() {
+ Some(shaped) => {
+ let m = shaped.matrix;
+ let screen = |p: [f32; 2]| self.screen(view, rect, to_canvas(m, p));
+ let anchors = pathedit::anchors(&shaped.subs);
+ let selected: Vec<usize> = self
+ .direct
+ .as_ref()
+ .map_or(Vec::new(), |d| d.points.iter().copied().collect());
+ let handle = selected.iter().find_map(|&i| {
+ let a = anchors.get(i)?.1;
+ [(Side::In, a.inn, a.has_in()), (Side::Out, a.out, a.has_out())]
+ .into_iter()
+ .find(|(_, p, has)| *has && screen(*p).distance(pos) <= HANDLE)
+ .map(|(side, _, _)| (i, side))
+ });
+ let anchor = anchors.iter().position(|(_, a)| screen(a.at).distance(pos) <= HANDLE);
+ let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * view.zoom;
+ let near = pathedit::nearest(&shaped.subs, to_local(m, c)).filter(|(_, _, d)| d * scale <= 8.0);
+ match (handle, anchor, near) {
+ (Some((i, side)), _, _) => Action::Handle(i, side),
+ (None, Some(i), _) => Action::Anchor(i, anchors[i].1.has_in() || anchors[i].1.has_out()),
+ (None, None, Some((segment, t, _))) if alt => Action::Insert(segment, t),
+ _ => Action::Elsewhere,
+ }
+ }
+ None => Action::Elsewhere,
+ };
+ match action {
+ Action::Handle(i, side) => {
+ self.point_drag = Some(PointDrag {
+ grab: PointGrab::Handle(i, side),
+ start: c,
+ now: c,
+ free: alt,
+ });
+ }
+ Action::Anchor(i, curved) if alt => {
+ let points = vec![i];
+ return self.commit_path(if curved {
+ PathEdit::Corner { points }
+ } else {
+ PathEdit::Smooth { points }
+ });
+ }
+ Action::Anchor(i, _) => {
+ if let Some(d) = self.direct.as_mut() {
+ if shift {
+ if !d.points.remove(&i) {
+ d.points.insert(i);
+ }
+ } else if !d.points.contains(&i) {
+ d.points = BTreeSet::from([i]);
+ }
+ if d.points.contains(&i) {
+ self.point_drag = Some(PointDrag {
+ grab: PointGrab::Anchors,
+ start: c,
+ now: c,
+ free: false,
+ });
+ }
+ }
+ }
+ Action::Insert(segment, t) => return self.commit_path(PathEdit::Insert { segment, t }),
+ Action::Elsewhere => {
+ self.under = overlay::leaf_hits(&self.scene.bundle.doc, self.scene.frame, (c.x, c.y))?;
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ let mut on_stroke = false;
+ if self.under.is_empty()
+ && let Some((path, mark)) = self.scene.marks_at((c.x, c.y), 5.0 / zoom)
+ {
+ if path != self.scene.active {
+ self.activate(path)?;
+ }
+ let picked = self
+ .scene
+ .active_marks()
+ .iter()
+ .find(|m| m.id() == mark)
+ .map(|m| m.as_stroke().is_some());
+ match (picked, self.scene.active_cel()) {
+ (Some(true), Some(cel)) => {
+ let address = markedit::address(&cel, mark);
+ if self.direct.as_ref().map(|d| &d.node) != Some(&address) {
+ self.pick_shape(address);
+ return Ok(());
+ }
+ on_stroke = true;
+ }
+ (Some(false), _) => {
+ self.say(Tone::Info, "that is a fill: A reshapes strokes and vector shapes")
+ }
+ _ => {}
+ }
+ }
+ let current = self.direct.as_ref().map(|d| d.node.clone());
+ let hit = match &current {
+ Some(id) if self.under.contains(id) => Some(id.clone()),
+ _ => self.under.first().cloned(),
+ };
+ match hit {
+ Some(id) if Some(&id) != current.as_ref() => self.pick_shape(id),
+ hit => {
+ self.point_drag = Some(PointDrag {
+ grab: PointGrab::Marquee {
+ on_shape: hit.is_some() || on_stroke,
+ },
+ start: c,
+ now: c,
+ free: false,
+ });
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn pen_down(&mut self, view: View, rect: Rect, pos: Pos2, c: Vec2) -> Result<()> {
+ let vector = self
+ .scene
+ .active_layer()
+ .is_some_and(|l| l.kind() == Kind::Vector && !l.locked);
+ if !vector {
+ self.say(
+ Tone::Refused,
+ "the pen draws vector paths: pick a vector layer, or add one with \"vector\" in Layers",
+ );
+ return Ok(());
+ }
+ let first = self
+ .pen_path
+ .as_ref()
+ .filter(|p| p.anchors.len() >= 2)
+ .and_then(|p| p.anchors.first())
+ .map(|a| self.screen(view, rect, vec2(a.at[0], a.at[1])));
+ if first.is_some_and(|f| f.distance(pos) <= HANDLE + 2.0) {
+ return self.commit_pen(true);
+ }
+ let path = self.pen_path.get_or_insert_with(|| PenPath {
+ anchors: Vec::new(),
+ dragging: false,
+ });
+ path.anchors.push(pathedit::Anchor::corner([c.x, c.y]));
+ path.dragging = true;
+ Ok(())
+ }
+
+ fn pen_move(&mut self, c: Vec2) {
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ let Some(last) = self
+ .pen_path
+ .as_mut()
+ .filter(|p| p.dragging)
+ .and_then(|p| p.anchors.last_mut())
+ else {
+ return;
+ };
+ let pull = [c.x - last.at[0], c.y - last.at[1]];
+ let (out, inn) = match pull[0].hypot(pull[1]) * zoom > 3.0 {
+ true => ([c.x, c.y], [last.at[0] - pull[0], last.at[1] - pull[1]]),
+ false => (last.at, last.at),
+ };
+ last.out = out;
+ last.inn = inn;
+ }
+
+ fn pen_keys(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ if self.pen_path.is_none() {
+ return Ok(());
+ }
+ if self.tool != Tool::Pen {
+ return self.commit_pen(false);
+ }
+ let (finish, cancel) = ui.input_mut(|i| {
+ (
+ i.consume_key(egui::Modifiers::NONE, Key::Enter),
+ i.consume_key(egui::Modifiers::NONE, Key::Escape),
+ )
+ });
+ if cancel {
+ self.pen_path = None;
+ self.say(Tone::Info, "path dropped");
+ }
+ if finish {
+ self.commit_pen(false)?;
+ }
+ Ok(())
+ }
+
+ fn commit_pen(&mut self, closed: bool) -> Result<()> {
+ let Some(path) = self.pen_path.take() else {
+ return Ok(());
+ };
+ if path.anchors.len() < 2 {
+ self.say(Tone::Info, "a path needs two points: click again before Return");
+ return Ok(());
+ }
+ let Some((layer, name)) = self
+ .scene
+ .active_layer()
+ .filter(|l| l.kind() == Kind::Vector)
+ .map(|l| (l.id.clone(), l.name.clone()))
+ else {
+ return Ok(());
+ };
+ let d = pathedit::to_d(&[Subpath {
+ anchors: path.anchors,
+ closed,
+ }]);
+ let (colour, outline) = (color::hex(self.color), color::hex(self.second));
+ let fill = (closed && self.pen_fill).then(|| colour.clone());
+ let mut node = json!({ "type": "path", "d": d });
+ if let Some(fill) = &fill {
+ node["fill"] = json!(fill);
+ }
+ if self.pen_stroke || fill.is_none() {
+ node["stroke"] = json!({ "paint": outline, "width": self.pen_width, "cap": "round", "join": "round" });
+ }
+ let op = Op::AddNode {
+ node,
+ place: klad_core::ops::Place {
+ into: Some(layer),
+ frame: Some(self.scene.frame),
+ ..Default::default()
+ },
+ };
+ self.apply(vec![op])?;
+ self.used_colour();
+ self.say(
+ Tone::Done,
+ format!(
+ "{} path added to {name}: V moves it, A edits its points",
+ if closed { "closed" } else { "open" }
+ ),
+ );
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn decorate_pen(
+ &self,
+ painter: &egui::Painter,
+ path: &PenPath,
+ hover: Option<Pos2>,
+ view: View,
+ rect: Rect,
+ accent: Color32,
+ dark: egui::Stroke,
+ ) {
+ let to_screen = |p: [f32; 2]| self.screen(view, rect, vec2(p[0], p[1]));
+ let mut anchors = path.anchors.clone();
+ if let Some(hover) = hover.filter(|h| !path.dragging && rect.contains(*h)) {
+ let c = view.to_canvas(hover - rect.min, rect.size());
+ anchors.push(pathedit::Anchor::corner([c.x, c.y]));
+ }
+ let sub = Subpath { anchors, closed: false };
+ pathedit::flatten(&[sub], 2.0 / view.zoom.max(1e-3))
+ .into_iter()
+ .for_each(|line| {
+ let points: Vec<Pos2> = line.into_iter().map(to_screen).collect();
+ painter.add(egui::Shape::line(points.clone(), dark));
+ painter.add(egui::Shape::line(points, egui::Stroke::new(1.5, accent)));
+ });
+ if let Some(last) = path.anchors.last().filter(|a| a.has_out()) {
+ [last.inn, last.out].into_iter().for_each(|h| {
+ painter.line_segment([to_screen(last.at), to_screen(h)], egui::Stroke::new(1.0, accent));
+ painter.circle_filled(to_screen(h), 3.5, accent);
+ });
+ }
+ path.anchors.iter().enumerate().for_each(|(i, a)| {
+ let p = to_screen(a.at);
+ let size = if i == 0 && path.anchors.len() >= 2 {
+ HANDLE + 3.0
+ } else {
+ HANDLE
+ };
+ let square = Rect::from_center_size(p, vec2(size, size));
+ painter.rect_filled(square, 1.0, Color32::WHITE);
+ painter.rect_stroke(square, 1.0, egui::Stroke::new(1.0, accent), egui::StrokeKind::Middle);
+ });
+ }
+
+ fn pick_shape(&mut self, id: String) {
+ self.direct = Some(Direct {
+ node: id,
+ points: BTreeSet::new(),
+ });
+ self.refresh_shape();
+ }
+
+ fn direct_up(&mut self) -> Result<()> {
+ let Some(drag) = self.point_drag.take() else {
+ return Ok(());
+ };
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ let moved = (drag.now - drag.start).length() * zoom > 2.0;
+ match drag.grab {
+ PointGrab::Marquee { on_shape } => {
+ if !moved {
+ let current = self.direct.as_ref().map(|d| d.node.clone());
+ let below = current
+ .and_then(|id| self.under.iter().position(|u| *u == id))
+ .filter(|_| self.under.len() > 1)
+ .map(|i| self.under[(i + 1) % self.under.len()].clone());
+ match (on_shape, below) {
+ (true, Some(id)) => self.pick_shape(id),
+ (true, None) => {
+ if let Some(d) = self.direct.as_mut() {
+ d.points.clear();
+ }
+ }
+ (false, _) => self.direct = None,
+ }
+ return Ok(());
+ }
+ let Some(shaped) = self.shaped.as_ref() else {
+ return Ok(());
+ };
+ let (lo, hi) = (drag.start.min(drag.now), drag.start.max(drag.now));
+ let inside: Vec<usize> = pathedit::anchors(&shaped.subs)
+ .iter()
+ .enumerate()
+ .filter(|(_, (_, a))| {
+ let p = to_canvas(shaped.matrix, a.at);
+ p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y
+ })
+ .map(|(i, _)| i)
+ .collect();
+ let adding = self.modifiers.shift;
+ if let Some(d) = self.direct.as_mut() {
+ if !adding {
+ d.points.clear();
+ }
+ d.points.extend(inside);
+ }
+ Ok(())
+ }
+ _ if !moved => Ok(()),
+ _ => match self.point_edit(&drag) {
+ Some(edit) => self.commit_path(edit),
+ None => Ok(()),
+ },
+ }
+ }
+
+ fn stroke_path(&self, id: &str) -> Option<Vec<Subpath>> {
+ let (cel, mark) = markedit::parse_address(id)?;
+ if self.scene.active_cel().as_deref() != Some(cel) {
+ return None;
+ }
+ let stroke = self
+ .scene
+ .active_marks()
+ .iter()
+ .find(|m| m.id() == mark)
+ .and_then(|m| m.as_stroke())?;
+ let points: Vec<[f32; 2]> = stroke
+ .samples
+ .iter()
+ .map(|s| {
+ let (x, y) = s.pos();
+ [x, y]
+ })
+ .collect();
+ Some(vec![pathedit::fit_polyline(
+ &points,
+ (stroke.size * 0.12).clamp(1.0, 6.0),
+ )])
+ }
+
+ fn reshape_stroke(&mut self, id: String, edit: PathEdit) -> Result<()> {
+ let Some(shaped) = self.shaped.as_ref().filter(|s| s.node == id) else {
+ return Ok(());
+ };
+ let mut subs = shaped.subs.clone();
+ if let Err(e) = edit.apply(&mut subs) {
+ self.say(Tone::Refused, format!("{e:#}"));
+ return Ok(());
+ }
+ let points = |subs: &[Subpath]| subs.iter().map(|s| s.anchors.len()).sum::<usize>();
+ if points(&subs) != points(&shaped.subs)
+ && let Some(d) = self.direct.as_mut()
+ {
+ d.points.clear();
+ }
+ let props: Map<String, Value> = [("path".to_string(), json!(pathedit::to_d(&subs)))]
+ .into_iter()
+ .collect();
+ self.apply(vec![Op::Set { id: id.clone(), props }])?;
+ self.shaped = Some(Shaped {
+ node: id,
+ rev: self.scene.bundle.doc.rev,
+ subs,
+ matrix: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
+ });
+ Ok(())
+ }
+
+ fn commit_path(&mut self, edit: PathEdit) -> Result<()> {
+ let Some(id) = self.direct.as_ref().map(|d| d.node.clone()) else {
+ return Ok(());
+ };
+ if self.path_commit.is_some() {
+ return Ok(());
+ }
+ if markedit::parse_address(&id).is_some() {
+ return self.reshape_stroke(id, edit);
+ }
+ let doc = &self.scene.bundle.doc;
+ let Some(Loc::Node(path, c, _)) = doc.locate(&id) else {
+ return Ok(());
+ };
+ let layer = doc.layer_at(&path);
+ if layer.locked {
+ self.say(Tone::Refused, format!("layer {} is locked", layer.name));
+ return Ok(());
+ }
+ let cel = layer.cels()[c].id.clone();
+ let ops = vector::pinned(doc, &[Op::Path { id: id.clone(), edit }])?;
+ let (next, _) = apply_all(doc, &ops)?;
+ let nodes = match next.locate(&cel) {
+ Some(Loc::Cel(p, c)) => next.layer_at(&p).cels()[c].nodes.clone(),
+ _ => Vec::new(),
+ };
+ let preview = match next.item(&id) {
+ Some(Item::Node(_, _, n)) => pathedit::from_shape(&n.shape).unwrap_or_default(),
+ _ => Vec::new(),
+ };
+ let count = |subs: &[Subpath]| subs.iter().map(|s| s.anchors.len()).sum::<usize>();
+ if Some(count(&preview)) != self.shaped.as_ref().map(|s| count(&s.subs))
+ && let Some(d) = self.direct.as_mut()
+ {
+ d.points.clear();
+ }
+ let job = lift::render(nodes, self.scene.size(), self.ctx.clone());
+ self.path_commit = Some(PathCommit {
+ job,
+ ops,
+ cel,
+ preview,
+ node: id,
+ });
+ Ok(())
+ }
+
+ fn tend_path(&mut self) -> Result<()> {
+ let Some(result) = self.path_commit.as_ref().and_then(|p| p.job.try_recv().ok()) else {
+ return Ok(());
+ };
+ let Some(commit) = self.path_commit.take() else {
+ return Ok(());
+ };
+ let start = Instant::now();
+ let dirty = match result {
+ Ok((hash, raster)) => self
+ .scene
+ .apply_rendered(&commit.ops, (commit.cel, hash, raster), &self.brushes)?,
+ Err(e) => {
+ self.error(format!("drawing the edited path: {e:#}"));
+ self.scene.apply(&commit.ops, &self.brushes)?
+ }
+ };
+ self.dirty.extend(dirty);
+ self.measure(
+ "point edit",
+ format!("point edit on {} written in {:.0} ms", commit.node, ms(start)),
+ );
+ self.forget_missing_selection();
+ Ok(())
+ }
+
+ fn on_pen(&mut self, ctx: &egui::Context, e: PenEvent, rect: Rect, was_focused: bool) -> Result<()> {
+ self.readout.pressure = e.pressure;
+ self.readout.tilt = e.tilt;
+ self.readout.eraser = e.eraser;
+ self.readout.tablet = e.tablet;
+ if e.tablet {
+ self.readout.device = e.device;
+ if e.phase != Phase::Up && self.settings.note_peak(&device_key(e.device), e.pressure) {
+ self.settings_dirty = true;
+ }
+ }
+ if e.phase == Phase::Move {
+ self.readout.samples.push_back(e.at);
+ while self
+ .readout
+ .samples
+ .front()
+ .is_some_and(|t| e.at.duration_since(*t) > Duration::from_secs(1))
+ {
+ self.readout.samples.pop_front();
+ }
+ }
+ let Some(view) = self.view else {
+ return Ok(());
+ };
+ let c = view.to_canvas(e.pos - rect.min, rect.size());
+ let on_canvas = rect.contains(e.pos)
+ && ctx
+ .layer_id_at(e.pos)
+ .is_none_or(|l| l.order == egui::Order::Background);
+ let picking = self.modifiers.alt && !self.modifiers.command && matches!(self.tool, Tool::Brush | Tool::Fill);
+ let sizing_now = self.modifiers.alt && self.modifiers.command && self.tool == Tool::Brush;
+ match (e.phase, self.sizing) {
+ (Phase::Down, None) if sizing_now && on_canvas && self.live.is_none() => {
+ self.sizing = Some((e.pos.x, self.size, e.pos));
+ return Ok(());
+ }
+ (Phase::Move, Some((x, start, _))) => {
+ self.size = options::size_from_drag(start, e.pos.x - x);
+ return Ok(());
+ }
+ (Phase::Up, Some(_)) => {
+ self.sizing = None;
+ return Ok(());
+ }
+ _ => {}
+ }
+ let pressing = e.phase == Phase::Down && was_focused && on_canvas && !self.navigating;
+ if pressing && self.holding_frame_keys() {
+ return Ok(());
+ }
+ let needs_canvas = matches!(self.tool, Tool::Brush | Tool::Fill | Tool::Strokes | Tool::Select);
+ if pressing && !needs_canvas {
+ self.hold_still();
+ }
+ if pressing && needs_canvas && !self.ensure_canvas()? {
+ self.say(
+ Tone::Info,
+ format!("frame {} is still loading; draw again in a moment", self.scene.frame),
+ );
+ return Ok(());
+ }
+ match (self.tool, e.phase) {
+ (_, Phase::Down) if !was_focused || !on_canvas || self.navigating => {}
+ (_, Phase::Down) if picking => self.pick_colour(c, self.modifiers.shift)?,
+ (Tool::Fill, Phase::Down) => {
+ if self.scene.can_paint() {
+ self.lasso = Some(Lasso {
+ points: vec![c],
+ start: e.pos,
+ far: false,
+ });
+ }
+ }
+ (Tool::Strokes, Phase::Down) if self.lift.as_ref().is_some_and(|l| l.commit.is_some()) => {}
+ (Tool::Strokes, Phase::Down) => match self.grab_at(view, rect, e.pos) {
+ Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
+ None => {
+ self.lasso = Some(Lasso {
+ points: vec![c],
+ start: e.pos,
+ far: false,
+ });
+ }
+ },
+ (Tool::Strokes, Phase::Up) if self.drag.is_some() => self.finish_drag()?,
+ (Tool::Strokes, Phase::Up) => self.finish_pick()?,
+ (Tool::Strokes, Phase::Move) if self.drag.is_some() => {
+ if let Some(drag) = self.drag.as_mut() {
+ drag.now = c;
+ }
+ self.copy_for_drag()?;
+ }
+ (Tool::Direct, Phase::Down) if self.path_commit.is_some() => {}
+ (Tool::Direct, Phase::Down) => self.direct_down(view, rect, e.pos, c)?,
+ (Tool::Direct, Phase::Move) => {
+ if let Some(drag) = self.point_drag.as_mut() {
+ drag.now = c;
+ drag.free |= self.modifiers.alt;
+ }
+ }
+ (Tool::Direct, Phase::Up) => self.direct_up()?,
+ (Tool::Fill | Tool::Strokes | Tool::Select, Phase::Move) if self.drag.is_none() => {
+ if let Some(lasso) = self.lasso.as_mut() {
+ lasso.far |= (e.pos - lasso.start).length() > 6.0;
+ if lasso.points.last().is_none_or(|p| (*p - c).length() >= 1.0) {
+ lasso.points.push(c);
+ }
+ }
+ }
+ (Tool::Fill, Phase::Up) => self.finish_fill()?,
+ (Tool::Brush, Phase::Down) => {
+ if self.live.is_none() && self.scene.can_paint() {
+ self.begin(&e, c)?;
+ }
+ }
+ (Tool::Brush, Phase::Move) => {
+ if let Some(live) = self.live.as_mut() {
+ let dt = e.at.duration_since(live.last_at).as_secs_f32() * 1000.0;
+ let sample = live.recorder.push(raw_of(&e, c, dt));
+ live.painter
+ .push_on(&sample, &mut self.buffer, self.scene.active_raster());
+ live.stroke.samples.push(sample);
+ if let Some((axis, copy, painter)) = live.twin.as_mut() {
+ let twin = make::mirrored(&sample, *axis);
+ painter.push_on(&twin, &mut self.mirror_buffer, self.scene.active_raster());
+ copy.samples.push(twin);
+ }
+ live.last_at = e.at;
+ self.pending.get_or_insert(e.at);
+ }
+ }
+ (Tool::Brush, Phase::Up) => self.finish()?,
+ (Tool::Select, Phase::Down) if self.lift.as_ref().is_some_and(|l| l.commit.is_some()) => {}
+ (Tool::Select, Phase::Down) => match self.grab_at(view, rect, e.pos) {
+ Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
+ None => self.grab_under(c, e.pos)?,
+ },
+ (Tool::Select, Phase::Move) => {
+ if let Some(drag) = self.drag.as_mut() {
+ drag.now = c;
+ }
+ self.copy_for_drag()?;
+ }
+ (Tool::Select, Phase::Up) if self.lasso.is_some() => match self.scene.active_cel() {
+ Some(_) => self.finish_pick()?,
+ None => {
+ self.lasso = None;
+ self.picked = None;
+ }
+ },
+ (Tool::Select, Phase::Up) => self.finish_drag()?,
+ (Tool::Note, Phase::Down) => self.press_note(c),
+ (Tool::Shape, Phase::Down) => self.shape_down(c),
+ (Tool::Shape, Phase::Move) => self.shape_move(c),
+ (Tool::Shape, Phase::Up) => self.shape_up()?,
+ (Tool::Pen, Phase::Down) => self.pen_down(view, rect, e.pos, c)?,
+ (Tool::Pen, Phase::Move) => self.pen_move(c),
+ (Tool::Pen, Phase::Up) => {
+ if let Some(path) = self.pen_path.as_mut() {
+ path.dragging = false;
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ fn shaped(&self) -> Result<(String, BrushDef)> {
+ let base = self
+ .brushes
+ .def(&self.brush)
+ .ok_or_else(|| anyhow!("no brush {}", self.brush))?;
+ let def = match &self.custom {
+ Some(def) => def.clone(),
+ None => self.tuning.shape(base),
+ };
+ Ok((pick_id(&self.brush, &def, &self.embedded), def))
+ }
+
+ fn pick(&mut self, id: &str) {
+ if let Some(def) = self.brushes.def(id) {
+ self.tuning = Tuning::of(def);
+ self.brush = id.to_string();
+ self.custom = None;
+ self.brush_window.name = def.name.clone();
+ }
+ }
+
+ fn begin(&mut self, e: &PenEvent, c: Vec2) -> Result<()> {
+ let (name, def, tuning) = if e.eraser {
+ let def = self
+ .brushes
+ .def("eraser")
+ .cloned()
+ .ok_or_else(|| anyhow!("no eraser brush"))?;
+ let tuning = Tuning::of(&def);
+ ("eraser".to_string(), def, tuning)
+ } else {
+ let (name, def) = self.shaped()?;
+ let tuning = match &self.custom {
+ Some(custom) => Tuning {
+ taper: custom.taper,
+ stabilizer: custom.stabilizer,
+ smoothing: custom.smoothing,
+ ..self.tuning
+ },
+ None => self.tuning,
+ };
+ (name, def, tuning)
+ };
+ if self.brushes.def(&name) != Some(&def) {
+ self.brushes.insert(&name, def);
+ }
+ let brush = self.brushes.get(&name)?.clone();
+ let lock = self.scene.active_locks_alpha();
+ if lock && stroke_blend(&brush, true).is_none() {
+ self.say(
+ Tone::Refused,
+ "alpha is locked on this layer, so the eraser cannot change it (untick lock alpha)",
+ );
+ return Ok(());
+ }
+ let id = self.scene.next_mark_id();
+ let mut stroke = Stroke::new(id, &name, self.color, self.size, self.rng.next_u64() as u32);
+ stroke.opacity = self.opacity;
+ stroke.flow = self.flow;
+ stroke.taper = tuning.taper;
+ stroke.lock = lock;
+ let curve = if e.tablet {
+ self.settings.curve(&device_key(e.device))
+ } else {
+ PressureCurve::default()
+ };
+ let mut recorder = Recorder::new(curve, tuning.stabilizer, tuning.smoothing);
+ let sample = recorder.push(raw_of(e, c, 0.0));
+ if brush.def.color.is_some_and(|c| c.uses_second()) {
+ stroke.second = Some(klad_core::color::to_u16(self.second));
+ }
+ let mut painter = StrokePainter::live(&brush, &stroke);
+ painter.push_on(&sample, &mut self.buffer, self.scene.active_raster());
+ stroke.samples.push(sample);
+ let twin = self.mirror.map(|axis| {
+ let mut copy = stroke.clone();
+ copy.id = id + 1;
+ copy.seed = stroke.seed.wrapping_add(1);
+ copy.samples = vec![make::mirrored(&sample, axis)];
+ let mut painter = StrokePainter::live(&brush, &copy);
+ painter.push_on(&copy.samples[0], &mut self.mirror_buffer, self.scene.active_raster());
+ (axis, copy, painter)
+ });
+ self.live = Some(Live {
+ stroke,
+ painter,
+ brush,
+ recorder,
+ last_at: e.at,
+ twin,
+ });
+ self.pending.get_or_insert(e.at);
+ Ok(())
+ }
+
+ fn finish(&mut self) -> Result<()> {
+ let Some(mut live) = self.live.take() else {
+ return Ok(());
+ };
+ let start = Instant::now();
+ let tail = live.recorder.finish();
+ tail.iter()
+ .for_each(|s| live.painter.push_on(s, &mut self.buffer, self.scene.active_raster()));
+ if let Some((axis, copy, painter)) = live.twin.as_mut() {
+ tail.iter().map(|s| make::mirrored(s, *axis)).for_each(|s| {
+ painter.push_on(&s, &mut self.mirror_buffer, self.scene.active_raster());
+ copy.samples.push(s);
+ });
+ }
+ live.stroke.samples.extend(tail);
+ let repainted = needs_repaint(&live.stroke);
+ if repainted {
+ self.dirty.extend(self.buffer.touched().iter().copied());
+ self.buffer.reset();
+ klad_brush::draw_stroke_on(&mut self.buffer, &live.brush, &live.stroke, self.scene.active_raster());
+ if let Some((_, copy, _)) = &live.twin {
+ self.dirty.extend(self.mirror_buffer.touched().iter().copied());
+ self.mirror_buffer.reset();
+ klad_brush::draw_stroke_on(&mut self.mirror_buffer, &live.brush, copy, self.scene.active_raster());
+ }
+ }
+ let ended = ms(start);
+ if self.external.is_some() {
+ self.reload()?;
+ }
+ if self.scene.bundle.embed_brush(&live.stroke.brush, &live.brush.def)? {
+ self.embedded.insert(live.stroke.brush.clone(), live.brush.def.clone());
+ }
+ let samples = live.stroke.samples.len();
+ let dabs = live.painter.dabs();
+ let alone = encode_cel(&[Mark::Stroke(live.stroke.clone())])?.len();
+ let brush = live.stroke.brush.clone();
+ let erasing = live.brush.blend == klad_brush::brush::StrokeBlend::Erase;
+ let blend = stroke_blend(&live.brush, live.stroke.lock).unwrap_or(live.brush.blend);
+ let mut touched = self.scene.commit_stroke(live.stroke, &mut self.buffer, blend)?;
+ if let Some((_, mut copy, _)) = live.twin {
+ copy.id = self.scene.next_mark_id();
+ touched.extend(self.scene.commit_stroke(copy, &mut self.mirror_buffer, blend)?);
+ }
+ let commit = ms(start);
+ self.dirty.extend(touched);
+ let saving = Instant::now();
+ let bytes = self.scene.save_active("stroke")?;
+ if !erasing {
+ self.used_colour();
+ }
+ let count = self.scene.active_marks().len();
+ let text = format!(
+ "{brush}: {samples} samples, {dabs} live dabs, {alone} B packed alone\nlayer file {bytes} B for {count} strokes and fills ({:.0} B each)\npen up {ended:.1} ms{}, commit {commit:.1} ms, save {:.1} ms",
+ bytes as f64 / count.max(1) as f64,
+ if repainted { " (tapered repaint)" } else { "" },
+ ms(saving)
+ );
+ self.measure("stroke", text);
+ Ok(())
+ }
+
+ fn set_colour(&mut self, rgba: [f32; 4]) {
+ self.color = rgba;
+ self.hsva = Hsva::from_rgba(rgba, self.hsva.h);
+ }
+
+ fn used_colour(&mut self) {
+ if self.settings.used(&color::hex(self.color)) {
+ self.settings_dirty = true;
+ }
+ }
+
+ fn pick_colour(&mut self, at: Vec2, layer_only: bool) -> Result<()> {
+ let where_from = if layer_only { "this layer" } else { "the image" };
+ match self.scene.sample((at.x, at.y), layer_only)? {
+ Some(rgba) => {
+ self.pick_new_colour(rgba);
+ self.say(Tone::Done, format!("picked {} from {where_from}", color::hex(rgba)));
+ }
+ None => self.say(Tone::Refused, format!("nothing to pick from {where_from} there")),
+ }
+ Ok(())
+ }
+
+ fn fill_reference(&self) -> FillRef {
+ match &self.fill.reference {
+ FillRef::Layer(id) if self.scene.active_id().as_ref() == Some(id) => FillRef::This,
+ FillRef::Layer(id) if self.scene.bundle.doc.layer(id).is_none() => FillRef::This,
+ other => other.clone(),
+ }
+ }
+
+ fn finish_fill(&mut self) -> Result<()> {
+ let Some(lasso) = self.lasso.take() else {
+ return Ok(());
+ };
+ let start = Instant::now();
+ let (w, h) = self.scene.size();
+ let (source, coverage) = if lasso.far && lasso.points.len() >= 3 {
+ let points: Vec<[f32; 2]> = lasso.points.iter().map(|p| [p.x, p.y]).collect();
+ let coverage = polygon(&points, w, h);
+ (FillSource::Polygon(points), coverage)
+ } else {
+ let at = lasso.points[0];
+ let seed = Seed {
+ x: at.x,
+ y: at.y,
+ tolerance: self.fill.tolerance,
+ gap: self.fill.gap,
+ expand: self.fill.expand,
+ };
+ let reference = self.fill_reference();
+ let image = self.scene.fill_reference(&reference, &self.brushes)?;
+ let coverage = flood(&image, &seed);
+ (FillSource::Seed { seed, reference }, coverage)
+ };
+ let computed = ms(start);
+ if coverage.is_empty() {
+ self.say(Tone::Refused, "nothing to fill there");
+ return Ok(());
+ }
+ if self.external.is_some() {
+ self.reload()?;
+ }
+ let pixels = coverage.pixels();
+ let lassoed = matches!(source, FillSource::Polygon(_));
+ let mut fill = Fill::new(self.scene.next_mark_id(), self.color, source, coverage);
+ fill.opacity = self.fill.opacity;
+ fill.lock = self.scene.active_locks_alpha();
+ let committing = Instant::now();
+ let touched = self.scene.commit_fill(fill, &self.brushes)?;
+ self.dirty.extend(touched);
+ let bytes = self.scene.save_active("fill")?;
+ self.used_colour();
+ let text = format!(
+ "{}: {pixels} px computed in {computed:.0} ms, painted and saved in {:.0} ms\nlayer file {bytes} B",
+ if lassoed { "lasso fill" } else { "fill" },
+ ms(committing)
+ );
+ self.measure("fill", text);
+ Ok(())
+ }
+
+ fn navigate(&mut self, ui: &egui::Ui, response: &egui::Response, rect: Rect) {
+ let area = rect.size();
+ let (zoom, scroll, rotation, hover, space, middle, primary, delta, time) = ui.input(|i| {
+ (
+ i.zoom_delta(),
+ i.smooth_scroll_delta,
+ i.rotation_delta(),
+ i.pointer.hover_pos(),
+ i.key_down(Key::Space),
+ i.pointer.middle_down(),
+ i.pointer.primary_down(),
+ i.pointer.delta(),
+ i.time,
+ )
+ });
+ self.navigating = (space && !ui.ctx().egui_wants_keyboard_input()) || middle;
+ let Some(view) = self.view.as_mut() else {
+ return;
+ };
+ let at = hover.filter(|p| rect.contains(*p)).map_or(area / 2.0, |p| p - rect.min);
+ if response.hovered() || response.dragged() {
+ if zoom != 1.0 {
+ view.zoom_at(zoom, at, area);
+ }
+ if scroll != Vec2::ZERO {
+ view.pan(scroll);
+ }
+ if rotation != 0.0 {
+ view.rotate_at(rotation, at, area);
+ }
+ }
+ if self.navigating && (middle || primary) && self.live.is_none() {
+ view.pan(delta);
+ }
+ if self.spin {
+ view.rotate_at(0.01, area / 2.0, area);
+ view.zoom_at(1.0 + 0.012 * (time as f32 * 1.5).sin(), area / 2.0, area);
+ ui.ctx().request_repaint();
+ }
+ }
+
+ fn canvas(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let rect = ui.max_rect();
+ let response = ui.allocate_rect(rect, Sense::click_and_drag());
+ self.canvas_rect = rect;
+ let area = rect.size();
+ let canvas = self.canvas_size();
+ self.view.get_or_insert_with(|| View::fit(canvas, area));
+ self.navigate(ui, &response, rect);
+ self.pen_keys(ui)?;
+ self.command_keys(ui)?;
+ let ctx = ui.ctx().clone();
+ let was_focused = self.focused;
+ self.focused = ctx.input(|i| i.focused);
+ self.modifiers = ctx.input(|i| i.modifiers);
+ self.refresh_shape();
+ let events = match &self.pen {
+ Some(pen) => pen.drain(ctx.content_rect().height()),
+ None => pen::from_egui(&ui.input(|i| i.events.clone())),
+ };
+ let holding = self.writing() && matches!(self.tool, Tool::Select | Tool::Direct);
+ self.held
+ .admit(holding, events)
+ .into_iter()
+ .try_for_each(|e| self.on_pen(&ctx, e, rect, was_focused))?;
+ if self.tool == Tool::Note
+ && response.secondary_clicked()
+ && let (Some(p), Some(view)) = (response.interact_pointer_pos(), self.view)
+ {
+ self.select_pin(view.to_canvas(p - rect.min, rect.size()))?;
+ }
+ let view = self.view.unwrap_or_else(|| View::fit(canvas, area));
+ self.zoom_px = view.zoom * ctx.pixels_per_point();
+ self.refresh_box();
+ self.refresh_cut();
+ self.refresh_shape();
+ self.tend_lift()?;
+ self.tend_path()?;
+ let level = match self.zoom_px >= 1.0 {
+ true => 0,
+ false => (1.0 / self.zoom_px).log2().floor().clamp(0.0, 4.0) as u32,
+ };
+ self.frames.set_level(level);
+ let show = self.tend_frames()?;
+ let view_uniform = view.uniform(area, ctx.pixels_per_point(), canvas);
+ let (w, h) = self.scene.size();
+ let moving = self.drag.as_ref().filter(|d| d.moved()).map(Drag::affine);
+ let mut base = Vec::new();
+ let mut tops = Vec::new();
+ let mut lifted = None;
+ let mut lifting = false;
+ if let Some(state) = self.lift.as_mut()
+ && let Some((p, planes)) = state.ready.as_ref()
+ {
+ let stages = planes.runs.len() + 2;
+ if state.stage == 0 {
+ base = planes.base.clone();
+ }
+ tops = planes
+ .runs
+ .iter()
+ .enumerate()
+ .map(|(k, (mix, tiles))| {
+ let draw = QuadDraw {
+ uniform: quad_uniform(&view_uniform, IDENTITY, 1.0, [0.0, 0.0, w as f32, h as f32]),
+ tiles: Mutex::new(if state.stage == k + 1 {
+ tiles.clone()
+ } else {
+ Vec::new()
+ }),
+ image: Mutex::new(None),
+ };
+ (*mix, draw)
+ })
+ .collect();
+ let affine = state.commit.as_ref().map_or(moving.unwrap_or(IDENTITY), |c| c.affine);
+ lifted = Some(QuadDraw {
+ uniform: quad_uniform(&view_uniform, affine, planes.opacity, p.lifted.rect),
+ tiles: Mutex::new(Vec::new()),
+ image: Mutex::new(
+ (state.stage == stages - 1).then(|| (p.lifted.width, p.lifted.height, p.lifted.pixels.clone())),
+ ),
+ });
+ if state.stage < stages {
+ state.stage += 1;
+ ctx.request_repaint();
+ }
+ lifting = state.stage >= stages && (moving.is_some() || state.commit.is_some());
+ }
+ let mut tiles = std::mem::take(&mut self.dirty);
+ let mut stroke: Vec<usize> = self.buffer.take_dirty();
+ stroke.extend(self.mirror_buffer.take_dirty());
+ if !self.canvas_current() {
+ tiles.clear();
+ stroke.clear();
+ }
+ let refill = self.live.is_none() && tiles.len() > self.batch;
+ if refill {
+ let later = tiles.split_off(&tiles.iter().nth(self.batch).copied().unwrap_or(usize::MAX));
+ self.dirty.extend(later);
+ ctx.request_repaint();
+ }
+ let tiles: Vec<usize> = tiles.into_iter().collect();
+ let start = Instant::now();
+ let preview = self.live.as_ref().map(|l| Preview {
+ twin: l.twin.as_ref().map(|_| &self.mirror_buffer),
+ buffer: &self.buffer,
+ color: l.stroke.color(),
+ opacity: l.stroke.opacity,
+ blend: stroke_blend(&l.brush, l.stroke.lock).unwrap_or(l.brush.blend),
+ });
+ let uploads = if tiles.is_empty() && stroke.is_empty() {
+ Vec::new()
+ } else {
+ self.scene.compose_painting(&stroke, &tiles, preview.as_ref())?
+ };
+ if !uploads.is_empty() {
+ let spent = ms(start);
+ if refill {
+ self.batch = ((uploads.len() as f64 * REFILL_MS / spent.max(0.1)) as usize).clamp(8, timeline::FILL);
+ }
+ let mut stats = lock(&self.stats);
+ stats.compose_ms.push(spent as f32);
+ stats.tiles.push(uploads.len() as f32);
+ }
+ let (frame_uploads, frame_drops) = self.frames.take();
+ ui.painter().add(egui_wgpu::Callback::new_paint_callback(
+ rect,
+ CanvasPaint {
+ show: show.filter(|_| !lifting),
+ frame_uploads: Mutex::new(frame_uploads),
+ frame_drops,
+ uniform: view_uniform,
+ uploads: Mutex::new(uploads),
+ size: (w, h),
+ cols: self.scene.cols(),
+ pending: self.pending.take(),
+ stats: self.stats.clone(),
+ base: Mutex::new(base),
+ tops,
+ lift: lifted,
+ lifting,
+ },
+ ));
+ self.parallax(ui, view, rect);
+ self.decorate(ui, view, rect);
+ if self.live.is_some()
+ || self.lasso.is_some()
+ || self.drag.is_some()
+ || self.point_drag.is_some()
+ || self.path_commit.is_some()
+ || self
+ .lift
+ .as_ref()
+ .is_some_and(|l| l.job.is_some() || l.commit.is_some())
+ {
+ ctx.request_repaint();
+ }
+ self.share_selection();
+ Ok(())
+ }
+
+ fn decorate(&self, ui: &egui::Ui, view: View, rect: Rect) {
+ let painter = ui.painter().with_clip_rect(rect);
+ let accent = Color32::from_rgb(64, 196, 255);
+ let dark = egui::Stroke::new(3.0, Color32::from_black_alpha(140));
+ if let Some(picked) = self.picked.as_ref().filter(|_| self.on_marks()) {
+ let thin = egui::Stroke::new(1.0, accent);
+ let moving = self.drag.as_ref().filter(|d| d.strokes && d.moved()).map(Drag::affine);
+ let to_screen = |x: f32, y: f32| {
+ let (x, y) = moving.map_or((x, y), |a| lift::affine_apply(a, (x, y)));
+ self.screen(view, rect, vec2(x, y))
+ };
+ let parts = self.picked_parts();
+ let chosen = parts
+ .iter()
+ .flat_map(|(_, _, marks, ids)| marks.iter().filter(|m| ids.contains(&m.id())));
+ chosen.for_each(|m| match m {
+ Mark::Stroke(s) => {
+ let points: Vec<(f32, f32)> = s.samples.iter().map(|v| v.pos()).collect();
+ points
+ .chunk_by(|a, b| klad_core::cut::keeps(&s.cuts, *a) == klad_core::cut::keeps(&s.cuts, *b))
+ .filter(|run| klad_core::cut::keeps(&s.cuts, run[0]))
+ .for_each(|run| {
+ let line: Vec<Pos2> = run.iter().map(|&(x, y)| to_screen(x, y)).collect();
+ painter.add(egui::Shape::line(line, thin));
+ });
+ }
+ Mark::Fill(f) => {
+ if let Some([x0, y0, x1, y1]) = m.bounds().or(f.bounds()) {
+ let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| to_screen(x, y));
+ painter.add(egui::Shape::closed_line(corners.to_vec(), thin));
+ }
+ }
+ });
+ if let Some(polygon) = &picked.cut {
+ let line: Vec<Pos2> = polygon.iter().map(|p| to_screen(p[0], p[1])).collect();
+ painter.add(egui::Shape::dashed_line(
+ &[line.clone(), line[..1].to_vec()].concat(),
+ egui::Stroke::new(1.5, accent),
+ 6.0,
+ 4.0,
+ ));
+ }
+ }
+ if self.tool == Tool::Direct {
+ self.decorate_points(&painter, view, rect, accent, dark);
+ }
+ self.decorate_shape(&painter, &|x, y| self.screen(view, rect, vec2(x, y)), accent);
+ if let Some(axis) = self.mirror.filter(|_| self.tool == Tool::Brush) {
+ let h = self.scene.size().1 as f32;
+ painter.add(egui::Shape::dashed_line(
+ &[
+ self.screen(view, rect, vec2(axis, 0.0)),
+ self.screen(view, rect, vec2(axis, h)),
+ ],
+ egui::Stroke::new(1.0, accent),
+ 8.0,
+ 6.0,
+ ));
+ }
+ if let Some(path) = self.pen_path.as_ref() {
+ let hover = ui.input(|i| i.pointer.hover_pos());
+ self.decorate_pen(&painter, path, hover, view, rect, accent, dark);
+ }
+ if let Some((_, corners)) = self.handles() {
+ let committing = self.lift.as_ref().and_then(|l| l.commit.as_ref()).map(|c| c.affine);
+ let corners = match (&self.drag, committing) {
+ (Some(drag), _) => drag.preview(),
+ (None, Some(a)) => corners.map(|c| {
+ let (x, y) = lift::affine_apply(a, (c.x, c.y));
+ vec2(x, y)
+ }),
+ _ => corners,
+ };
+ let screen: Vec<Pos2> = corners.iter().map(|c| self.screen(view, rect, *c)).collect();
+ painter.add(egui::Shape::closed_line(screen.clone(), dark));
+ painter.add(egui::Shape::closed_line(screen.clone(), egui::Stroke::new(1.5, accent)));
+ screen.iter().for_each(|p| {
+ painter.rect_filled(Rect::from_center_size(*p, vec2(HANDLE, HANDLE)), 1.0, Color32::WHITE);
+ painter.rect_stroke(
+ Rect::from_center_size(*p, vec2(HANDLE, HANDLE)),
+ 1.0,
+ egui::Stroke::new(1.0, accent),
+ egui::StrokeKind::Middle,
+ );
+ });
+ if self.edges() {
+ let flat = [0, 1, 2, 3].map(|i| screen[i].to_vec2());
+ (0..4).for_each(|side| {
+ let p = edge(&flat, side).to_pos2();
+ painter.circle_filled(p, HANDLE / 2.0 - 0.5, Color32::WHITE);
+ painter.circle_stroke(p, HANDLE / 2.0 - 0.5, egui::Stroke::new(1.0, accent));
+ });
+ }
+ let top = screen[0].lerp(screen[1], 0.5);
+ let center = screen.iter().fold(Vec2::ZERO, |a, p| a + p.to_vec2()) / 4.0;
+ let knob = top + (top.to_vec2() - center).normalized() * KNOB;
+ painter.line_segment([top, knob], egui::Stroke::new(1.5, accent));
+ painter.circle_filled(knob, HANDLE / 2.0 + 1.0, Color32::WHITE);
+ painter.circle_stroke(knob, HANDLE / 2.0 + 1.0, egui::Stroke::new(1.0, accent));
+ }
+ self.draw_pins(&painter, |c| self.screen(view, rect, c));
+ if let Some(lasso) = self.lasso.as_ref().filter(|l| l.far) {
+ let line: Vec<Pos2> = lasso.points.iter().map(|p| self.screen(view, rect, *p)).collect();
+ let tint = if matches!(self.tool, Tool::Strokes | Tool::Select) {
+ accent
+ } else {
+ color::color32(self.color)
+ };
+ painter.add(egui::Shape::closed_line(line.clone(), dark));
+ painter.add(egui::Shape::closed_line(line, egui::Stroke::new(1.5, tint)));
+ }
+ let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p));
+ if let Some(hover) = hover.filter(|_| self.modifiers.alt && matches!(self.tool, Tool::Brush | Tool::Fill)) {
+ painter.circle_stroke(hover, 9.0, egui::Stroke::new(3.0, Color32::from_black_alpha(160)));
+ painter.circle_stroke(hover, 9.0, egui::Stroke::new(1.5, Color32::WHITE));
+ painter.circle_filled(hover, 5.0, color::color32(self.color));
+ return;
+ }
+ if self.tool == Tool::Fill
+ && let Some(hover) = hover
+ {
+ let arm = |d: Vec2| [hover + d * 3.0, hover + d * 9.0];
+ [vec2(1.0, 0.0), vec2(-1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, -1.0)]
+ .iter()
+ .for_each(|d| {
+ painter.line_segment(arm(*d), egui::Stroke::new(3.0, Color32::from_black_alpha(160)));
+ painter.line_segment(arm(*d), egui::Stroke::new(1.5, Color32::WHITE));
+ });
+ }
+ if let Some((_, _, origin)) = self.sizing {
+ let radius = (self.size * 0.5 * view.zoom).max(1.5);
+ painter.circle_stroke(origin, radius, egui::Stroke::new(1.0, Color32::from_gray(30)));
+ painter.circle_stroke(origin, radius + 1.0, egui::Stroke::new(1.0, Color32::from_gray(235)));
+ painter.text(
+ origin + vec2(radius + 8.0, 0.0),
+ egui::Align2::LEFT_CENTER,
+ format!("{:.1} px", self.size),
+ egui::FontId::proportional(13.0),
+ Color32::WHITE,
+ );
+ return;
+ }
+ if self.tool == Tool::Brush
+ && let Some(hover) = hover
+ {
+ let radius = (self.size * 0.5 * view.zoom).max(1.5);
+ painter.circle_stroke(hover, radius, egui::Stroke::new(1.0, Color32::from_gray(30)));
+ painter.circle_stroke(hover, radius + 1.0, egui::Stroke::new(1.0, Color32::from_gray(235)));
+ }
+ }
+
+ fn decorate_points(&self, painter: &egui::Painter, view: View, rect: Rect, accent: Color32, dark: egui::Stroke) {
+ let (Some(shaped), Some(direct)) = (self.shaped.as_ref(), self.direct.as_ref()) else {
+ return;
+ };
+ let Some(subs) = self.shown_subs() else {
+ return;
+ };
+ let m = shaped.matrix;
+ let screen = |p: [f32; 2]| self.screen(view, rect, to_canvas(m, p));
+ let step = (2.0 / (view.zoom * (m[0] * m[3] - m[1] * m[2]).abs().sqrt()).max(1e-3)).clamp(0.05, 8.0);
+ pathedit::flatten(&subs, step)
+ .iter()
+ .zip(&subs)
+ .for_each(|(line, sub)| {
+ let points: Vec<Pos2> = line.iter().map(|p| screen(*p)).collect();
+ let shape = if sub.closed {
+ egui::Shape::closed_line(points, egui::Stroke::new(1.5, accent))
+ } else {
+ egui::Shape::line(points, egui::Stroke::new(1.5, accent))
+ };
+ painter.add(shape);
+ });
+ let anchors = pathedit::anchors(&subs);
+ let thin = egui::Stroke::new(1.0, accent);
+ direct.points.iter().filter_map(|&i| anchors.get(i)).for_each(|(_, a)| {
+ let at = screen(a.at);
+ [(a.inn, a.has_in()), (a.out, a.has_out())]
+ .into_iter()
+ .filter(|(_, has)| *has)
+ .for_each(|(p, _)| {
+ let h = screen(p);
+ painter.line_segment([at, h], thin);
+ painter.circle_filled(h, HANDLE / 2.0 - 0.5, Color32::WHITE);
+ painter.circle_stroke(h, HANDLE / 2.0 - 0.5, thin);
+ });
+ });
+ let size = HANDLE - 2.0;
+ anchors.iter().enumerate().for_each(|(i, (_, a))| {
+ let square = Rect::from_center_size(screen(a.at), vec2(size, size));
+ let fill = if direct.points.contains(&i) {
+ accent
+ } else {
+ Color32::WHITE
+ };
+ painter.rect_filled(square, 0.0, fill);
+ painter.rect_stroke(square, 0.0, thin, egui::StrokeKind::Middle);
+ });
+ if let Some(drag) = self.point_drag.filter(|d| matches!(d.grab, PointGrab::Marquee { .. })) {
+ let (a, b) = (self.screen(view, rect, drag.start), self.screen(view, rect, drag.now));
+ let area = Rect::from_two_pos(a, b);
+ painter.rect_stroke(area, 0.0, dark, egui::StrokeKind::Middle);
+ painter.rect_stroke(area, 0.0, thin, egui::StrokeKind::Middle);
+ }
+ }
+
+ fn chosen_marks(&self) -> Option<(Picked, Vec<(String, Mark)>)> {
+ let picked = self.picked.clone()?;
+ let parts = self.picked_parts();
+ if parts.is_empty() {
+ return None;
+ }
+ let chosen = parts
+ .iter()
+ .flat_map(|(_, cel, marks, ids)| {
+ marks
+ .iter()
+ .filter(|m| ids.contains(&m.id()))
+ .map(|m| (cel.clone(), m.clone()))
+ })
+ .collect();
+ Some((picked, chosen))
+ }
+
+ fn set_picked(&mut self, sets: Vec<(String, u32, &'static str, Value)>) -> Result<()> {
+ let Some(picked) = self.picked.clone().filter(|_| !sets.is_empty()) else {
+ return Ok(());
+ };
+ let start = Instant::now();
+ let (mut ops, after) = match &picked.cut {
+ Some(_) => self
+ .picked_ops(LassoAction::Transform(MarkTransform::default()))
+ .ok_or_else(|| anyhow!("the cut selection is out of date"))?,
+ None => (Vec::new(), Some(picked.clone())),
+ };
+ ops.extend(sets.into_iter().map(|(cel, id, key, value)| Op::Set {
+ id: address(&cel, id),
+ props: Map::from_iter([(key.to_string(), value)]),
+ }));
+ self.apply(ops)?;
+ self.picked = after;
+ self.forget_missing_selection();
+ self.measure("stroke edit", format!("stroke edit redrawn in {:.0} ms", ms(start)));
+ Ok(())
+ }
+
+ fn recolour_picked(&mut self) -> Result<()> {
+ let hex = color::hex(self.color);
+ let sets = self.chosen_marks().map_or(Vec::new(), |(_, chosen)| {
+ chosen
+ .iter()
+ .map(|(cel, m)| (cel.clone(), m.id(), "color", json!(hex)))
+ .collect()
+ });
+ self.set_picked(sets)
+ }
+
+ fn size_picked(&mut self, k: f32) -> Result<()> {
+ let sets = self.chosen_marks().map_or(Vec::new(), |(_, chosen)| {
+ chosen
+ .iter()
+ .filter_map(|(cel, m)| {
+ m.as_stroke()
+ .map(|s| (cel.clone(), s.id, "size", json!((s.size * k).max(0.1))))
+ })
+ .collect()
+ });
+ self.set_picked(sets)
+ }
+
+ fn flip_picked(&mut self, sx: f32, sy: f32) -> Result<()> {
+ let middle = self
+ .picked_corners()
+ .map(|(_, c)| [(c[0].x + c[2].x) / 2.0, (c[0].y + c[2].y) / 2.0]);
+ let start = Instant::now();
+ self.edit_picked(LassoAction::Transform(MarkTransform {
+ sx,
+ sy,
+ pivot: middle,
+ ..Default::default()
+ }))?;
+ self.measure("stroke edit", format!("stroke edit redrawn in {:.0} ms", ms(start)));
+ Ok(())
+ }
+
+ fn select_all_strokes(&mut self) {
+ let ids: Vec<u32> = self.scene.active_marks().iter().map(Mark::id).collect();
+ let more: Vec<Part> = self
+ .also_cels()
+ .into_iter()
+ .map(|(layer, cel)| Part {
+ ids: self.scene.marks_of(&cel).iter().map(Mark::id).collect(),
+ layer,
+ cel,
+ })
+ .filter(|p| !p.ids.is_empty())
+ .collect();
+ if let Some(cel) = self.scene.active_cel().filter(|_| !ids.is_empty() || !more.is_empty()) {
+ self.tool = Tool::Strokes;
+ self.picked = Some(Picked {
+ more,
+ ..Picked::whole(cel, ids)
+ });
+ }
+ }
+
+ fn strokes_inspector(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some((picked, chosen)) = self.chosen_marks() else {
+ ui.label(match self.also.is_empty() {
+ true => "click a stroke or drag a loop around strokes on the active paint layer (shift adds); cmd click layers in the layers panel to select on several at once".to_string(),
+ false => format!("click a stroke or drag a loop: it selects on the active layer and {} more (cmd clicked in the layers panel)", self.also.len()),
+ });
+ return Ok(());
+ };
+ let fills = chosen.iter().filter(|(_, m)| m.as_fill().is_some()).count();
+ let place = match picked.more.len() {
+ 0 => format!("in cel {}", picked.cel),
+ n => format!("on {} layers", n + 1),
+ };
+ ui.label(format!(
+ "{} strokes, {fills} fills selected {place}{}",
+ chosen.len() - fills,
+ if picked.cut.is_some() {
+ "\n(with the parts crossing the lasso edge)"
+ } else {
+ ""
+ }
+ ));
+ ui.small("the bar under the selection edits it; drag inside the box to move, a corner to scale, an edge to stretch (past the other edge flips), the knob to turn; arrows nudge");
+ Ok(())
+ }
+
+ fn path_inspector(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some(direct) = self.direct.clone() else {
+ ui.label("click a stroke, path, rect or ellipse to edit its points");
+ return Ok(());
+ };
+ if markedit::parse_address(&direct.node).is_some() {
+ let points = self
+ .shaped
+ .as_ref()
+ .map_or(0, |s| s.subs.iter().map(|p| p.anchors.len()).sum());
+ ui.label(format!("stroke {}: {points} points fitted to it", direct.node));
+ ui.small("drag a point or a handle to bend the stroke (it keeps its pressure); alt click the line adds a point; Delete removes the selected points");
+ return Ok(());
+ }
+ let Some(Item::Node(layer, _, node)) = self.scene.bundle.doc.item(&direct.node) else {
+ self.direct = None;
+ return Ok(());
+ };
+ let (kind, layer_id, is_path) = (
+ node.type_name(),
+ layer.id.clone(),
+ matches!(node.shape, Shape::Path { .. }),
+ );
+ let total = self
+ .shaped
+ .as_ref()
+ .map_or(0, |s| s.subs.iter().map(|p| p.anchors.len()).sum::<usize>());
+ ui.label(format!(
+ "{kind} {}{} in {layer_id}: {total} points, {} selected",
+ direct.node,
+ if node.name.is_empty() {
+ String::new()
+ } else {
+ format!(" \"{}\"", node.name)
+ },
+ direct.points.len()
+ ));
+ if !is_path {
+ ui.label(format!("any point edit turns this {kind} into a path"));
+ }
+ if self.under.len() > 1 && self.under.contains(&direct.node) {
+ ui.label("under the last click (clicking the shape again steps down):");
+ let doc = &self.scene.bundle.doc;
+ let rows: Vec<(String, String)> = self
+ .under
+ .iter()
+ .take(12)
+ .map(|id| {
+ let what = match doc.item(id) {
+ Some(Item::Node(_, _, n)) => format!("{id} {} {}", n.type_name(), n.name),
+ _ => id.clone(),
+ };
+ (id.clone(), what)
+ })
+ .collect();
+ let mut pick = None;
+ rows.into_iter().for_each(|(id, what)| {
+ if ui.selectable_label(id == direct.node, what).clicked() {
+ pick = Some(id);
+ }
+ });
+ if let Some(id) = pick {
+ self.pick_shape(id);
+ return Ok(());
+ }
+ }
+ ui.small(
+ "drag points or handles; shift click adds a point to the selection, drag on empty canvas selects in a box\n\
+ alt click the outline: new point; alt click a point: corner or smooth; alt drag a handle: break it",
+ );
+ if self.path_commit.is_some() {
+ ui.label("writing the last edit...");
+ }
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn number(
+ &mut self,
+ ui: &mut egui::Ui,
+ key: &str,
+ label: &str,
+ current: f32,
+ range: RangeInclusive<f32>,
+ speed: f64,
+ hint: &str,
+ ) -> Option<f32> {
+ let mut value = self.edits.get(key).copied().unwrap_or(current);
+ let response = ui
+ .add(egui::DragValue::new(&mut value).speed(speed).range(range).prefix(label))
+ .hint(hint);
+ if response.dragged() || response.has_focus() {
+ self.edits.insert(key.to_string(), value);
+ return None;
+ }
+ let pending = self.edits.remove(key);
+ if response.drag_stopped() || response.lost_focus() || response.changed() {
+ return Some(value);
+ }
+ pending.filter(|p| (p - current).abs() > f32::EPSILON)
+ }
+
+ fn text(&mut self, ui: &mut egui::Ui, key: &str, label: &str, current: &str, hint: &str) -> Option<String> {
+ let mut value = self.texts.get(key).cloned().unwrap_or_else(|| current.to_string());
+ let label = ui.label(label);
+ let response = ui.text_edit_singleline(&mut value).labelled_by(label.id).hint(hint);
+ if response.has_focus() {
+ self.texts.insert(key.to_string(), value);
+ return None;
+ }
+ self.texts.remove(key);
+ (response.lost_focus() && value != current).then_some(value)
+ }
+
+ fn node_inspector(&mut self, ui: &mut egui::Ui, id: &str) -> Result<()> {
+ let Some(Item::Node(layer, _, node)) = self.scene.bundle.doc.item(id) else {
+ self.selection = None;
+ return Ok(());
+ };
+ let (node, layer) = (node.clone(), layer.id.clone());
+ ui.label(format!("{} {} in {}", node.type_name(), node.id, layer));
+ let mut props: Vec<(String, Value)> = Vec::new();
+ ui.horizontal(|ui| {
+ if let Some(name) = self.text(
+ ui,
+ &format!("{id}.name"),
+ "name",
+ &node.name,
+ "the shape's name; Return keeps it",
+ ) {
+ props.push(("name".into(), json!(name)));
+ }
+ });
+ if let Some(paint) = self.paint_editor(ui, id, &node) {
+ props.push(("fill".into(), serde_json::to_value(paint)?));
+ }
+ if let Shape::Rays(rays) = &node.shape {
+ let changed = ui.horizontal_wrapped(|ui| self.rays_section(ui, id, rays)).inner;
+ if let Some(Value::Object(fields)) = changed {
+ props.extend(fields);
+ }
+ }
+ props.extend(self.shape_fields(ui, id, &node));
+ let t = node.transform;
+ ui.horizontal(|ui| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.x"),
+ "x ",
+ t.x,
+ -1e5..=1e5,
+ 1.0,
+ "move it across, in canvas px",
+ ) {
+ props.push(("transform.x".into(), json!(v)));
+ }
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.y"),
+ "y ",
+ t.y,
+ -1e5..=1e5,
+ 1.0,
+ "move it down, in canvas px",
+ ) {
+ props.push(("transform.y".into(), json!(v)));
+ }
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.r"),
+ "rotate ",
+ t.rotate,
+ -3600.0..=3600.0,
+ 0.5,
+ "turn it, in degrees clockwise",
+ ) {
+ props.push(("transform.rotate".into(), json!(v)));
+ }
+ });
+ ui.horizontal(|ui| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.sx"),
+ "sx ",
+ t.sx,
+ -100.0..=100.0,
+ 0.01,
+ "scale across; negative mirrors",
+ ) {
+ props.push(("transform.sx".into(), json!(v)));
+ }
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.sy"),
+ "sy ",
+ t.sy,
+ -100.0..=100.0,
+ 0.01,
+ "scale up and down; negative mirrors",
+ ) {
+ props.push(("transform.sy".into(), json!(v)));
+ }
+ });
+ ui.horizontal(|ui| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.o"),
+ "opacity ",
+ node.opacity,
+ 0.0..=1.0,
+ 0.01,
+ "the shape's opacity",
+ ) {
+ props.push(("opacity".into(), json!(v)));
+ }
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.b"),
+ "blur ",
+ node.blur,
+ 0.0..=200.0,
+ 0.2,
+ "soften the whole shape, in px",
+ ) {
+ props.push(("blur".into(), json!(v)));
+ }
+ });
+ let mut remove = false;
+ ui.horizontal(|ui| {
+ let mut visible = node.visible;
+ if ui
+ .checkbox(&mut visible, "visible")
+ .hint("show or hide this shape")
+ .changed()
+ {
+ props.push(("visible".into(), json!(visible)));
+ }
+ remove = ui.button("delete").hint("remove this shape (Delete)").clicked();
+ if ui.button("deselect").hint("clear the selection (Esc)").clicked() {
+ self.selection = None;
+ }
+ });
+ self.set(id, props)?;
+ if remove {
+ self.selection = None;
+ self.apply(vec![Op::Remove {
+ ids: vec![id.to_string()],
+ }])?;
+ }
+ Ok(())
+ }
+
+ fn paint_editor(&mut self, ui: &mut egui::Ui, id: &str, node: &Node) -> Option<Paint> {
+ let first = |stops: &[Stop]| stops.first().map_or("#000000".to_string(), |s| s.1.clone());
+ let (kind, base) = match &node.fill {
+ Some(Paint::Solid(hex)) if hex == "none" => ("none", "#000000".to_string()),
+ Some(Paint::Solid(hex)) => ("solid", hex.clone()),
+ None => ("solid", "#000000".to_string()),
+ Some(Paint::Linear { linear }) => ("linear", first(&linear.stops)),
+ Some(Paint::Radial { radial }) => ("radial", first(&radial.stops)),
+ };
+ let mut chosen = kind;
+ let mut out: Option<Paint> = None;
+ ui.horizontal(|ui| {
+ ui.label("fill");
+ egui::ComboBox::from_id_salt(format!("{id}.fillkind"))
+ .selected_text(kind)
+ .show_ui(ui, |ui| {
+ ["none", "solid", "linear", "radial"].iter().for_each(|k| {
+ ui.selectable_value(&mut chosen, *k, *k);
+ });
+ })
+ .response
+ .hint("no fill, one colour, or a linear or radial gradient");
+ if kind == "solid" {
+ let mut colour = color_of(&base).unwrap_or(Color32::BLACK);
+ if egui::color_picker::color_edit_button_srgba(ui, &mut colour, egui::color_picker::Alpha::OnlyBlend)
+ .hint("the fill colour")
+ .changed()
+ {
+ out = Some(Paint::Solid(hex_of(colour)));
+ }
+ if ui
+ .button("use brush colour")
+ .hint("fill it with the current colour")
+ .clicked()
+ {
+ out = Some(Paint::Solid(color::hex(self.color)));
+ }
+ }
+ });
+ if chosen != kind {
+ let [x, y, w, h] = klad_render::vector::local_bounds(node)
+ .ok()
+ .flatten()
+ .map_or([0.0, 0.0, 100.0, 100.0], |r| [r.left, r.top, r.width(), r.height()]);
+ let stops = vec![Stop(0.0, base.clone()), Stop(1.0, "#ffffff".into())];
+ return Some(match chosen {
+ "none" => Paint::Solid("none".into()),
+ "solid" => Paint::Solid(base),
+ "linear" => Paint::Linear {
+ linear: Linear {
+ from: [x + w / 2.0, y],
+ to: [x + w / 2.0, y + h],
+ stops,
+ },
+ },
+ _ => Paint::Radial {
+ radial: Radial {
+ center: [x + w / 2.0, y + h / 2.0],
+ radius: (w.max(h) / 2.0).max(1.0),
+ stops,
+ },
+ },
+ });
+ }
+ match &node.fill {
+ Some(Paint::Linear { linear }) => {
+ let mut next = linear.clone();
+ let mut changed = false;
+ ui.horizontal(|ui| {
+ [("fx", 0, "from x "), ("fy", 1, "y ")]
+ .iter()
+ .for_each(|(k, c, label)| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.g.{k}"),
+ label,
+ linear.from[*c],
+ -1e5..=1e5,
+ 1.0,
+ "where the gradient starts, in the shape's own px",
+ ) {
+ next.from[*c] = v;
+ changed = true;
+ }
+ });
+ });
+ ui.horizontal(|ui| {
+ [("tx", 0, "to x "), ("ty", 1, "y ")].iter().for_each(|(k, c, label)| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.g.{k}"),
+ label,
+ linear.to[*c],
+ -1e5..=1e5,
+ 1.0,
+ "where the gradient ends, in the shape's own px",
+ ) {
+ next.to[*c] = v;
+ changed = true;
+ }
+ });
+ });
+ if let Some(stops) = self.stops_editor(ui, id, &linear.stops) {
+ next.stops = stops;
+ changed = true;
+ }
+ changed.then_some(Paint::Linear { linear: next }).or(out)
+ }
+ Some(Paint::Radial { radial }) => {
+ let mut next = radial.clone();
+ let mut changed = false;
+ ui.horizontal(|ui| {
+ [("cx", 0, "centre x "), ("cy", 1, "y ")]
+ .iter()
+ .for_each(|(k, c, label)| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.g.{k}"),
+ label,
+ radial.center[*c],
+ -1e5..=1e5,
+ 1.0,
+ "the centre of the gradient, in the shape's own px",
+ ) {
+ next.center[*c] = v;
+ changed = true;
+ }
+ });
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.g.r"),
+ "radius ",
+ radial.radius,
+ 0.1..=1e5,
+ 1.0,
+ "how far the gradient reaches",
+ ) {
+ next.radius = v;
+ changed = true;
+ }
+ });
+ if let Some(stops) = self.stops_editor(ui, id, &radial.stops) {
+ next.stops = stops;
+ changed = true;
+ }
+ changed.then_some(Paint::Radial { radial: next }).or(out)
+ }
+ _ => out,
+ }
+ }
+
+ fn stops_editor(&mut self, ui: &mut egui::Ui, id: &str, stops: &[Stop]) -> Option<Vec<Stop>> {
+ let mut next = stops.to_vec();
+ let mut changed = false;
+ let mut remove = None;
+ stops.iter().enumerate().for_each(|(i, Stop(at, hex))| {
+ ui.horizontal(|ui| {
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.g.s{i}"),
+ "stop ",
+ *at,
+ 0.0..=1.0,
+ 0.005,
+ "where this colour sits along the gradient, 0 to 1",
+ ) {
+ next[i].0 = v;
+ changed = true;
+ }
+ let mut colour = color_of(hex).unwrap_or(Color32::BLACK);
+ if egui::color_picker::color_edit_button_srgba(ui, &mut colour, egui::color_picker::Alpha::OnlyBlend)
+ .hint("this stop's colour")
+ .changed()
+ {
+ next[i].1 = hex_of(colour);
+ changed = true;
+ }
+ if ui
+ .button("brush colour")
+ .hint("give this stop the current colour")
+ .clicked()
+ {
+ next[i].1 = color::hex(self.color);
+ changed = true;
+ }
+ if stops.len() > 1 && ui.button(crate::theme::icon::CLOSE).hint("remove this stop").clicked() {
+ remove = Some(i);
+ }
+ });
+ });
+ if let Some(i) = remove {
+ next.remove(i);
+ changed = true;
+ }
+ if ui
+ .button("add stop")
+ .hint("a stop between the last two, in the current colour")
+ .clicked()
+ {
+ let at = match stops {
+ [.., a, b] => (a.0 + b.0) / 2.0,
+ _ => 0.5,
+ };
+ next.push(Stop(at, color::hex(self.color)));
+ changed = true;
+ }
+ if changed {
+ next.sort_by(|a, b| a.0.total_cmp(&b.0));
+ }
+ changed.then_some(next)
+ }
+
+ fn activate(&mut self, path: Vec<usize>) -> Result<()> {
+ if self.live.is_some() {
+ return Ok(());
+ }
+ let id = self.scene.bundle.doc.locate_path(&path).map(|l| l.id.clone());
+ self.scene.set_active_later(path);
+ if self.scene.onion_on {
+ self.frames_changed();
+ }
+ self.also.retain(|a| Some(a) != id.as_ref());
+ self.selection = None;
+ self.picked = None;
+ Ok(())
+ }
+
+ fn mask_inspector(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some(mask) = self.scene.active_layer().cloned() else {
+ return Ok(());
+ };
+ let owner_path = self.scene.active[..self.scene.active.len() - 1].to_vec();
+ let owner = self.scene.bundle.doc.layer_at(&owner_path).clone();
+ ui.label(format!("mask {} of {} ({})", mask.id, owner.name, owner.id));
+ ui.colored_label(Color32::from_rgb(255, 150, 150), self.mask_hint());
+ ui.horizontal_wrapped(|ui| {
+ self.command_check(ui, Cmd::ToggleMask, "mask on");
+ self.command_check(ui, Cmd::TintMask, "show the mask in red");
+ });
+ ui.horizontal_wrapped(|ui| {
+ self.command_button(ui, Cmd::BackToLayer, Some("back to the layer"));
+ self.command_button(ui, Cmd::RemoveMask, Some("remove mask"));
+ });
+ Ok(())
+ }
+
+ fn mask_hint(&self) -> &'static str {
+ if self.brush == "eraser" {
+ "the eraser is on: it shows the layer again where the mask hid it (E switches back to the brush)"
+ } else {
+ "the brush hides the layer where you paint (any colour); the eraser (E) shows it again"
+ }
+ }
+
+ fn layer_inspector(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ if self.scene.active_is_mask() {
+ return self.mask_inspector(ui);
+ }
+ let Some(layer) = self.scene.active_layer().cloned() else {
+ ui.label("no layer selected");
+ return Ok(());
+ };
+ let id = layer.id.clone();
+ ui.label(format!("{} layer {}", layer.kind().name(), id));
+ let mut props: Vec<(String, Value)> = Vec::new();
+ ui.horizontal(|ui| {
+ if let Some(name) = self.text(
+ ui,
+ &format!("{id}.name"),
+ "name",
+ &layer.name,
+ "the layer's name; Return keeps it",
+ ) {
+ props.push(("name".into(), json!(name)));
+ }
+ });
+ ui.horizontal_wrapped(|ui| {
+ self.command_check(ui, Cmd::ToggleLocked, "locked");
+ self.command_check(ui, Cmd::ToggleClip, "clip to layer below");
+ if layer.kind() == Kind::Paint {
+ self.command_check(ui, Cmd::ToggleLockAlpha, "lock alpha");
+ }
+ });
+ ui.horizontal_wrapped(|ui| match &layer.mask {
+ Some(_) => {
+ self.command_check(ui, Cmd::ToggleMask, "mask on");
+ self.command_button(ui, Cmd::PaintMask, Some("paint on the mask"));
+ self.command_button(ui, Cmd::RemoveMask, Some("remove mask"));
+ }
+ None => {
+ self.command_button(ui, Cmd::AddMask, Some("add mask"));
+ self.command_button(ui, Cmd::AddMaskHiding, Some("add mask hiding all"));
+ }
+ });
+ ui.horizontal_wrapped(|ui| {
+ let mut reference = layer.reference;
+ if ui
+ .checkbox(&mut reference, "reference")
+ .hint("shown here to trace over, left out of renders and exports (klad render --references shows it)")
+ .changed()
+ {
+ props.push(("reference".into(), json!(reference)));
+ }
+ });
+ self.set(&id, props)?;
+ self.depth_section(ui, &layer)?;
+ self.adjust_section(ui, &layer)?;
+ self.effects_section(ui, &layer)
+ }
+
+ fn colour_panel(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let mut picked: Option<[f32; 4]> = None;
+ let mut hsva = self.hsva;
+ ui.horizontal(|ui| {
+ if color::picker(ui, &mut hsva, 150.0) {
+ self.color = hsva.rgba();
+ self.hsva = hsva;
+ }
+ ui.vertical(|ui| {
+ color::swatch(ui, self.color, false, 44.0).hint("the current colour");
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ if let Some(text) = self.text(
+ ui,
+ "colour.hex",
+ "hex",
+ &color::hex(self.color),
+ "type #rrggbb or #rrggbbaa and press Return",
+ ) {
+ match color::rgba_of(&text) {
+ Some(rgba) => picked = Some(rgba),
+ None => self.say(Tone::Refused, format!("{text:?} is not #rrggbb or #rrggbbaa")),
+ }
+ }
+ });
+ let mut alpha = self.color[3];
+ if ui
+ .add(egui::Slider::new(&mut alpha, 0.0..=1.0).text("alpha"))
+ .hint("how see-through the colour is")
+ .changed()
+ {
+ let [r, g, b, _] = self.color;
+ self.set_colour([r, g, b, alpha]);
+ }
+ });
+ });
+ ui.label("palette");
+ let edit = self.palette_row(ui);
+ ui.horizontal_wrapped(|ui| {
+ let label = ui.label("name");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.swatch_name)
+ .hint_text("optional")
+ .desired_width(110.0),
+ )
+ .labelled_by(label.id)
+ .hint("a name for the colour; agents can use it in place of the hex");
+ self.command_button(ui, Cmd::AddSwatch, Some("add colour"));
+ });
+ if !self.settings.recent.is_empty() {
+ ui.label("recent");
+ let recent = self.settings.recent.clone();
+ let current = color::hex(self.color);
+ ui.horizontal_wrapped(|ui| {
+ recent.iter().for_each(|hex| {
+ if let Some(rgba) = color::rgba_of(hex)
+ && color::swatch(ui, rgba, hex.eq_ignore_ascii_case(&current), 24.0)
+ .hint(format!("{hex}, used lately"))
+ .clicked()
+ {
+ picked = Some(rgba);
+ }
+ });
+ });
+ }
+ if let Some(rgba) = picked {
+ self.pick_new_colour(rgba);
+ }
+ match edit {
+ Some(edit) => self.apply(vec![Op::Palette(edit)]),
+ None => Ok(()),
+ }
+ }
+
+ fn fill_panel(&mut self, ui: &mut egui::Ui) {
+ let layers: Vec<(String, String)> = self
+ .scene
+ .bundle
+ .doc
+ .all_layers()
+ .iter()
+ .rev()
+ .map(|l| (l.id.clone(), l.name.clone()))
+ .collect();
+ let name_of = |r: &FillRef| match r {
+ FillRef::This => "this layer".to_string(),
+ FillRef::All => "all visible layers".to_string(),
+ FillRef::Layer(id) => layers
+ .iter()
+ .find(|(l, _)| l == id)
+ .map_or(id.clone(), |(_, name)| format!("{name} ({id})")),
+ };
+ let mut reference = self.fill.reference.clone();
+ ui.horizontal_wrapped(|ui| {
+ ui.label("inside the lines of");
+ egui::ComboBox::from_id_salt("fill.ref")
+ .selected_text(name_of(&reference))
+ .width(170.0)
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut reference, FillRef::This, name_of(&FillRef::This));
+ ui.selectable_value(&mut reference, FillRef::All, name_of(&FillRef::All));
+ layers.iter().for_each(|(id, _)| {
+ let r = FillRef::Layer(id.clone());
+ let text = name_of(&r);
+ ui.selectable_value(&mut reference, r, text);
+ });
+ })
+ .response
+ .hint("the lines the fill stops at: this layer, everything visible, or a layer such as your lines");
+ });
+ self.fill.reference = reference;
+ let f = &mut self.fill;
+ ui.add(egui::Slider::new(&mut f.gap, 0.0..=fill::MAX_GAP).text("close gaps px"))
+ .hint("openings in the lines up to this wide count as closed");
+ ui.add(egui::Slider::new(&mut f.tolerance, 0.0..=1.0).text("tolerance"))
+ .hint("how different a pixel may be from where you click and still fill");
+ ui.add(egui::Slider::new(&mut f.expand, 0.0..=fill::MAX_EXPAND).text("grow under lines px"))
+ .hint("the fill reaches this far under the lines, so no paper shows between line and colour");
+ ui.add(egui::Slider::new(&mut f.opacity, 0.05..=1.0).text("opacity"))
+ .hint("the fill's opacity");
+ ui.small("click inside lines to fill, drag a loop to lasso fill");
+ if !self.scene.can_paint() {
+ ui.colored_label(Color32::LIGHT_YELLOW, "pick a paint layer to fill on");
+ }
+ }
+
+ fn pen_panel(&mut self, ui: &mut egui::Ui) {
+ let key = device_key(self.readout.device);
+ let mut curve = self.settings.curve(&key);
+ let raw = self.readout.pressure;
+ let peak = self.settings.peak(&key);
+ ui.label(if self.readout.device == 0 {
+ "pen: not identified yet (move it away from the tablet and back)".to_string()
+ } else {
+ format!("pen: {key}")
+ });
+ ui.add(egui::ProgressBar::new(raw).text(format!("pen {raw:.3}")));
+ ui.add(egui::ProgressBar::new(curve.apply(raw)).text(format!("recorded {:.3}", curve.apply(raw))));
+ ui.label(format!("heaviest press seen {peak:.3}"));
+ let before = curve;
+ ui.add(egui::Slider::new(&mut curve.low, 0.0..=0.5).text("lightest"))
+ .hint("the pen's raw pressure that records as the lightest touch");
+ ui.add(egui::Slider::new(&mut curve.high, 0.05..=1.0).text("heaviest"))
+ .hint("the pen's raw pressure that records as full pressure");
+ ui.add(
+ egui::Slider::new(&mut curve.gamma, 0.3..=3.0)
+ .logarithmic(true)
+ .text("curve"),
+ )
+ .hint("below 1 light presses record heavier, above 1 lighter");
+ ui.horizontal_wrapped(|ui| {
+ if ui
+ .button("heaviest = my peak")
+ .hint("set heaviest to the hardest press seen with this pen")
+ .clicked()
+ && peak > 0.05
+ {
+ curve.high = peak;
+ }
+ if ui.button("reset").hint("the default curve").clicked() {
+ curve = PressureCurve::default();
+ }
+ if ui
+ .button("forget peak")
+ .hint("start measuring the hardest press again")
+ .clicked()
+ && let Some(pen) = self.settings.pens.get_mut(&key)
+ {
+ pen.peak = 0.0;
+ self.settings_dirty = true;
+ }
+ });
+ let (rect, _) = ui.allocate_exact_size(vec2(160.0, 90.0), Sense::hover());
+ let painter = ui.painter_at(rect);
+ painter.rect_filled(rect, 2.0, Color32::from_gray(28));
+ let at = |x: f32, y: f32| egui::pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height());
+ let line: Vec<Pos2> = (0..=40)
+ .map(|i| i as f32 / 40.0)
+ .map(|x| at(x, curve.apply(x)))
+ .collect();
+ painter.add(egui::Shape::line(line, egui::Stroke::new(1.5, Color32::LIGHT_BLUE)));
+ painter.circle_filled(at(raw, curve.apply(raw)), 3.5, Color32::YELLOW);
+ if curve != before {
+ curve.high = curve.high.max(curve.low + 0.05);
+ self.settings.set_curve(&key, curve);
+ self.settings_dirty = true;
+ }
+ }
+}
+
+impl Editor {
+ #[cfg(test)]
+ pub(crate) fn redraw_canvas(&mut self) {
+ self.dirty.extend(self.scene.all_tiles());
+ }
+
+ pub(crate) fn clear(&self) -> [f32; 4] {
+ crate::theme::surround(self.settings.defaults.surround)
+ }
+
+ pub(crate) fn take_tabs(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
+ if !ctx.egui_wants_keyboard_input() {
+ self.tabs.extend(crate::layout::take_tabs(raw_input));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn grab_finds_every_handle_where_the_press_lands() {
+ use egui::pos2;
+ let screen = [
+ pos2(100.0, 100.0),
+ pos2(300.0, 100.0),
+ pos2(300.0, 200.0),
+ pos2(100.0, 200.0),
+ ];
+ assert_eq!(grab(screen, pos2(200.0, 100.0 - KNOB), true), Some(Grab::Rotate));
+ assert_eq!(
+ grab(screen, pos2(200.0 + 9.0, 100.0 - KNOB - 6.0), true),
+ Some(Grab::Rotate)
+ );
+ assert_eq!(grab(screen, pos2(311.0, 104.0), true), Some(Grab::Scale));
+ assert_eq!(grab(screen, pos2(92.0, 207.0), false), Some(Grab::Scale));
+ assert_eq!(grab(screen, pos2(200.0, 111.0), true), Some(Grab::Stretch(0)));
+ assert_eq!(grab(screen, pos2(309.0, 150.0), true), Some(Grab::Stretch(1)));
+ assert_eq!(grab(screen, pos2(200.0, 189.0), true), Some(Grab::Stretch(2)));
+ assert_eq!(grab(screen, pos2(91.0, 150.0), true), Some(Grab::Stretch(3)));
+ assert_eq!(grab(screen, pos2(309.0, 150.0), false), None);
+ assert_eq!(grab(screen, pos2(295.0, 150.0), false), Some(Grab::Move));
+ assert_eq!(grab(screen, pos2(200.0, 150.0), true), Some(Grab::Move));
+ assert_eq!(grab(screen, pos2(330.0, 150.0), true), None);
+ }
+
+ #[test]
+ fn stroke_drags_commit_what_the_preview_shows() {
+ [
+ Grab::Move,
+ Grab::Scale,
+ Grab::Rotate,
+ Grab::Stretch(0),
+ Grab::Stretch(1),
+ Grab::Stretch(3),
+ ]
+ .iter()
+ .for_each(|&grab| {
+ let drag = Drag {
+ grab,
+ node: "c1:1,2".into(),
+ strokes: true,
+ fresh: false,
+ copy: false,
+ start: vec2(140.0, 80.0),
+ now: vec2(190.0, 20.0),
+ center: vec2(100.0, 100.0),
+ corners: [
+ vec2(50.0, 50.0),
+ vec2(150.0, 50.0),
+ vec2(150.0, 150.0),
+ vec2(50.0, 150.0),
+ ],
+ };
+ let committed = drag.mark_transform();
+ let a = committed.affine(committed.pivot.unwrap_or([0.0, 0.0]));
+ drag.affine()
+ .iter()
+ .zip(a)
+ .for_each(|(p, c)| assert!((p - c).abs() < 1e-3, "{grab:?}: {:?} vs {a:?}", drag.affine()));
+ });
+ }
+
+ #[test]
+ fn points_map_between_canvas_and_the_shape() {
+ let m = [0.0, -2.0, 2.0, 0.0, 100.0, 50.0];
+ let local = to_local(m, vec2(80.0, 70.0));
+ let back = to_canvas(m, local);
+ assert!((back - vec2(80.0, 70.0)).length() < 1e-3);
+ let picked = Picked::whole("c4".into(), vec![3, 12]);
+ assert_eq!(picked.addresses(), ["c4:s3", "c4:s12"]);
+ assert_eq!(picked.key(), "c4:3,12");
+ let cut = Picked {
+ cut: Some(vec![[0.0, 0.0], [5.0, 0.0], [5.0, 5.0]]),
+ ..picked.clone()
+ };
+ assert!(cut.key().starts_with("c4:3,12:cut"));
+ }
+
+ #[test]
+ fn hardness_and_curve_make_a_variant_but_feel_settings_do_not() {
+ let set = BrushSet::presets();
+ let ink = set.def("ink").unwrap();
+ let tuning = Tuning::of(ink);
+ assert_eq!(&tuning.shape(ink), ink);
+ let soft = set.def("soft").unwrap();
+ assert_eq!(&Tuning::of(soft).shape(soft), soft);
+ let feel = Tuning {
+ taper: [0.0, 0.0],
+ stabilizer: 0.0,
+ smoothing: 80.0,
+ ..tuning
+ };
+ assert_eq!(&feel.shape(ink), ink);
+ let harder = Tuning {
+ hardness: Some(1.0),
+ ..tuning
+ };
+ assert_eq!(harder.shape(ink).hardness(), Some(1.0));
+ let lighter = Tuning {
+ size_min: 0.3,
+ ..tuning
+ };
+ let shaped = lighter.shape(ink);
+ assert_eq!(shaped.dynamics.size.pressure.map(|c| c.min), Some(0.3));
+ let none = BTreeMap::new();
+ assert_eq!(pick_id("ink", &tuning.shape(ink), &none), "ink");
+ assert!(pick_id("ink", &shaped, &none).starts_with("ink-"));
+ }
+}
diff --git a/crates/app/src/editor/between.rs b/crates/app/src/editor/between.rs
new file mode 100644
index 0000000..6d94888
--- /dev/null
+++ b/crates/app/src/editor/between.rs
@@ -0,0 +1,865 @@
+use super::Editor;
+use super::tweens::{self, Span};
+use crate::jobs::{Spec, Tag};
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use anyhow::Result;
+use egui::{Color32, RichText, Sense, Stroke, pos2, vec2};
+use klad_core::doc::{Document, Kind, Loc};
+use klad_core::stroke::{Author, Mark};
+use klad_core::tween::{Spacing, made_hash};
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Request {
+ pub layers: Vec<String>,
+ pub from: u32,
+ pub to: u32,
+ pub count: Option<u32>,
+ pub spacing: String,
+ pub matching: String,
+ pub unpaired: String,
+ pub pairs: Vec<[u32; 2]>,
+}
+
+pub(super) fn args(r: &Request) -> Vec<String> {
+ let mut out = vec![
+ "--layers".to_string(),
+ r.layers.join(","),
+ "--from".into(),
+ r.from.to_string(),
+ "--to".into(),
+ r.to.to_string(),
+ "--spacing".into(),
+ r.spacing.clone(),
+ "--match".into(),
+ r.matching.clone(),
+ ];
+ if let Some(n) = r.count {
+ out.extend(["--count".to_string(), n.to_string()]);
+ }
+ if !r.unpaired.is_empty() && r.unpaired != "leave" {
+ out.extend(["--unpaired".to_string(), r.unpaired.clone()]);
+ }
+ if !r.pairs.is_empty() {
+ let pairs: Vec<String> = r.pairs.iter().map(|[a, b]| format!("s{a}=s{b}")).collect();
+ out.extend(["--pair".to_string(), pairs.join(",")]);
+ }
+ out
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) enum Line {
+ Layer {
+ name: String,
+ a: String,
+ b: String,
+ paired: u32,
+ touching: u32,
+ parts: Vec<String>,
+ },
+ Unpaired {
+ cel: String,
+ id: u32,
+ first: bool,
+ },
+ Clash(String),
+ Left {
+ what: String,
+ frame: Option<u32>,
+ },
+ Made {
+ cel: String,
+ frame: u32,
+ },
+ Kept {
+ cel: String,
+ count: u32,
+ },
+ Note(String),
+}
+
+fn layer_line(text: &str) -> Option<Line> {
+ let (name, rest) = text.split_once(": ")?;
+ let (a, rest) = rest.split_once(" -> ")?;
+ let (b, rest) = rest.split_once(", ")?;
+ let (paired, rest) = rest.split_once(" marks paired (")?;
+ let (_, rest) = rest.split_once(" flood fills)")?;
+ let (rest, touching) = match rest.rsplit_once(", ") {
+ Some((before, last)) if last.ends_with(" line ends kept touching") => {
+ (before, last.trim_end_matches(" line ends kept touching").parse().ok()?)
+ }
+ _ => (rest, 0),
+ };
+ let parts = rest
+ .strip_prefix(", by part first: ")
+ .map(|p| p.split(", ").map(String::from).collect())
+ .unwrap_or_default();
+ Some(Line::Layer {
+ name: name.to_string(),
+ a: a.to_string(),
+ b: b.to_string(),
+ paired: paired.parse().ok()?,
+ touching,
+ parts,
+ })
+}
+
+fn unpaired_items(list: &str) -> Vec<Line> {
+ list.split("), ")
+ .map(|item| item.trim_end_matches(')'))
+ .filter_map(|item| {
+ let (mark, why) = item.split_once(" (")?;
+ match why {
+ "only in the first key" | "only in the second key" => {
+ let (cel, id) = klad_core::markedit::parse_address(mark)?;
+ Some(Line::Unpaired {
+ cel: cel.to_string(),
+ id,
+ first: why.contains("first"),
+ })
+ }
+ _ => Some(Line::Clash(format!("{mark} ({why})"))),
+ }
+ })
+ .collect()
+}
+
+fn frame_in(text: &str) -> Option<u32> {
+ let (_, rest) = text.split_once("at frame ")?;
+ rest.split(|c: char| !c.is_ascii_digit()).next()?.parse().ok()
+}
+
+pub(super) fn report(text: &str) -> Vec<Line> {
+ text.lines()
+ .flat_map(|raw| {
+ let line = raw.trim();
+ if let Some(rest) = line.strip_prefix("unpaired, ") {
+ return rest
+ .split_once(": ")
+ .map(|(_, list)| unpaired_items(list))
+ .unwrap_or_default();
+ }
+ if let Some(list) = line.strip_prefix("fills left out: ") {
+ return list
+ .split("; ")
+ .map(|what| Line::Left {
+ what: what.to_string(),
+ frame: frame_in(what),
+ })
+ .collect();
+ }
+ if let Some((cel, rest)) = line.split_once(" at frame ")
+ && rest.contains(" (t ")
+ && !cel.contains(' ')
+ {
+ return frame_in(line)
+ .map(|frame| Line::Made {
+ cel: cel.to_string(),
+ frame,
+ })
+ .into_iter()
+ .collect();
+ }
+ if let Some((cel, rest)) = line.split_once(": ")
+ && rest.ends_with("drawn by hand kept on top")
+ {
+ let count = rest.split(' ').next().and_then(|n| n.parse().ok()).unwrap_or(0);
+ return vec![Line::Kept {
+ cel: cel.to_string(),
+ count,
+ }];
+ }
+ if let Some(layer) = layer_line(line) {
+ return vec![layer];
+ }
+ let skip = line.is_empty()
+ || ["rev ", "added ", "changed ", "removed "]
+ .iter()
+ .any(|p| line.starts_with(p));
+ match skip {
+ true => Vec::new(),
+ false => vec![Line::Note(line.to_string())],
+ }
+ })
+ .collect()
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Pick {
+ pub cel: String,
+ pub id: u32,
+ pub first: bool,
+ pub partner_cel: String,
+ pub partner_frame: u32,
+}
+
+pub(super) fn pair_from(pick: &Pick, partner: u32) -> [u32; 2] {
+ match pick.first {
+ true => [pick.id, partner],
+ false => [partner, pick.id],
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Status {
+ Remake,
+ Drawn(usize),
+ Edited,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct RedoRow {
+ pub cel: String,
+ pub layer: String,
+ pub frame: u32,
+ pub status: Status,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Choice {
+ Keep,
+ Force,
+ Leave,
+}
+
+pub(super) fn redo_rows(
+ doc: &Document,
+ span: Option<(u32, u32)>,
+ layers: &[String],
+ read: impl Fn(&str, &str) -> Result<Vec<Mark>>,
+) -> Result<Vec<RedoRow>> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Paint && (layers.is_empty() || layers.contains(&l.id)))
+ .flat_map(|l| l.cels().iter().map(move |c| (l, c)))
+ .filter(|(_, c)| c.tween.is_some() && span.is_none_or(|(a, b)| c.frame >= a && c.frame <= b))
+ .map(|(l, c)| {
+ let marks = read(&l.id, &c.id)?;
+ let made = c.tween.as_ref().map(|t| t.made.clone()).unwrap_or_default();
+ let hand = marks.iter().filter(|m| m.author() == Author::Human).count();
+ let status = match (made_hash(&marks) == made, hand) {
+ (true, _) => Status::Remake,
+ (false, 0) => Status::Edited,
+ (false, n) => Status::Drawn(n),
+ };
+ Ok(RedoRow {
+ cel: c.id.clone(),
+ layer: l.id.clone(),
+ frame: c.frame,
+ status,
+ })
+ })
+ .collect()
+}
+
+pub(super) fn default_choice(status: Status) -> Choice {
+ match status {
+ Status::Remake => Choice::Force,
+ Status::Drawn(_) => Choice::Keep,
+ Status::Edited => Choice::Leave,
+ }
+}
+
+pub(super) fn redo_args(rows: &[RedoRow], choices: &BTreeMap<String, Choice>) -> Option<Vec<String>> {
+ let choice = |r: &RedoRow| choices.get(&r.cel).copied().unwrap_or(default_choice(r.status));
+ let only: Vec<&str> = rows
+ .iter()
+ .filter(|r| r.status == Status::Remake || choice(r) != Choice::Leave)
+ .map(|r| r.cel.as_str())
+ .collect();
+ if only.is_empty() {
+ return None;
+ }
+ let listed = |want: Choice| -> Vec<&str> {
+ rows.iter()
+ .filter(|r| r.status != Status::Remake && choice(r) == want)
+ .map(|r| r.cel.as_str())
+ .collect()
+ };
+ let mut out = vec!["--redo".to_string(), "--only".into(), only.join(",")];
+ [("--keep-cels", Choice::Keep), ("--force-cels", Choice::Force)]
+ .into_iter()
+ .for_each(|(flag, want)| {
+ let cels = listed(want);
+ if !cels.is_empty() {
+ out.extend([flag.to_string(), cels.join(",")]);
+ }
+ });
+ Some(out)
+}
+
+#[derive(Default)]
+pub(super) struct Between {
+ pub last: Option<Request>,
+ pub report: Vec<Line>,
+ pub pick: Option<Pick>,
+ pub redo: Option<Vec<RedoRow>>,
+ pub choices: BTreeMap<String, Choice>,
+}
+
+impl Editor {
+ fn request_from(&self, span: &Span) -> Option<Request> {
+ let (from, to) = tweens::keys(&self.scene.bundle.doc, span)?;
+ let ask = &self.timeline.ask;
+ Some(Request {
+ layers: span.rows.clone(),
+ from,
+ to,
+ count: (!ask.every_frame).then_some(ask.count),
+ spacing: ask.spacing.clone(),
+ matching: ask.matching.clone(),
+ unpaired: ask.unpaired.clone(),
+ pairs: self
+ .between
+ .last
+ .as_ref()
+ .filter(|l| (l.from, l.to) == (from, to) && l.layers == span.rows)
+ .map(|l| l.pairs.clone())
+ .unwrap_or_default(),
+ })
+ }
+
+ pub(super) fn make_inbetweens(&mut self, request: Request) {
+ let what = format!("in-betweens of frames {} and {}", request.from, request.to);
+ self.between.last = Some(request.clone());
+ self.between.report.clear();
+ self.between.redo = None;
+ self.run_inbetween_args(args(&request), what);
+ }
+
+ pub(super) fn check_redo(&mut self) -> Result<()> {
+ let (span, layers) = match &self.timeline.span {
+ Some(s) => (Some((s.from, s.to)), s.rows.clone()),
+ None => (None, Vec::new()),
+ };
+ let bundle = &self.scene.bundle;
+ let rows = redo_rows(&bundle.doc, span, &layers, |l, c| bundle.read_marks(l, c))?;
+ self.between.choices.clear();
+ self.between.redo = Some(rows);
+ self.windows.between = true;
+ Ok(())
+ }
+
+ pub(super) fn run_inbetween_args(&mut self, extra: Vec<String>, what: String) {
+ if self.jobs.busy(Tag::Inbetween) {
+ self.say(Tone::Refused, "in-betweens are already being made; wait for them");
+ return;
+ }
+ let mut full = vec![
+ "inbetween".to_string(),
+ self.scene.bundle.root.to_string_lossy().to_string(),
+ ];
+ full.extend(extra);
+ self.start_job(Spec {
+ tag: Tag::Inbetween,
+ name: what,
+ exe: PathBuf::new(),
+ args: full,
+ env: Vec::new(),
+ reruns: 3,
+ summary: |out, _| tweens::summary(out),
+ failure: |_, err| tweens::failure(err),
+ });
+ }
+
+ pub(super) fn tend_pick(&mut self) -> Result<()> {
+ let Some(pick) = self.between.pick.clone() else {
+ return Ok(());
+ };
+ let Some((cel, id)) = self
+ .picked
+ .as_ref()
+ .filter(|p| p.cel == pick.partner_cel && p.ids.len() == 1)
+ .map(|p| (p.cel.clone(), p.ids[0]))
+ else {
+ return Ok(());
+ };
+ self.between.pick = None;
+ self.picked = None;
+ let Some(mut request) = self.between.last.clone() else {
+ return Ok(());
+ };
+ let pair = pair_from(&pick, id);
+ request.pairs.retain(|p| p[0] != pair[0] && p[1] != pair[1]);
+ request.pairs.push(pair);
+ self.say(
+ Tone::Done,
+ format!(
+ "{}:s{} pairs with {cel}:s{id}; making the in-betweens again",
+ pick.cel, pick.id
+ ),
+ );
+ self.make_inbetweens(request);
+ Ok(())
+ }
+
+ fn spacing_chart(ui: &mut egui::Ui, spacing: &str, count: usize, (a, b): (u32, u32)) {
+ let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().min(320.0), 44.0), Sense::hover());
+ let painter = ui.painter_at(rect);
+ let (left, right, y) = (rect.left() + 14.0, rect.right() - 14.0, rect.center().y);
+ let ink = Stroke::new(1.5, theme::TEXT);
+ painter.line_segment([pos2(left, y), pos2(right, y)], ink);
+ [(left, a), (right, b)].into_iter().for_each(|(x, f)| {
+ painter.line_segment([pos2(x, y - 12.0), pos2(x, y + 12.0)], Stroke::new(2.5, theme::TEXT));
+ painter.text(
+ pos2(x, rect.bottom() - 2.0),
+ egui::Align2::CENTER_BOTTOM,
+ f.to_string(),
+ egui::FontId::proportional(11.0),
+ theme::WEAK,
+ );
+ });
+ let ts = Spacing::parse(spacing).map(|s| s.ts(count)).unwrap_or_default();
+ ts.iter().for_each(|t| {
+ let x = left + (right - left) * t;
+ painter.line_segment([pos2(x, y - 7.0), pos2(x, y + 7.0)], Stroke::new(1.5, theme::ACCENT));
+ });
+ }
+
+ pub(super) fn between_window(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let span = self.timeline.span.clone();
+ let request = span.as_ref().and_then(|s| self.request_from(s));
+ match (&span, &request) {
+ (Some(span), Some(r)) => {
+ let first = span.rows.first().cloned().unwrap_or_default();
+ let key_cels: Vec<Option<String>> = [r.from, r.to]
+ .iter()
+ .map(|f| {
+ self.scene
+ .bundle
+ .doc
+ .layer(&first)
+ .and_then(|l| l.content_at(*f))
+ .map(|c| c.link.clone().unwrap_or_else(|| c.id.clone()))
+ })
+ .collect();
+ ui.horizontal(|ui| {
+ [r.from, r.to].iter().zip(&key_cels).for_each(|(f, cel)| {
+ ui.vertical(|ui| {
+ match cel.as_ref().and_then(|c| self.thumb(ui.ctx(), c)) {
+ Some(t) => {
+ ui.add(egui::Image::new(&t).fit_to_exact_size(vec2(96.0, 68.0)));
+ }
+ None => {
+ let (rect, _) = ui.allocate_exact_size(vec2(96.0, 68.0), Sense::hover());
+ ui.painter().rect_stroke(
+ rect,
+ 2.0,
+ Stroke::new(1.0, theme::WEAK),
+ egui::StrokeKind::Inside,
+ );
+ ui.painter().text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ format!("go to {f}\nto see it"),
+ egui::FontId::proportional(11.0),
+ theme::WEAK,
+ );
+ }
+ }
+ ui.label(format!("key at {f}: {}", cel.clone().unwrap_or_default()));
+ });
+ });
+ });
+ let room = r.to - r.from - 1;
+ let ask = &mut self.timeline.ask;
+ ask.count = ask.count.clamp(1, room.max(1));
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut ask.every_frame, "one on every frame")
+ .hint("an in-between on each frame between the keys");
+ if !ask.every_frame {
+ let label = ui.label("count");
+ ui.add(egui::DragValue::new(&mut ask.count).range(1..=room.max(1)))
+ .labelled_by(label.id)
+ .hint("how many in-betweens, spread over the frames between the keys");
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("spacing");
+ ["even", "in", "out", "in-out"].iter().for_each(|s| {
+ ui.selectable_value(&mut ask.spacing, s.to_string(), *s)
+ .hint("in: bunched near the first key; out: near the second");
+ });
+ });
+ let count = if ask.every_frame { room } else { ask.count } as usize;
+ let spacing = ask.spacing.clone();
+ Self::spacing_chart(ui, &spacing, count, (r.from, r.to));
+ let ask = &mut self.timeline.ask;
+ ui.horizontal(|ui| {
+ ui.label("pair by");
+ [("id", "id"), ("order", "order"), ("near", "nearest shape")]
+ .iter()
+ .for_each(|(key, label)| {
+ ui.selectable_value(&mut ask.matching, key.to_string(), *label)
+ .hint("how marks without a shared part find their partner");
+ });
+ });
+ ui.horizontal(|ui| {
+ ui.label("one key only");
+ ["leave", "pop", "fade", "draw-on"].iter().for_each(|m| {
+ ui.selectable_value(&mut ask.unpaired, m.to_string(), *m)
+ .hint("marks in one key only: left out, popping in or out halfway, fading, or drawn on");
+ });
+ });
+ let parts = self.shared_parts(&first, &key_cels);
+ if !parts.is_empty() {
+ ui.label(RichText::new(format!("parts pair first: {}", parts.join(", "))).color(theme::WEAK));
+ }
+ if !r.pairs.is_empty() {
+ let listed: Vec<String> = r.pairs.iter().map(|[a, b]| format!("s{a}=s{b}")).collect();
+ ui.label(RichText::new(format!("pairs you chose: {}", listed.join(", "))).color(theme::WEAK));
+ }
+ if ui
+ .add_enabled(
+ !self.jobs.busy(Tag::Inbetween),
+ egui::Button::new("make the in-betweens"),
+ )
+ .hint("runs klad inbetween with these settings; you can keep drawing meanwhile")
+ .clicked()
+ {
+ self.make_inbetweens(r.clone());
+ }
+ }
+ _ => {
+ ui.label(
+ "select from one drawing to the frame where another starts, on a paint layer: drag over the cells",
+ );
+ }
+ }
+ self.report_rows(ui)?;
+ ui.separator();
+ self.redo_rows_ui(ui)
+ }
+
+ fn shared_parts(&self, layer: &str, cels: &[Option<String>]) -> Vec<String> {
+ let parts = |cel: &Option<String>| -> BTreeMap<String, Vec<u32>> {
+ match cel.as_ref().and_then(|c| self.scene.bundle.doc.locate(c)) {
+ Some(Loc::Cel(path, c)) => self.scene.bundle.doc.layer_at(&path).cels()[c].parts.clone(),
+ _ => BTreeMap::new(),
+ }
+ };
+ let _ = layer;
+ match cels {
+ [a, b] => {
+ let (pa, pb) = (parts(a), parts(b));
+ pa.keys().filter(|k| pb.contains_key(*k)).cloned().collect()
+ }
+ _ => Vec::new(),
+ }
+ }
+
+ fn report_rows(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ if self.between.report.is_empty() {
+ return Ok(());
+ }
+ ui.separator();
+ ui.label(RichText::new("the last run").strong());
+ let mut go = None;
+ let mut pick = None;
+ let made: Vec<String> = self
+ .between
+ .report
+ .iter()
+ .filter_map(|l| match l {
+ Line::Made { cel, frame } => Some(format!("{cel} at {frame}")),
+ _ => None,
+ })
+ .collect();
+ let last = self.between.last.clone();
+ self.between.report.clone().into_iter().for_each(|line| match line {
+ Line::Layer {
+ name,
+ a,
+ b,
+ paired,
+ touching,
+ parts,
+ } => {
+ let by = if parts.is_empty() {
+ String::new()
+ } else {
+ format!(", by part: {}", parts.join(", "))
+ };
+ ui.label(format!(
+ "{name}: {a} to {b}, {paired} pairs{by}, {touching} line ends kept touching"
+ ));
+ }
+ Line::Unpaired { cel, id, first } => {
+ let side = if first { "first" } else { "second" };
+ if ui
+ .button(format!("{cel}:s{id}, only in the {side} key: pick its partner"))
+ .hint(
+ "then click the stroke it should become with S; the in-betweens are made again with that pair",
+ )
+ .clicked()
+ && let Some(r) = &last
+ {
+ let partner_frame = if first { r.to } else { r.from };
+ let layer = r.layers.first().cloned().unwrap_or_default();
+ let partner_cel = self
+ .scene
+ .bundle
+ .doc
+ .layer(&layer)
+ .and_then(|l| l.content_at(partner_frame))
+ .map(|c| c.link.clone().unwrap_or_else(|| c.id.clone()))
+ .unwrap_or_default();
+ pick = Some(Pick {
+ cel,
+ id,
+ first,
+ partner_cel,
+ partner_frame,
+ });
+ }
+ }
+ Line::Clash(text) => {
+ ui.label(RichText::new(format!("not paired: {text}")).color(theme::WEAK));
+ }
+ Line::Left { what, frame } => {
+ if ui
+ .button(format!("fill left out: {what}"))
+ .hint("go to that frame")
+ .clicked()
+ {
+ go = frame;
+ }
+ }
+ Line::Kept { cel, count } => {
+ ui.label(format!("{cel}: {count} hand-drawn marks kept on top"));
+ }
+ Line::Made { .. } => {}
+ Line::Note(text) => {
+ ui.label(RichText::new(text).color(theme::WEAK));
+ }
+ });
+ if !made.is_empty() {
+ ui.label(RichText::new(format!("made: {}", made.join(", "))).color(theme::WEAK));
+ }
+ if let Some(p) = pick {
+ self.say(
+ Tone::Info,
+ format!(
+ "now click the partner of {}:s{} on frame {} (the stroke tool is on)",
+ p.cel, p.id, p.partner_frame
+ ),
+ );
+ go = Some(p.partner_frame);
+ self.tool = super::Tool::Strokes;
+ self.picked = None;
+ self.between.pick = Some(p);
+ }
+ if let Some(p) = self.between.pick.clone() {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(format!("picking the partner of {}:s{}", p.cel, p.id)).color(theme::ACCENT));
+ if ui.button("stop").hint("stop picking a partner").clicked() {
+ self.between.pick = None;
+ }
+ });
+ }
+ if let Some(frame) = go {
+ self.go_to(frame)?;
+ }
+ Ok(())
+ }
+
+ fn redo_rows_ui(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ if ui
+ .button("check what a redo would remake (after a key changed)")
+ .hint("lists the in-betweens in the selection (or all) and those drawn on since they were made")
+ .clicked()
+ {
+ self.check_redo()?;
+ }
+ let Some(rows) = self.between.redo.clone() else {
+ return Ok(());
+ };
+ if rows.is_empty() {
+ ui.label("no in-betweens here");
+ return Ok(());
+ }
+ rows.iter().for_each(|r| {
+ ui.horizontal(|ui| {
+ ui.label(format!("{} at {} on {}", r.cel, r.frame, r.layer));
+ match r.status {
+ Status::Remake => {
+ ui.label(RichText::new("remade").color(theme::WEAK));
+ }
+ status => {
+ let what = match status {
+ Status::Drawn(n) => format!("{n} marks drawn by hand"),
+ _ => "edited since it was made".to_string(),
+ };
+ ui.label(RichText::new(what).color(Color32::from_rgb(240, 190, 90)));
+ let choice = self
+ .between
+ .choices
+ .entry(r.cel.clone())
+ .or_insert(default_choice(status));
+ if matches!(status, Status::Drawn(_)) {
+ ui.selectable_value(choice, Choice::Keep, "keep them on top").hint(
+ "remake the in-between and keep the hand-drawn marks over it, moved with their line",
+ );
+ }
+ ui.selectable_value(choice, Choice::Force, "in-between them too")
+ .hint("remake it from the keys; marks drawn on it are replaced");
+ ui.selectable_value(choice, Choice::Leave, "leave it")
+ .hint("this in-between stays as it is");
+ }
+ }
+ });
+ });
+ let args = redo_args(&rows, &self.between.choices);
+ if ui
+ .add_enabled(
+ args.is_some() && !self.jobs.busy(Tag::Inbetween),
+ egui::Button::new("redo them"),
+ )
+ .hint("one history step for all of them")
+ .clicked()
+ && let Some(args) = args
+ {
+ self.between.redo = None;
+ self.between.report.clear();
+ self.run_inbetween_args(args, "redoing in-betweens".into());
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const RUN: &str = "lines: lines0 -> lines2, 15 marks paired (0 flood fills), by part first: body, near leg, 16 line ends kept touching
+colour: col0 -> col6, 2 marks paired (2 flood fills)
+ unpaired, left out: b6:s3 (only in the second key), a0:s5 (only in the first key), a0:s2 and b6:s4 (one is a stroke or lasso fill, the other not)
+ fills left out: col0:s2 at frame 4: its seed lands on a line; col0:s1 at frame 5: it leaked (40 px where the keys have 10 and 12)
+ c11 at frame 1 (t 0.17) on lines
+ c12 at frame 2 (t 0.33) on lines
+ c14: 1 mark drawn by hand kept on top
+2 in-betweens on 2 frames in 120 ms (60 ms per frame)
+rev 5";
+
+ #[test]
+ fn the_panel_builds_the_cli_arguments() {
+ let r = Request {
+ layers: vec!["lines".into(), "colour".into()],
+ from: 0,
+ to: 6,
+ count: Some(2),
+ spacing: "in-out".into(),
+ matching: "near".into(),
+ unpaired: "fade".into(),
+ pairs: vec![[3, 7], [5, 9]],
+ };
+ assert_eq!(
+ args(&r).join(" "),
+ "--layers lines,colour --from 0 --to 6 --spacing in-out --match near --count 2 --unpaired fade --pair s3=s7,s5=s9"
+ );
+ let plain = Request {
+ count: None,
+ unpaired: "leave".into(),
+ pairs: Vec::new(),
+ ..r
+ };
+ assert!(
+ !args(&plain)
+ .iter()
+ .any(|a| a == "--count" || a == "--unpaired" || a == "--pair")
+ );
+ }
+
+ #[test]
+ fn the_cli_report_becomes_rows_and_two_clicks_make_a_pair() {
+ let rows = report(RUN);
+ assert_eq!(
+ rows[0],
+ Line::Layer {
+ name: "lines".into(),
+ a: "lines0".into(),
+ b: "lines2".into(),
+ paired: 15,
+ touching: 16,
+ parts: vec!["body".into(), "near leg".into()],
+ }
+ );
+ assert!(matches!(&rows[1], Line::Layer { touching: 0, parts, .. } if parts.is_empty()));
+ assert_eq!(
+ rows[2],
+ Line::Unpaired {
+ cel: "b6".into(),
+ id: 3,
+ first: false
+ }
+ );
+ assert_eq!(
+ rows[3],
+ Line::Unpaired {
+ cel: "a0".into(),
+ id: 5,
+ first: true
+ }
+ );
+ assert!(matches!(&rows[4], Line::Clash(t) if t.contains("a0:s2 and b6:s4")));
+ assert!(matches!(&rows[5], Line::Left { frame: Some(4), .. }));
+ assert!(matches!(&rows[6], Line::Left { frame: Some(5), what } if what.contains("leaked")));
+ assert_eq!(
+ rows[7],
+ Line::Made {
+ cel: "c11".into(),
+ frame: 1
+ }
+ );
+ assert_eq!(
+ rows[9],
+ Line::Kept {
+ cel: "c14".into(),
+ count: 1
+ }
+ );
+ assert!(matches!(&rows[10], Line::Note(t) if t.starts_with("2 in-betweens")));
+ assert_eq!(rows.len(), 11);
+ let second = Pick {
+ cel: "b6".into(),
+ id: 3,
+ first: false,
+ partner_cel: "a0".into(),
+ partner_frame: 0,
+ };
+ assert_eq!(pair_from(&second, 8), [8, 3]);
+ let first = Pick { first: true, ..second };
+ assert_eq!(pair_from(&first, 8), [3, 8]);
+ }
+
+ #[test]
+ fn a_redo_lists_what_it_remakes_and_takes_a_choice_per_drawn_in_between() {
+ let row = |cel: &str, status| RedoRow {
+ cel: cel.into(),
+ layer: "lines".into(),
+ frame: 1,
+ status,
+ };
+ let rows = vec![
+ row("c11", Status::Remake),
+ row("c12", Status::Drawn(2)),
+ row("c13", Status::Edited),
+ row("c14", Status::Drawn(1)),
+ ];
+ let mut choices = BTreeMap::new();
+ assert_eq!(
+ redo_args(&rows, &choices).unwrap().join(" "),
+ "--redo --only c11,c12,c14 --keep-cels c12,c14"
+ );
+ choices.insert("c13".to_string(), Choice::Force);
+ choices.insert("c14".to_string(), Choice::Leave);
+ assert_eq!(
+ redo_args(&rows, &choices).unwrap().join(" "),
+ "--redo --only c11,c12,c13 --keep-cels c12 --force-cels c13"
+ );
+ let left = vec![row("c13", Status::Edited)];
+ assert_eq!(redo_args(&left, &BTreeMap::new()), None);
+ }
+}
diff --git a/crates/app/src/editor/brushwin.rs b/crates/app/src/editor/brushwin.rs
new file mode 100644
index 0000000..aed1173
--- /dev/null
+++ b/crates/app/src/editor/brushwin.rs
@@ -0,0 +1,657 @@
+use super::Editor;
+use super::options;
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use anyhow::{Result, anyhow, bail};
+use egui::{Color32, RichText, TextureHandle, TextureOptions};
+use klad_core::brushes::{AngleDef, BrushDef, ColorDef, Curve, DualDef, GrainDef, PaintDef, Paper, TIP_IMAGES, TipDef};
+use std::path::Path;
+
+pub(super) const PREVIEW: (u32, u32) = (320, 84);
+
+#[derive(Default)]
+pub(super) struct BrushWindow {
+ pub name: String,
+ pub picture_path: String,
+ preview: Option<(u64, TextureHandle)>,
+}
+
+fn slider(ui: &mut egui::Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, text: &str, hint: &str) -> bool {
+ ui.add(egui::Slider::new(value, range).text(text)).hint(hint).changed()
+}
+
+fn curve_of(c: Option<Curve>) -> Curve {
+ c.unwrap_or(Curve {
+ min: 1.0,
+ max: 1.0,
+ gamma: 1.0,
+ })
+}
+
+fn plain(c: Curve) -> Option<Curve> {
+ (c.min != 1.0 || c.max != 1.0 || c.gamma != 1.0).then_some(c)
+}
+
+pub(super) fn slug(name: &str) -> String {
+ let words: Vec<String> = name
+ .split(|c: char| !c.is_ascii_alphanumeric())
+ .filter(|w| !w.is_empty())
+ .map(str::to_lowercase)
+ .collect();
+ words.join("-")
+}
+
+fn tip_name(tip: &TipDef) -> String {
+ match tip {
+ TipDef::Round { .. } => "round".into(),
+ TipDef::Chalk { .. } => "chalk".into(),
+ TipDef::Image { image } => image.clone(),
+ }
+}
+
+fn tip_choice(ui: &mut egui::Ui, salt: &str, tip: &mut TipDef, pictures: &[String], hint: &str) -> bool {
+ let mut changed = false;
+ egui::ComboBox::from_id_salt(salt)
+ .selected_text(tip_name(tip))
+ .show_ui(ui, |ui| {
+ let mut pick = |ui: &mut egui::Ui, label: &str, next: TipDef| {
+ if ui.selectable_label(tip_name(tip) == label, label).clicked() && tip_name(tip) != label {
+ *tip = next;
+ changed = true;
+ }
+ };
+ pick(ui, "round", TipDef::Round { hardness: 0.8 });
+ pick(ui, "chalk", TipDef::Chalk { seed: 7 });
+ pictures.iter().for_each(|name| {
+ pick(ui, name, TipDef::Image { image: name.clone() });
+ });
+ })
+ .response
+ .hint(hint);
+ match tip {
+ TipDef::Round { hardness } => changed |= slider(ui, hardness, 0.0..=1.0, "hardness", "soft to hard edge"),
+ TipDef::Chalk { seed } => {
+ changed |= ui
+ .add(egui::DragValue::new(seed).range(0..=9999).prefix("seed "))
+ .hint("which chalk grain")
+ .changed()
+ }
+ TipDef::Image { .. } => {}
+ }
+ changed
+}
+
+impl Editor {
+ #[cfg(test)]
+ pub(super) fn brush_window_preview_key(&self) -> Option<u64> {
+ self.brush_window.preview.as_ref().map(|(k, _)| *k)
+ }
+
+ pub(super) fn draft(&self) -> Result<BrushDef> {
+ match &self.custom {
+ Some(def) => Ok(def.clone()),
+ None => Ok(self.shaped()?.1),
+ }
+ }
+
+ fn picture_names(&self) -> Vec<String> {
+ TIP_IMAGES
+ .iter()
+ .map(|n| n.to_string())
+ .chain(self.brushes.pictures().keys().cloned())
+ .collect()
+ }
+
+ pub(super) fn add_brush_picture(&mut self, name: &str, bytes: &[u8]) -> Result<()> {
+ klad_core::brushes::valid_image(name)?;
+ let picture = klad_brush::images::decode(bytes)?;
+ let path = self
+ .scene
+ .bundle
+ .root
+ .join("brushes")
+ .join("images")
+ .join(format!("{name}.png"));
+ if path.exists() && std::fs::read(&path)? != bytes {
+ bail!(
+ "a picture {name} is in this drawing already with other pixels; brushes using it would change, so give it another name"
+ );
+ }
+ std::fs::create_dir_all(path.parent().ok_or_else(|| anyhow!("no folder"))?)?;
+ klad_core::bundle::write_atomic(&path, bytes)?;
+ self.brushes.add_picture(name, picture);
+ self.say(
+ Tone::Done,
+ format!("picture {name} added: pick it as a tip or a texture"),
+ );
+ Ok(())
+ }
+
+ fn add_picture_from(&mut self, path: &Path) -> Result<()> {
+ let name = slug(path.file_stem().and_then(|s| s.to_str()).unwrap_or_default());
+ if name.is_empty() {
+ bail!("{} has no usable name", path.display());
+ }
+ let bytes = std::fs::read(path)?;
+ self.add_brush_picture(&name, &bytes)
+ }
+
+ pub(super) fn save_brush(&mut self) -> Result<()> {
+ let mut def = self.draft()?;
+ let id = slug(&self.brush_window.name);
+ if id.is_empty() {
+ bail!("give the brush a name first");
+ }
+ def.name = self.brush_window.name.trim().to_string();
+ match self.scene.bundle.brush(&id)? {
+ Some(known) if known == def => {}
+ Some(_) => bail!(
+ "a brush {id} is in this drawing already with other settings; strokes keep their brush, so pick another name"
+ ),
+ None => {
+ if klad_core::brushes::library(&id).is_some() {
+ bail!("{id} is a library brush; pick another name");
+ }
+ self.scene.bundle.embed_brush(&id, &def)?;
+ }
+ }
+ self.embedded.insert(id.clone(), def.clone());
+ self.brushes.insert(&id, def);
+ self.pick(&id);
+ self.say(Tone::Done, format!("brush {id} saved in this drawing"));
+ Ok(())
+ }
+
+ fn preview(&mut self, ctx: &egui::Context, def: &BrushDef) -> Option<TextureHandle> {
+ let key = def.fingerprint() ^ self.brushes.fingerprint();
+ if let Some((k, texture)) = &self.brush_window.preview
+ && *k == key
+ {
+ return Some(texture.clone());
+ }
+ let mut set = self.brushes.clone();
+ set.insert("draft", def.clone());
+ let raster = options::sample_sized(&set, "draft", PREVIEW, 28.0).ok()?;
+ let image = options::image_of(&raster, PREVIEW, Color32::from_gray(38));
+ let texture = ctx.load_texture("brush preview", image, TextureOptions::LINEAR);
+ self.brush_window.preview = Some((key, texture.clone()));
+ Some(texture)
+ }
+
+ pub(super) fn brush_window_ui(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let dropped: Vec<std::path::PathBuf> = ui.ctx().input(|i| {
+ i.raw
+ .dropped_files
+ .iter()
+ .map(|f| f.path().to_path_buf())
+ .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("png")))
+ .collect()
+ });
+ dropped.iter().try_for_each(|p| self.add_picture_from(p))?;
+ let mut def = self.draft()?;
+ let pictures = self.picture_names();
+ if let Some(texture) = self.preview(ui.ctx(), &def) {
+ ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(PREVIEW.0 as f32, PREVIEW.1 as f32)));
+ }
+ let mut changed = false;
+ ui.horizontal_wrapped(|ui| {
+ ui.set_max_width(380.0);
+ let mut dual = def.dual.is_some();
+ if ui
+ .checkbox(&mut dual, RichText::new("dual tip").strong())
+ .hint("a second tip, scattered, cuts the first into a broken, bristly mark")
+ .changed()
+ {
+ def.dual = dual.then(|| DualDef {
+ tip: TipDef::Image {
+ image: "bristle-round".into(),
+ },
+ size: 0.5,
+ scatter: 1.0,
+ count: 3,
+ });
+ changed = true;
+ }
+ let mut textured = def.grain.is_some();
+ if ui
+ .checkbox(&mut textured, RichText::new("texture").strong())
+ .hint("paper or a picture under the paint, fixed on the canvas")
+ .changed()
+ {
+ def.grain = textured.then_some(GrainDef {
+ paper: Some(Paper { seed: 23, feature: 4 }),
+ image: None,
+ strength: 0.4,
+ scale: 1.0,
+ contrast: 1.0,
+ pressure: 0.0,
+ });
+ changed = true;
+ }
+ let mut colour = def.color.is_some();
+ if ui
+ .checkbox(&mut colour, RichText::new("colour dynamics").strong())
+ .hint("colour that varies per dab, per stroke, with pressure or along the stroke")
+ .changed()
+ {
+ def.color = colour.then(ColorDef::default);
+ changed = true;
+ }
+ });
+ ui.horizontal(|ui| {
+ let kind = match def.paint {
+ None => 0,
+ Some(PaintDef::Wet { .. }) => 1,
+ Some(PaintDef::Smudge { .. }) => 2,
+ Some(PaintDef::Blend { .. }) => 3,
+ };
+ [
+ (0, "dry", "lays its own colour"),
+ (1, "wet", "picks up the colour under it and mixes it in"),
+ (2, "smudge", "pulls the paint along"),
+ (3, "blend", "softens what is under it"),
+ ]
+ .iter()
+ .for_each(|(k, label, hint)| {
+ if ui.selectable_label(kind == *k, *label).hint(*hint).clicked() && kind != *k {
+ def.paint = match k {
+ 1 => Some(PaintDef::Wet {
+ wetness: 0.6,
+ pickup: 0.5,
+ dilution: 0.2,
+ }),
+ 2 => Some(PaintDef::Smudge { strength: 0.7 }),
+ 3 => Some(PaintDef::Blend { strength: 0.5 }),
+ _ => None,
+ };
+ changed = true;
+ }
+ });
+ });
+ egui::ScrollArea::vertical().max_height(460.0).show(ui, |ui| {
+ ui.set_max_width(380.0);
+ ui.label(RichText::new("tip").strong());
+ ui.vertical(|ui| {
+ changed |= tip_choice(
+ ui,
+ "brush tip",
+ &mut def.tip,
+ &pictures,
+ "the shape each dab stamps: round, chalk or a picture",
+ );
+ });
+ ui.vertical(|ui| {
+ changed |= slider(
+ ui,
+ &mut def.spacing,
+ 0.01..=2.0,
+ "spacing",
+ "the gap between dabs, as a part of the size",
+ );
+ changed |= slider(ui, &mut def.roundness, 0.05..=1.0, "roundness", "squash the tip");
+ });
+ ui.vertical(|ui| {
+ let mut follow = def.angle == AngleDef::Follow;
+ let mut tilt = def.angle == AngleDef::Tilt;
+ if ui
+ .checkbox(&mut follow, "turn with the stroke")
+ .hint("the tip turns along the stroke")
+ .changed()
+ {
+ def.angle = if follow { AngleDef::Follow } else { AngleDef::Fixed(0.0) };
+ changed = true;
+ }
+ if ui
+ .checkbox(&mut tilt, "turn with the pen's tilt")
+ .hint("the tip turns with the pen's tilt")
+ .changed()
+ {
+ def.angle = if tilt { AngleDef::Tilt } else { AngleDef::Fixed(0.0) };
+ changed = true;
+ }
+ if let AngleDef::Fixed(angle) = &mut def.angle {
+ changed |= slider(ui, angle, -3.15..=3.15, "angle", "the tip's fixed angle, in radians");
+ }
+ });
+ ui.vertical(|ui| {
+ changed |= slider(
+ ui,
+ &mut def.jitter.size,
+ 0.0..=1.0,
+ "size jitter",
+ "each dab's size varies by up to this much",
+ );
+ changed |= slider(
+ ui,
+ &mut def.jitter.angle,
+ 0.0..=6.3,
+ "angle jitter",
+ "each dab turns by up to this much",
+ );
+ changed |= slider(
+ ui,
+ &mut def.jitter.scatter,
+ 0.0..=4.0,
+ "scatter",
+ "dabs stray across the stroke by up to this many sizes",
+ );
+ });
+ ui.separator();
+ ui.label(RichText::new("pressure and tilt").strong());
+ ui.vertical(|ui| {
+ let mut size = curve_of(def.dynamics.size.pressure);
+ let mut flow = curve_of(def.dynamics.flow.pressure);
+ let mut opacity = curve_of(def.dynamics.opacity.pressure);
+ let a = slider(
+ ui,
+ &mut size.min,
+ 0.0..=1.0,
+ "size at the lightest press",
+ "how big a light press draws",
+ );
+ let b = slider(
+ ui,
+ &mut size.gamma,
+ 0.3..=3.0,
+ "size curve",
+ "below 1 light presses grow sooner, above 1 later",
+ );
+ let c = slider(
+ ui,
+ &mut flow.min,
+ 0.0..=1.0,
+ "flow at the lightest press",
+ "how much paint a light press lays",
+ );
+ let d = slider(
+ ui,
+ &mut opacity.min,
+ 0.0..=1.0,
+ "opacity at the lightest press",
+ "how dark a light press can get",
+ );
+ if a || b || c || d {
+ def.dynamics.size.pressure = plain(size);
+ def.dynamics.flow.pressure = plain(flow);
+ def.dynamics.opacity.pressure = plain(opacity);
+ changed = true;
+ }
+ let mut tilt_size = curve_of(def.dynamics.size.tilt);
+ let mut tilt_opacity = curve_of(def.dynamics.opacity.tilt);
+ let e = slider(
+ ui,
+ &mut tilt_size.max,
+ 0.2..=4.0,
+ "size at full tilt",
+ "a tilted pen paints this much bigger",
+ );
+ let f = slider(
+ ui,
+ &mut tilt_opacity.max,
+ 0.0..=1.0,
+ "opacity at full tilt",
+ "a tilted pen paints this light",
+ );
+ if e || f {
+ def.dynamics.size.tilt = plain(tilt_size);
+ def.dynamics.opacity.tilt = plain(tilt_opacity);
+ changed = true;
+ }
+ });
+ ui.vertical(|ui| {
+ changed |= slider(ui, &mut def.flow, 0.001..=1.0, "flow", "paint per dab");
+ changed |= slider(
+ ui,
+ &mut def.opacity,
+ 0.001..=1.0,
+ "opacity",
+ "the most one stroke can cover",
+ );
+ changed |= slider(
+ ui,
+ &mut def.taper[0],
+ 0.0..=200.0,
+ "taper in px",
+ "the start comes to full size over this length",
+ );
+ changed |= slider(
+ ui,
+ &mut def.taper[1],
+ 0.0..=200.0,
+ "taper out px",
+ "the end comes to a point over this length",
+ );
+ changed |= slider(
+ ui,
+ &mut def.stabilizer,
+ 0.0..=200.0,
+ "stabiliser ms",
+ "the line follows the pen's average over this many ms",
+ );
+ changed |= slider(
+ ui,
+ &mut def.smoothing,
+ 0.0..=100.0,
+ "pressure smoothing ms",
+ "evens out pressure over this many ms",
+ );
+ });
+ ui.separator();
+ if let Some(d) = def.dual.as_mut() {
+ ui.vertical(|ui| {
+ changed |= tip_choice(ui, "dual tip", &mut d.tip, &pictures, "the second tip");
+ changed |= slider(ui, &mut d.size, 0.05..=2.0, "its size", "as a part of the main tip");
+ changed |= slider(ui, &mut d.scatter, 0.0..=4.0, "its scatter", "how far its stamps stray");
+ let mut count = d.count as f32;
+ if slider(
+ ui,
+ &mut count,
+ 1.0..=8.0,
+ "stamps per dab",
+ "more stamps fill the mark in",
+ ) {
+ d.count = count.round() as u32;
+ changed = true;
+ }
+ });
+ }
+ if let Some(g) = def.grain.as_mut() {
+ ui.vertical(|ui| {
+ let current = g.image.clone().unwrap_or_else(|| "paper".into());
+ egui::ComboBox::from_id_salt("brush texture")
+ .selected_text(&current)
+ .show_ui(ui, |ui| {
+ if ui.selectable_label(g.image.is_none(), "paper").clicked() && g.image.is_some() {
+ g.image = None;
+ g.paper = Some(Paper { seed: 23, feature: 4 });
+ changed = true;
+ }
+ pictures.iter().for_each(|name| {
+ if ui.selectable_label(g.image.as_deref() == Some(name), name).clicked()
+ && g.image.as_deref() != Some(name)
+ {
+ g.image = Some(name.clone());
+ g.paper = None;
+ changed = true;
+ }
+ });
+ })
+ .response
+ .hint("the texture: paper noise or a picture");
+ if let Some(paper) = g.paper.as_mut() {
+ let mut feature = paper.feature as f32;
+ if slider(ui, &mut feature, 1.0..=64.0, "grain size", "how coarse the paper is") {
+ paper.feature = feature.round() as usize;
+ changed = true;
+ }
+ }
+ changed |= slider(
+ ui,
+ &mut g.strength,
+ 0.0..=1.0,
+ "strength",
+ "how much the texture takes away",
+ );
+ changed |= slider(ui, &mut g.scale, 0.05..=20.0, "scale", "the texture's size");
+ changed |= slider(
+ ui,
+ &mut g.contrast,
+ 0.0..=8.0,
+ "contrast",
+ "harder or softer texture edges",
+ );
+ changed |= slider(
+ ui,
+ &mut g.pressure,
+ 0.0..=1.0,
+ "pressed in",
+ "a hard press fills the texture in by this much",
+ );
+ });
+ }
+ if let Some(c) = def.color.as_mut() {
+ ui.vertical(|ui| {
+ changed |= slider(
+ ui,
+ &mut c.hue,
+ 0.0..=180.0,
+ "hue per dab",
+ "degrees each dab's hue can move",
+ );
+ changed |= slider(
+ ui,
+ &mut c.saturation,
+ 0.0..=1.0,
+ "saturation per dab",
+ "how far each dab's saturation can move",
+ );
+ changed |= slider(
+ ui,
+ &mut c.value,
+ 0.0..=1.0,
+ "value per dab",
+ "how far each dab's lightness can move",
+ );
+ changed |= slider(
+ ui,
+ &mut c.stroke_hue,
+ 0.0..=180.0,
+ "hue per stroke",
+ "degrees each stroke's hue can move",
+ );
+ changed |= slider(
+ ui,
+ &mut c.stroke_saturation,
+ 0.0..=1.0,
+ "saturation per stroke",
+ "per stroke",
+ );
+ changed |= slider(ui, &mut c.stroke_value, 0.0..=1.0, "value per stroke", "per stroke");
+ let mut by_pressure = c.pressure.is_some();
+ if ui
+ .checkbox(&mut by_pressure, "second colour at light pressure")
+ .hint("a light press paints the second colour, a full press the first")
+ .changed()
+ {
+ c.pressure = by_pressure.then_some(Curve {
+ min: 0.0,
+ max: 1.0,
+ gamma: 1.0,
+ });
+ changed = true;
+ }
+ changed |= slider(
+ ui,
+ &mut c.along,
+ 0.0..=2000.0,
+ "to the second colour over px",
+ "the colour turns into the second over this length (0: off)",
+ );
+ });
+ }
+ ui.vertical(|ui| match def.paint.as_mut() {
+ Some(PaintDef::Wet {
+ wetness,
+ pickup,
+ dilution,
+ }) => {
+ changed |= slider(
+ ui,
+ wetness,
+ 0.0..=1.0,
+ "wetness",
+ "how much of the picked-up colour it lays",
+ );
+ changed |= slider(
+ ui,
+ pickup,
+ 0.0..=1.0,
+ "pickup",
+ "how fast it takes on the colour under it",
+ );
+ changed |= slider(ui, dilution, 0.0..=1.0, "dilution", "thinner, lighter paint");
+ }
+ Some(PaintDef::Smudge { strength } | PaintDef::Blend { strength }) => {
+ changed |= slider(ui, strength, 0.0..=1.0, "strength", "how strongly it moves the paint");
+ }
+ None => {}
+ });
+ ui.separator();
+ ui.vertical(|ui| {
+ let label = ui.label("picture from a file");
+ ui.add(egui::TextEdit::singleline(&mut self.brush_window.picture_path).desired_width(180.0))
+ .labelled_by(label.id)
+ .hint("a PNG for a tip or a texture: dark is paint, or its alpha; or drop the file on this window");
+ if ui
+ .button("add the picture")
+ .hint("copy the PNG into this drawing's brushes/images")
+ .clicked()
+ {
+ let path = std::path::PathBuf::from(self.brush_window.picture_path.trim());
+ self.check(|e| e.add_picture_from(&path));
+ }
+ });
+ });
+ if changed {
+ def.validate()?;
+ self.custom = Some(def);
+ }
+ ui.separator();
+ ui.horizontal_wrapped(|ui| {
+ let label = ui.label("name");
+ ui.add(egui::TextEdit::singleline(&mut self.brush_window.name).desired_width(140.0))
+ .labelled_by(label.id)
+ .hint("the brush's name; saving keeps it in this drawing");
+ if ui
+ .button("save in this drawing")
+ .hint("a brush of this drawing, in the brush tiles; its id comes from the name")
+ .clicked()
+ {
+ self.check(|e| e.save_brush());
+ }
+ if ui
+ .add_enabled(self.custom.is_some(), egui::Button::new("back to the brush"))
+ .hint("drop the edits and draw with the brush as it was")
+ .clicked()
+ {
+ self.custom = None;
+ self.brush_window.preview = None;
+ }
+ });
+ if self.custom.is_some() {
+ ui.label(RichText::new("you draw with these settings now; save them to keep them").color(theme::WEAK));
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn brush_names_become_ids() {
+ assert_eq!(slug("My Wet Oil!"), "my-wet-oil");
+ assert_eq!(slug(" "), "");
+ }
+}
diff --git a/crates/app/src/editor/buffer.rs b/crates/app/src/editor/buffer.rs
new file mode 100644
index 0000000..f1b4215
--- /dev/null
+++ b/crates/app/src/editor/buffer.rs
@@ -0,0 +1,291 @@
+use super::{Editor, ms};
+use crate::composite::{Prepared, picture_path};
+use crate::messages::Tone;
+use anyhow::Result;
+use klad_brush::cache::{CelCache, Write};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::mpsc::{Receiver, channel};
+use std::time::{Instant, SystemTime};
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub(super) struct Buffered {
+ pub watch: BTreeSet<u32>,
+ pub draw: BTreeSet<u32>,
+}
+
+type Memo = BTreeMap<PathBuf, (SystemTime, u64, u64)>;
+type Ask = (u64, Vec<(String, String)>, PathBuf);
+type Planes = Option<Ask>;
+type FrameState = (u32, u64, bool, Vec<(String, String)>, Planes, Option<(String, String)>);
+
+pub(super) struct Survey {
+ frames: Vec<FrameState>,
+ pictures: PathBuf,
+ root: PathBuf,
+ cache: CelCache,
+ holding: BTreeSet<String>,
+ memo: Memo,
+}
+
+struct Keys<'a> {
+ root: &'a Path,
+ cache: &'a CelCache,
+ memo: Memo,
+ held: BTreeMap<String, bool>,
+}
+
+impl Keys<'_> {
+ fn key(&mut self, layer: &str, cel: &str) -> u64 {
+ let path = self.root.join("strokes").join(layer).join(format!("{cel}.strokes"));
+ let stamp = std::fs::metadata(&path)
+ .ok()
+ .and_then(|m| Some((m.modified().ok()?, m.len())));
+ match (stamp, self.memo.get(&path)) {
+ (Some((at, len)), Some((was, size, key))) if at == *was && len == *size => *key,
+ (stamp, _) => {
+ let key = self.cache.key(&std::fs::read(&path).unwrap_or_default());
+ if let Some((at, len)) = stamp {
+ self.memo.insert(path, (at, len, key));
+ }
+ key
+ }
+ }
+ }
+
+ fn active_drawn(&mut self, holding: &BTreeSet<String>, active: Option<&(String, String)>) -> bool {
+ active.is_none_or(|(l, c)| self.drawn(holding, l, c))
+ }
+
+ fn planned(&mut self, planes: Option<&Ask>) -> bool {
+ planes.is_some_and(|(base, cels, dir)| {
+ let list: Vec<u64> = cels.iter().map(|(l, c)| self.key(l, c)).collect();
+ crate::planes::path(dir, crate::planes::key(*base, &list)).exists()
+ })
+ }
+
+ fn drawn(&mut self, holding: &BTreeSet<String>, layer: &str, cel: &str) -> bool {
+ if holding.contains(cel) {
+ return true;
+ }
+ if let Some(known) = self.held.get(cel) {
+ return *known;
+ }
+ let key = self.key(layer, cel);
+ let known = self.cache.holds_key(cel, key);
+ self.held.insert(cel.to_string(), known);
+ known
+ }
+}
+
+pub(super) fn survey(s: Survey) -> (Buffered, Memo) {
+ let mut keys = Keys {
+ root: &s.root,
+ cache: &s.cache,
+ memo: s.memo,
+ held: BTreeMap::new(),
+ };
+ let mut buffered = Buffered::default();
+ s.frames
+ .iter()
+ .for_each(|(frame, key, in_memory, cels, planes, active)| {
+ if *in_memory || picture_path(&s.pictures, *key).exists() {
+ buffered.watch.insert(*frame);
+ }
+ let all = cels.iter().all(|(layer, cel)| keys.drawn(&s.holding, layer, cel));
+ if all || (keys.active_drawn(&s.holding, active.as_ref()) && keys.planned(planes.as_ref())) {
+ buffered.draw.insert(*frame);
+ }
+ });
+ (buffered, keys.memo)
+}
+
+pub(super) struct Preparing {
+ pub from: u32,
+ pub to: u32,
+ pub done: Arc<AtomicU64>,
+ stop: Arc<AtomicBool>,
+ rx: Receiver<Result<(usize, usize)>>,
+ since: Instant,
+}
+
+#[derive(Default)]
+pub(super) struct BufferState {
+ pub shown: Buffered,
+ job: Option<Receiver<(Buffered, Memo)>>,
+ memo: Memo,
+ asked: u64,
+ pub preparing: Option<Preparing>,
+ pub writes: Arc<AtomicU64>,
+}
+
+impl BufferState {
+ #[cfg(test)]
+ pub fn job_idle(&self) -> bool {
+ self.job.is_none()
+ }
+}
+
+impl Editor {
+ fn buffer_signature(&self) -> u64 {
+ let numbers = [
+ self.scene.bundle.doc.rev,
+ self.frames.level as u64,
+ self.scene.onion_on as u64,
+ self.frames.len() as u64,
+ self.buffering.writes.load(Ordering::Relaxed),
+ self.scene.holding().len() as u64,
+ self.scene.bundle.doc.timeline.frames as u64,
+ ];
+ fnv(FNV_OFFSET, &numbers.map(u64::to_le_bytes).concat())
+ }
+
+ pub(super) fn tend_buffer(&mut self) {
+ let finished = self.buffering.job.as_ref().and_then(|rx| rx.try_recv().ok());
+ if let Some((shown, memo)) = finished {
+ self.buffering.shown = shown;
+ self.buffering.memo = memo;
+ self.buffering.job = None;
+ }
+ if let Some(result) = self.buffering.preparing.as_ref().and_then(|p| p.rx.try_recv().ok()) {
+ let Some(p) = self.buffering.preparing.take() else {
+ return;
+ };
+ match result {
+ Ok((frames, drawings)) => self.say(
+ Tone::Done,
+ format!(
+ "frames {} to {} prepared in {:.1} s: {frames} pictures and {drawings} drawings made, the rest were ready",
+ p.from,
+ p.to,
+ ms(p.since) / 1000.0
+ ),
+ ),
+ Err(e) => self.error(format!("preparing frames: {e:#}")),
+ }
+ }
+ if self.buffering.job.is_some() || !self.cacheable() {
+ return;
+ }
+ let signature = self.buffer_signature();
+ if signature == self.buffering.asked {
+ return;
+ }
+ self.buffering.asked = signature;
+ let onion = self.scene.onion_on;
+ let count = self.scene.bundle.doc.timeline.frames;
+ let frames: Vec<FrameState> = (0..count)
+ .map(|f| {
+ let key = self.frames.key(&mut self.scene, f, onion, &self.brushes);
+ let cels = self
+ .scene
+ .bundle
+ .doc
+ .paint_content_at(f)
+ .iter()
+ .map(|(l, c)| (l.id.clone(), c.id.clone()))
+ .collect();
+ let planes = self.scene.planes_ask(f).map(|p| (p.base, p.cels, p.dir));
+ let active = self
+ .scene
+ .active_layer()
+ .and_then(|l| l.content_at(f).map(|c| (l.id.clone(), c.id.clone())));
+ (f, key, self.frames.has(key), cels, planes, active)
+ })
+ .collect();
+ let job = Survey {
+ frames,
+ pictures: self.scene.pictures(),
+ root: self.scene.bundle.root.clone(),
+ cache: CelCache::new(&self.scene.bundle, &self.brushes, Write::Never),
+ holding: self.scene.holding(),
+ memo: std::mem::take(&mut self.buffering.memo),
+ };
+ let (tx, rx) = channel();
+ let ctx = self.ctx.clone();
+ std::thread::spawn(move || {
+ let _ = tx.send(survey(job));
+ ctx.request_repaint();
+ });
+ self.buffering.job = Some(rx);
+ }
+
+ pub(super) fn prepare_span(&self) -> (u32, u32) {
+ let last = self.scene.bundle.doc.timeline.frames.saturating_sub(1);
+ match (self.timeline.range, self.current_clip()) {
+ (Some((a, b)), _) => (a.min(last), b.min(last)),
+ (None, Some(clip)) => (clip.from.min(last), clip.to.min(last)),
+ _ => (0, last),
+ }
+ }
+
+ pub(super) fn prepare_frames(&mut self) -> Result<()> {
+ if let Some(p) = self.buffering.preparing.as_ref() {
+ p.stop.store(true, Ordering::Relaxed);
+ self.say(Tone::Info, "stopping after the frame being prepared");
+ return Ok(());
+ }
+ let (from, to) = self.prepare_span();
+ let (onion, level) = (self.scene.onion_on, self.frames.level);
+ let mut seen = BTreeSet::new();
+ let requests: Vec<_> = (from..=to)
+ .map(|f| {
+ let request = self.scene.prepare_request(f, onion, level, &self.brushes);
+ let fresh = seen.insert(request.key);
+ fresh.then_some(request)
+ })
+ .collect();
+ let done = Arc::new(AtomicU64::new(0));
+ let stop = Arc::new(AtomicBool::new(false));
+ let (tx, rx) = channel();
+ let (counter, halt, writes, ctx) = (
+ done.clone(),
+ stop.clone(),
+ self.buffering.writes.clone(),
+ self.ctx.clone(),
+ );
+ std::thread::spawn(move || {
+ let result = requests
+ .into_iter()
+ .try_fold((0usize, 0usize), |(frames, drawings), request| {
+ if halt.load(Ordering::Relaxed) {
+ return Ok((frames, drawings));
+ }
+ let made = match request {
+ Some(r) => crate::background().install(|| r.prepare())?,
+ None => Prepared::Already,
+ };
+ counter.fetch_add(1, Ordering::Relaxed);
+ writes.fetch_add(1, Ordering::Relaxed);
+ ctx.request_repaint();
+ Ok::<_, anyhow::Error>(match made {
+ Prepared::Already => (frames, drawings),
+ Prepared::Drawings(n) => (frames, drawings + n),
+ Prepared::Frame(n) => (frames + 1, drawings + n),
+ })
+ });
+ let _ = tx.send(result);
+ ctx.request_repaint();
+ });
+ self.buffering.preparing = Some(Preparing {
+ from,
+ to,
+ done,
+ stop,
+ rx,
+ since: Instant::now(),
+ });
+ self.say(Tone::Info, format!("preparing frames {from} to {to} in the background"));
+ Ok(())
+ }
+
+ pub(super) fn preparing_text(&self) -> Option<String> {
+ self.buffering
+ .preparing
+ .as_ref()
+ .map(|p| format!("preparing {} of {}", p.done.load(Ordering::Relaxed), p.to - p.from + 1))
+ }
+}
diff --git a/crates/app/src/editor/cells.rs b/crates/app/src/editor/cells.rs
new file mode 100644
index 0000000..7247036
--- /dev/null
+++ b/crates/app/src/editor/cells.rs
@@ -0,0 +1,355 @@
+use super::Editor;
+use crate::commands::Cmd;
+use crate::messages::Tone;
+use crate::theme::{self, Hint, icon};
+use anyhow::Result;
+use egui::RichText;
+use klad_core::doc::{Cel, Document, Layer};
+use klad_core::ops::{ClipEdit, Op};
+use klad_core::timing::{CelAction, CelSpec, OPEN, ends};
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct CellCopy {
+ pub layer: String,
+ pub offset: u32,
+ pub source: String,
+ pub length: u32,
+ pub link: bool,
+}
+
+fn exposures(layer: &Layer, frames: u32) -> Vec<(Cel, u32, u32)> {
+ let cels = layer.cels();
+ cels.iter()
+ .zip(ends(cels))
+ .map(|(c, e)| (c.clone(), c.frame, if e == OPEN { frames.max(c.frame + 1) } else { e }))
+ .collect()
+}
+
+pub(super) fn copy_cells(doc: &Document, rows: &[String], from: u32, to: u32) -> Vec<CellCopy> {
+ let frames = doc.timeline.frames;
+ rows.iter()
+ .filter_map(|id| doc.layer(id).map(|l| (id, l)))
+ .flat_map(|(id, layer)| {
+ exposures(layer, frames)
+ .into_iter()
+ .filter(|(_, start, end)| *start <= to && *end > from)
+ .map(|(cel, start, end)| {
+ let first = start.max(from);
+ CellCopy {
+ layer: id.clone(),
+ offset: first - from,
+ source: cel.link.clone().unwrap_or_else(|| cel.id.clone()),
+ length: end.min(to + 1) - first,
+ link: cel.link.is_some(),
+ }
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect()
+}
+
+pub(super) fn paste_ops(doc: &Document, cells: &[CellCopy], at: u32, links: bool) -> Vec<Op> {
+ cells
+ .iter()
+ .map(|c| {
+ let frame = at + c.offset;
+ let taken = doc
+ .layer(&c.layer)
+ .is_some_and(|l| l.cels().iter().any(|x| x.frame == frame));
+ Op::Cel(CelSpec {
+ action: match links || c.link {
+ true => CelAction::Link { cel: c.source.clone() },
+ false => CelAction::Dup { cel: c.source.clone() },
+ },
+ id: None,
+ frame: Some(frame),
+ hold: Some(c.length),
+ insert: taken,
+ })
+ })
+ .collect()
+}
+
+impl Editor {
+ pub(super) fn copy_selected_cells(&mut self) {
+ let (rows, from, to) = match &self.timeline.span {
+ Some(span) => (span.rows.clone(), span.from, span.to),
+ None => match self.here() {
+ Some((layer, Some((cel, end)))) => {
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let end = if end == OPEN { frames.max(cel.frame + 1) } else { end };
+ (vec![layer], cel.frame, end - 1)
+ }
+ _ => return,
+ },
+ };
+ let copied = copy_cells(&self.scene.bundle.doc, &rows, from, to);
+ let drawings = copied.len();
+ self.timeline.cells = Some(copied);
+ self.say(
+ Tone::Done,
+ format!("copied {drawings} cells of frames {from} to {to}: paste them at the playhead as copies or links"),
+ );
+ }
+
+ pub(super) fn paste_cells(&mut self, links: bool) -> Result<()> {
+ let Some(cells) = self.timeline.cells.clone() else {
+ return Ok(());
+ };
+ let ops = paste_ops(&self.scene.bundle.doc, &cells, self.scene.frame, links);
+ if self.timeline_apply(ops)?.is_some() {
+ self.say(
+ Tone::Done,
+ format!(
+ "pasted {} cells at frame {} as {}",
+ cells.len(),
+ self.scene.frame,
+ if links { "links" } else { "copies" }
+ ),
+ );
+ }
+ Ok(())
+ }
+
+ pub(super) fn move_drawing(&mut self, by: i32) -> Result<()> {
+ let Some((_, Some((cel, _)))) = self.here() else {
+ return Ok(());
+ };
+ let to = (cel.frame as i64 + by as i64).max(0) as u32;
+ let op = Op::Cel(CelSpec {
+ action: CelAction::Move { cel: cel.id.clone() },
+ id: None,
+ frame: Some(to),
+ hold: None,
+ insert: false,
+ });
+ if self.timeline_apply(vec![op])?.is_some() {
+ self.go_to(to)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn selection_toolbar(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let mut hold_to = None;
+ ui.horizontal_wrapped(|ui| {
+ [
+ Cmd::NewDrawing,
+ Cmd::Duplicate,
+ Cmd::Link,
+ Cmd::Unlink,
+ Cmd::DeleteDrawing,
+ ]
+ .into_iter()
+ .for_each(|cmd| {
+ self.command_button(ui, cmd, None);
+ });
+ ui.separator();
+ self.command_button(ui, Cmd::HoldShorter, None);
+ if let Some((_, Some((cel, end)))) = self.here() {
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let end = if end == OPEN { frames.max(cel.frame + 1) } else { end };
+ let mut hold = end - cel.frame;
+ let label = ui.label("hold");
+ let r = ui
+ .add(egui::DragValue::new(&mut hold).range(1..=10_000))
+ .labelled_by(label.id)
+ .hint("how many frames this drawing shows; later drawings move along");
+ if (r.drag_stopped() || r.lost_focus() || (r.changed() && !r.dragged() && !r.has_focus()))
+ && hold != end - cel.frame
+ {
+ hold_to = Some((cel.clone(), end, hold));
+ }
+ }
+ self.command_button(ui, Cmd::HoldLonger, None);
+ ui.separator();
+ [
+ Cmd::InsertFrame,
+ Cmd::InsertFrameAll,
+ Cmd::RemoveFrame,
+ Cmd::RemoveFrameAll,
+ ]
+ .into_iter()
+ .for_each(|cmd| {
+ self.command_button(ui, cmd, None);
+ });
+ ui.separator();
+ [Cmd::CopyCells, Cmd::PasteCells, Cmd::PasteCellsLinked]
+ .into_iter()
+ .for_each(|cmd| {
+ self.command_button(ui, cmd, None);
+ });
+ ui.separator();
+ let span = self.timeline.span.is_some();
+ ui.add_enabled_ui(span, |ui| {
+ ui.menu_button(format!("{} retime", icon::RETIME), |ui| {
+ [Cmd::OnOnes, Cmd::OnTwos, Cmd::OnThrees].into_iter().for_each(|cmd| {
+ if self.command_button(ui, cmd, Some(cmd.spec().name)).clicked() {
+ ui.close();
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.add(egui::DragValue::new(&mut self.timeline.ask.fit).range(1..=10_000))
+ .hint("the number of frames to fit the selection into");
+ if self.command_button(ui, Cmd::FitFrames, Some("fit")).clicked() {
+ ui.close();
+ }
+ });
+ [Cmd::Reverse, Cmd::Pingpong].into_iter().for_each(|cmd| {
+ if self.command_button(ui, cmd, Some(cmd.spec().name)).clicked() {
+ ui.close();
+ }
+ });
+ self.command_check(ui, Cmd::EveryLayer, "on every layer");
+ })
+ .response
+ .hint("retime the selected frames: on ones, twos, threes, fit, reverse, ping-pong");
+ })
+ .response
+ .on_disabled_hover_text("select frames first: drag over cells, or shift click");
+ self.command_button(ui, Cmd::Inbetween, Some("in-between"));
+ self.command_button(ui, Cmd::RedoInbetweens, None);
+ self.command_button(ui, Cmd::NewClip, None);
+ if let Some(span) = &self.timeline.span {
+ ui.label(
+ RichText::new(format!(
+ "frames {} to {} on {} rows",
+ span.from,
+ span.to,
+ span.rows.len()
+ ))
+ .color(theme::WEAK),
+ );
+ }
+ });
+ if let Some((cel, end, hold)) = hold_to {
+ let layer = self.scene.active_id().unwrap_or_default();
+ let open = self
+ .scene
+ .active_layer()
+ .and_then(|l| l.cels().iter().find(|c| c.id == cel.id).cloned())
+ .is_some_and(|c| c.hold.is_none());
+ self.resize(&layer, &cel.id, (cel.frame, end, open), cel.frame + hold)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn clip_window(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some(clip) = self.current_clip() else {
+ ui.label("no clip here: click a clip's bar above the frame numbers, or make one from a selection");
+ self.command_button(ui, Cmd::NewClip, Some("new clip from the selection"));
+ return Ok(());
+ };
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let (mut from, mut to) = (clip.from, clip.to);
+ let mut ops = Vec::new();
+ ui.horizontal(|ui| {
+ let label = ui.label("frames");
+ let a = ui
+ .add(egui::DragValue::new(&mut from).range(0..=frames - 1))
+ .labelled_by(label.id)
+ .hint("the clip's first frame");
+ ui.label("to");
+ let b = ui
+ .add(egui::DragValue::new(&mut to).range(0..=frames - 1))
+ .hint("the clip's last frame");
+ let done = |r: &egui::Response| r.drag_stopped() || r.lost_focus();
+ if (done(&a) || done(&b)) && (from, to) != (clip.from, clip.to) && from <= to {
+ ops.push(Op::Clip(ClipEdit::Set {
+ name: clip.name.clone(),
+ rename: None,
+ from: Some(from),
+ to: Some(to),
+ looping: None,
+ fps: None,
+ }));
+ }
+ });
+ self.timeline_apply(ops)?;
+ self.clip_row(ui)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Layer;
+
+ fn doc() -> Document {
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 12;
+ let mut layer = Layer::paint("l1", "lines", "c1");
+ if let Some(cels) = layer.cels_mut() {
+ cels[0].hold = Some(2);
+ cels.push(Cel::at("c2", 2));
+ cels[1].hold = Some(3);
+ let mut link = Cel::at("c3", 5);
+ link.link = Some("c1".into());
+ link.hold = Some(1);
+ cels.push(link);
+ }
+ doc.layers.push(layer);
+ doc
+ }
+
+ #[test]
+ fn cells_copy_their_drawings_holds_and_links_and_paste_as_copies_or_links() {
+ let doc = doc();
+ let cells = copy_cells(&doc, &["l1".into()], 1, 5);
+ assert_eq!(
+ cells,
+ [
+ CellCopy {
+ layer: "l1".into(),
+ offset: 0,
+ source: "c1".into(),
+ length: 1,
+ link: false
+ },
+ CellCopy {
+ layer: "l1".into(),
+ offset: 1,
+ source: "c2".into(),
+ length: 3,
+ link: false
+ },
+ CellCopy {
+ layer: "l1".into(),
+ offset: 4,
+ source: "c1".into(),
+ length: 1,
+ link: true
+ },
+ ]
+ );
+ let ops = paste_ops(&doc, &cells, 8, false);
+ assert_eq!(ops.len(), 3);
+ assert!(
+ matches!(&ops[0], Op::Cel(CelSpec { action: CelAction::Dup { cel }, frame: Some(8), hold: Some(1), .. }) if cel == "c1")
+ );
+ assert!(
+ matches!(&ops[2], Op::Cel(CelSpec { action: CelAction::Link { cel }, frame: Some(12), .. }) if cel == "c1")
+ );
+ let linked = paste_ops(&doc, &cells, 8, true);
+ assert!(linked.iter().all(|op| matches!(
+ op,
+ Op::Cel(CelSpec {
+ action: CelAction::Link { .. },
+ ..
+ })
+ )));
+ let onto = paste_ops(&doc, &cells, 2, false);
+ assert!(matches!(&onto[0], Op::Cel(CelSpec { insert: true, .. })));
+ let (pasted, _) = klad_core::ops::apply_all(&doc, &ops).unwrap();
+ let cels: Vec<(u32, Option<u32>)> = pasted
+ .layer("l1")
+ .unwrap()
+ .cels()
+ .iter()
+ .map(|c| (c.frame, c.hold))
+ .collect();
+ assert!(
+ cels.contains(&(8, Some(1))) && cels.contains(&(9, Some(3))) && cels.contains(&(12, Some(1))),
+ "{cels:?}"
+ );
+ }
+}
diff --git a/crates/app/src/editor/clips.rs b/crates/app/src/editor/clips.rs
new file mode 100644
index 0000000..2da9aee
--- /dev/null
+++ b/crates/app/src/editor/clips.rs
@@ -0,0 +1,443 @@
+use super::Editor;
+use crate::commands::Cmd;
+use crate::jobs::{Spec, Tag};
+use crate::theme::Hint;
+use anyhow::Result;
+use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, pos2};
+use klad_core::doc::{Clip, Timeline as Clock};
+use klad_core::ops::{ClipEdit, Op};
+use std::path::{Path, PathBuf};
+
+pub(super) const LANE: f32 = 16.0;
+const END: f32 = 6.0;
+
+pub(super) fn lanes(clips: &[Clip]) -> Vec<usize> {
+ let mut order: Vec<usize> = (0..clips.len()).collect();
+ order.sort_by_key(|&i| (clips[i].from, clips[i].to));
+ let mut ends: Vec<u32> = Vec::new();
+ let mut lane = vec![0; clips.len()];
+ order.into_iter().for_each(|i| {
+ let c = &clips[i];
+ let at = ends.iter().position(|&e| e < c.from).unwrap_or(ends.len());
+ match ends.get_mut(at) {
+ Some(e) => *e = c.to,
+ None => ends.push(c.to),
+ }
+ lane[i] = at;
+ });
+ lane
+}
+
+pub(super) fn band_height(clips: &[Clip]) -> f32 {
+ (lanes(clips).into_iter().max().map_or(1, |m| m + 2)) as f32 * LANE
+}
+
+pub(super) fn fresh_name(clips: &[Clip]) -> String {
+ (1..)
+ .map(|n| format!("clip{n}"))
+ .find(|n| clips.iter().all(|c| &c.name != n))
+ .unwrap_or_default()
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Span {
+ pub from: u32,
+ pub to: u32,
+ pub fps: u32,
+ pub once: bool,
+ pub what: String,
+}
+
+pub(super) fn play_span(t: &Clock, frame: u32, range: Option<(u32, u32)>, chosen: Option<&str>) -> Span {
+ if let Some((a, b)) = range.filter(|(a, b)| a <= b && *b < t.frames) {
+ return Span {
+ from: a,
+ to: b,
+ fps: t.fps,
+ once: false,
+ what: format!("the loop range {a} to {b}"),
+ };
+ }
+ let picked = chosen
+ .and_then(|n| t.clip(n))
+ .filter(|c| c.from <= frame && frame <= c.to);
+ match picked.or_else(|| t.clip_at(frame)) {
+ Some(c) => Span {
+ from: c.from,
+ to: c.to.min(t.frames - 1),
+ fps: t.fps_of(c),
+ once: !c.looping,
+ what: format!("clip {}", c.name),
+ },
+ None => Span {
+ from: 0,
+ to: t.frames - 1,
+ fps: t.fps,
+ once: false,
+ what: "the timeline".into(),
+ },
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Hit {
+ Body,
+ First,
+ Last,
+}
+
+pub(super) struct Strip {
+ pub rect: Rect,
+ pub cell: f32,
+ pub lanes: Vec<usize>,
+}
+
+impl Strip {
+ fn x_of(&self, f: u32) -> f32 {
+ self.rect.left() + f as f32 * self.cell
+ }
+
+ fn bar(&self, from: u32, to: u32, lane: usize) -> Rect {
+ let top = self.rect.top() + lane as f32 * LANE;
+ Rect::from_min_max(
+ pos2(self.x_of(from) + 1.0, top + 2.0),
+ pos2(self.x_of(to + 1) - 1.0, top + LANE - 2.0),
+ )
+ }
+
+ pub fn hit(&self, clips: &[Clip], p: Pos2) -> Option<(usize, Hit)> {
+ let lane = ((p.y - self.rect.top()) / LANE).floor().max(0.0) as usize;
+ clips
+ .iter()
+ .zip(&self.lanes)
+ .enumerate()
+ .filter(|(_, (_, l))| **l == lane)
+ .find_map(|(i, (c, _))| {
+ let (a, b) = (self.x_of(c.from), self.x_of(c.to + 1));
+ match p.x {
+ x if (x - a).abs() <= END && x < (a + b) / 2.0 => Some((i, Hit::First)),
+ x if (x - b).abs() <= END => Some((i, Hit::Last)),
+ x if a < x && x < b => Some((i, Hit::Body)),
+ _ => None,
+ }
+ })
+ }
+
+ pub fn paint(
+ &self,
+ painter: &Painter,
+ clips: &[Clip],
+ fps: u32,
+ chosen: Option<&str>,
+ spans: &[(usize, u32, u32)],
+ ) {
+ painter.rect_filled(self.rect, 0.0, Color32::from_gray(20));
+ clips.iter().zip(&self.lanes).enumerate().for_each(|(i, (c, &lane))| {
+ let (from, to) = spans
+ .iter()
+ .find(|(k, _, _)| *k == i)
+ .map_or((c.from, c.to), |&(_, a, b)| (a, b));
+ let bar = self.bar(from, to, lane);
+ let fill = match c.looping {
+ true => Color32::from_rgb(52, 128, 118),
+ false => Color32::from_rgb(150, 112, 52),
+ };
+ painter.rect_filled(bar, 3.0, fill);
+ if chosen == Some(c.name.as_str()) {
+ painter.rect_stroke(bar, 3.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Inside);
+ }
+ [bar.left() + 2.0, bar.right() - 2.0].iter().for_each(|&x| {
+ painter.line_segment(
+ [pos2(x, bar.top() + 2.0), pos2(x, bar.bottom() - 2.0)],
+ Stroke::new(1.0, Color32::from_gray(220)),
+ );
+ });
+ let label = format!(
+ "{}{}{}",
+ c.name,
+ c.fps
+ .filter(|f| *f != fps)
+ .map_or(String::new(), |f| format!(", {f} fps")),
+ if c.looping { ", loops" } else { ", once" }
+ );
+ painter.with_clip_rect(bar.shrink(3.0)).text(
+ pos2(bar.left() + 6.0, bar.center().y),
+ Align2::LEFT_CENTER,
+ label,
+ FontId::proportional(10.5),
+ Color32::from_gray(240),
+ );
+ });
+ }
+
+ pub fn outline(&self, painter: &Painter, from: u32, to: u32) {
+ let (a, b) = (from.min(to), from.max(to));
+ painter.rect_stroke(
+ Rect::from_min_max(
+ pos2(self.x_of(a), self.rect.top() + 1.0),
+ pos2(self.x_of(b + 1), self.rect.bottom() - 1.0),
+ ),
+ 3.0,
+ Stroke::new(1.5, Color32::YELLOW),
+ egui::StrokeKind::Inside,
+ );
+ }
+}
+
+fn summary(stderr: &str) -> String {
+ let keep: Vec<&str> = stderr
+ .lines()
+ .filter(|l| l.starts_with("animations:") || l.starts_with("kept ") || l.contains(" in all"))
+ .collect();
+ keep.join("; ")
+}
+
+fn failure(stderr: &str) -> String {
+ let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect();
+ lines[lines.len().saturating_sub(3)..].join(" ")
+}
+
+pub(super) fn resolve(home: &Path, folder: &str) -> PathBuf {
+ let path = PathBuf::from(folder.trim());
+ match path.is_absolute() {
+ true => path,
+ false => home.join(path),
+ }
+}
+
+impl Editor {
+ fn bundle_home(&self) -> PathBuf {
+ let root = self.scene.bundle.root.components().collect::<PathBuf>();
+ match root.parent() {
+ Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
+ _ => PathBuf::from("."),
+ }
+ }
+
+ pub(super) fn add_clip(&mut self, from: u32, to: u32) -> Result<()> {
+ let (from, to) = (from.min(to), from.max(to));
+ let name = fresh_name(&self.scene.bundle.doc.timeline.clips);
+ let clip = Clip::new(&name, from, to, true);
+ if self.timeline_apply(vec![Op::Clip(ClipEdit::Add(clip))])?.is_some() {
+ self.timeline.clip = Some(name);
+ self.timeline.clip_name = (String::new(), String::new());
+ }
+ Ok(())
+ }
+
+ pub(super) fn reach_clip(&mut self, name: &str, from: u32, to: u32) -> Result<()> {
+ let Some(clip) = self.scene.bundle.doc.timeline.clip(name).cloned() else {
+ return Ok(());
+ };
+ if (clip.from, clip.to) == (from, to) {
+ return Ok(());
+ }
+ let op = Op::Clip(ClipEdit::Set {
+ name: name.to_string(),
+ rename: None,
+ from: Some(from),
+ to: Some(to),
+ looping: None,
+ fps: None,
+ });
+ self.timeline_apply(vec![op])?;
+ Ok(())
+ }
+
+ pub(super) fn current_clip(&self) -> Option<Clip> {
+ let t = &self.scene.bundle.doc.timeline;
+ let frame = self.scene.frame;
+ let chosen = self.timeline.clip.as_deref().and_then(|n| t.clip(n));
+ chosen.or_else(|| t.clip_at(frame)).cloned()
+ }
+
+ pub(super) fn clip_row(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let t = self.scene.bundle.doc.timeline.clone();
+ if self.timeline.clip.as_deref().is_some_and(|n| t.clip(n).is_none()) {
+ self.timeline.clip = None;
+ }
+ let stored = self.scene.bundle.doc.export.godot.clone().unwrap_or_default();
+ if self.timeline.godot.0 != stored {
+ self.timeline.godot = (stored.clone(), stored.clone());
+ }
+ let current = self.current_clip();
+ let mut ops: Vec<Op> = Vec::new();
+ ui.horizontal_wrapped(|ui| {
+ match &current {
+ None if t.clips.is_empty() => {
+ ui.small("clips: drag along the strip above the frame numbers to make one (exports turn each clip into an animation)");
+ }
+ None => {
+ ui.small(format!(
+ "no clip at frame {}: click a clip's bar to pick it, or drag along the empty row of the strip for a new one",
+ self.scene.frame
+ ));
+ }
+ Some(clip) => {
+ let set = |rename, looping, fps| {
+ Op::Clip(ClipEdit::Set {
+ name: clip.name.clone(),
+ rename,
+ from: None,
+ to: None,
+ looping,
+ fps,
+ })
+ };
+ if self.timeline.clip_name.0 != clip.name {
+ self.timeline.clip_name = (clip.name.clone(), clip.name.clone());
+ }
+ let label = ui.label("clip");
+ let name = ui
+ .add(egui::TextEdit::singleline(&mut self.timeline.clip_name.1).desired_width(90.0))
+ .labelled_by(label.id)
+ .hint("the clip's name, which exports use for the animation; Return keeps it");
+ let typed = self.timeline.clip_name.1.trim().to_string();
+ if name.lost_focus() && typed != clip.name && !typed.is_empty() {
+ ops.push(set(Some(typed.clone()), None, None));
+ self.timeline.clip = Some(typed);
+ }
+ ui.label(format!("frames {} to {} ({} frames)", clip.from, clip.to, clip.frames()));
+ self.command_check(ui, Cmd::ClipLoops, "loops");
+ self.command_check(ui, Cmd::ClipOwnFps, "own fps");
+ if let Some(fps) = clip.fps {
+ if !ui.memory(|m| m.focused().is_some()) || self.timeline.clip_fps == 0 {
+ self.timeline.clip_fps = fps;
+ }
+ let r = ui
+ .add(egui::DragValue::new(&mut self.timeline.clip_fps).range(1..=240))
+ .hint("the clip's own frames per second");
+ if (r.drag_stopped() || r.lost_focus()) && self.timeline.clip_fps != fps {
+ ops.push(set(None, None, Some(Some(self.timeline.clip_fps))));
+ }
+ } else {
+ ui.label(format!("({} fps, the document's)", t.fps));
+ }
+ self.command_button(ui, Cmd::DeleteClip, Some("delete clip"));
+ }
+ }
+ ui.separator();
+ let label = ui.label("Godot folder");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.timeline.godot.1)
+ .desired_width(180.0)
+ .hint_text("next to the bundle, e.g. ../game/art"),
+ )
+ .labelled_by(label.id)
+ .hint("where export to Godot writes, relative to the folder holding the bundle");
+ self.command_button(ui, Cmd::ExportGodot, Some("export to Godot"));
+ });
+ self.timeline_apply(ops).map(|_| ())
+ }
+
+ pub(super) fn godot_folder(&self) -> String {
+ self.timeline.godot.1.trim().to_string()
+ }
+
+ pub(super) fn export_godot(&mut self) {
+ let typed = self.godot_folder();
+ let mut args: Vec<String> = vec![
+ "export".into(),
+ self.scene.bundle.root.to_string_lossy().to_string(),
+ "--godot".into(),
+ ];
+ if typed != self.timeline.godot.0 {
+ args.push(resolve(&self.bundle_home(), &typed).to_string_lossy().to_string());
+ args.push("--store".into());
+ }
+ self.start_job(Spec {
+ tag: Tag::Export,
+ name: format!("export to Godot ({typed})"),
+ exe: PathBuf::new(),
+ args,
+ env: Vec::new(),
+ reruns: 3,
+ summary: |_, err| summary(err),
+ failure: |_, err| failure(err),
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn overlapping_clips_take_separate_lanes() {
+ let clips = vec![
+ Clip::new("a", 0, 5, true),
+ Clip::new("b", 3, 9, false),
+ Clip::new("c", 6, 8, true),
+ Clip::new("d", 10, 12, true),
+ ];
+ assert_eq!(lanes(&clips), [0, 1, 0, 0]);
+ assert_eq!(
+ band_height(&clips),
+ 3.0 * LANE,
+ "two lanes of bars and a free one to drag new clips on"
+ );
+ assert_eq!(band_height(&[]), LANE);
+ assert_eq!(fresh_name(&clips), "clip1");
+ assert_eq!(fresh_name(&[Clip::new("clip1", 0, 1, true)]), "clip2");
+ }
+
+ #[test]
+ fn return_plays_the_loop_range_then_the_clip_under_the_playhead_then_everything() {
+ let mut t = Clock {
+ frames: 24,
+ ..Clock::default()
+ };
+ t.clips = vec![
+ Clip::new("idle", 0, 5, true),
+ Clip {
+ fps: Some(24),
+ ..Clip::new("jump", 4, 11, false)
+ },
+ ];
+ let span = |frame, range, chosen| {
+ let s = play_span(&t, frame, range, chosen);
+ (s.from, s.to, s.fps, s.once)
+ };
+ assert_eq!(span(2, None, None), (0, 5, 12, false));
+ assert_eq!(span(8, None, None), (4, 11, 24, true));
+ assert_eq!(
+ span(4, None, None),
+ (0, 5, 12, false),
+ "the first clip holding the frame"
+ );
+ assert_eq!(
+ span(4, None, Some("jump")),
+ (4, 11, 24, true),
+ "unless another one is picked"
+ );
+ assert_eq!(
+ span(2, None, Some("jump")),
+ (0, 5, 12, false),
+ "a picked clip away from the playhead"
+ );
+ assert_eq!(span(15, None, None), (0, 23, 12, false));
+ assert_eq!(span(8, Some((6, 9)), None), (6, 9, 12, false));
+ assert_eq!(play_span(&t, 8, None, None).what, "clip jump");
+ }
+
+ #[test]
+ fn the_strip_finds_bars_and_their_ends() {
+ let clips = vec![Clip::new("a", 2, 5, true), Clip::new("b", 4, 9, false)];
+ let strip = Strip {
+ rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 2.0 * LANE)),
+ cell: 20.0,
+ lanes: lanes(&clips),
+ };
+ assert_eq!(strip.hit(&clips, pos2(41.0, 8.0)), Some((0, Hit::First)));
+ assert_eq!(strip.hit(&clips, pos2(70.0, 8.0)), Some((0, Hit::Body)));
+ assert_eq!(strip.hit(&clips, pos2(118.0, 8.0)), Some((0, Hit::Last)));
+ assert_eq!(strip.hit(&clips, pos2(150.0, 8.0)), None);
+ assert_eq!(strip.hit(&clips, pos2(150.0, 24.0)), Some((1, Hit::Body)));
+ assert_eq!(strip.hit(&clips, pos2(199.0, 24.0)), Some((1, Hit::Last)));
+ assert_eq!(
+ resolve(Path::new("/work/art"), "../game/sprites"),
+ PathBuf::from("/work/art/../game/sprites")
+ );
+ assert_eq!(resolve(Path::new("/work/art"), "/abs/x"), PathBuf::from("/abs/x"));
+ }
+}
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
new file mode 100644
index 0000000..d1ff4f0
--- /dev/null
+++ b/crates/app/src/editor/commands.rs
@@ -0,0 +1,878 @@
+use super::selection::Selected;
+use super::tweens::{self, SpanAction};
+use super::{Editor, Tool};
+use crate::commands::{Cmd, Repeat};
+use crate::layout::Pane;
+use crate::messages::Tone;
+use crate::stats::{Stats, lock};
+use crate::theme::{self, Hint};
+use crate::view::View;
+use anyhow::Result;
+use egui::RichText;
+use klad_core::doc::{Kind as LayerKind, MASK, Shape};
+use klad_core::history::Stack;
+use klad_core::markedit::LassoAction;
+use klad_core::ops::{ClipEdit, Op, PaletteEdit};
+use klad_core::pathedit::PathEdit;
+use klad_core::retime::Retime;
+use klad_core::timing::OPEN;
+use serde_json::{Map, json};
+use std::collections::BTreeSet;
+
+const RECENT: usize = 12;
+
+impl Editor {
+ fn drawing_here(&self) -> Option<(klad_core::doc::Cel, u32)> {
+ self.here().and_then(|(_, c)| c)
+ }
+
+ fn active_paint(&self) -> bool {
+ self.scene.active_layer().is_some_and(|l| l.kind() == LayerKind::Paint)
+ }
+
+ fn timeline_edit(&self) -> Option<String> {
+ if self.timeline.player.is_some() {
+ return Some("stop playback first (Return)".into());
+ }
+ if self.holding_frame_keys() {
+ return Some("let go of Q or W first".into());
+ }
+ if self.busy() {
+ return Some("finish the stroke or drag first".into());
+ }
+ None
+ }
+
+ pub(super) fn can_run(&self, cmd: Cmd) -> Option<String> {
+ let spec = cmd.spec();
+ if spec.is_hold() {
+ return Some(format!("{}: {}", spec.name, self.bindings.label(cmd)));
+ }
+ let layer = self.scene.active_layer();
+ let pick_layer = || Some("pick a layer in the timeline or the layers panel first".to_string());
+ let mask = layer.and_then(|l| l.mask.as_deref());
+ let picked = self.picked.is_some() && self.on_marks();
+ let need_strokes = || (!picked).then(|| "select strokes with S first".to_string());
+ let direct = self.direct.as_ref();
+ let span = self.timeline.span.as_ref();
+ let need_span = || {
+ span.is_none()
+ .then(|| "select frames first: shift click or shift drag over cells".to_string())
+ };
+ let clip = self.current_clip();
+ let need_clip = || {
+ clip.is_none()
+ .then(|| "no clip here: click a clip's bar above the frame numbers".to_string())
+ };
+ let editing = self.busy().then(|| "finish the stroke or drag first".to_string());
+ match cmd {
+ Cmd::Undo | Cmd::Redo => editing,
+ Cmd::Delete => match self.tool {
+ Tool::Note => self
+ .note_open
+ .is_none()
+ .then(|| "right click a note's pin with N to select it first".to_string()),
+ Tool::Strokes => need_strokes(),
+ _ if picked => None,
+ Tool::Direct => direct
+ .filter(|d| !d.points.is_empty())
+ .is_none()
+ .then(|| "select points with A first".to_string()),
+ _ => self
+ .selection
+ .is_none()
+ .then(|| "select a shape or strokes with V first".to_string()),
+ }
+ .or(editing),
+ Cmd::Copy => need_strokes(),
+ Cmd::Paste => match (&self.clipboard, self.drag.is_some()) {
+ (None, _) => Some("copy strokes first: S, select them, cmd C".into()),
+ (_, true) => Some("finish the drag first".into()),
+ _ => None,
+ },
+ Cmd::SelectAll => (!self.active_paint() || self.scene.active_marks().is_empty())
+ .then(|| "the active layer has no strokes on this frame".to_string()),
+ Cmd::Recolour | Cmd::Thinner | Cmd::Thicker => need_strokes().or(editing),
+ Cmd::FlipH | Cmd::FlipV | Cmd::TurnLeft90 | Cmd::TurnRight90 | Cmd::DuplicateInPlace => {
+ match self.selected() {
+ Some(Selected::Strokes | Selected::Shape(_)) => editing,
+ _ => Some("select strokes (S) or a shape (V) first".to_string()),
+ }
+ }
+ Cmd::NudgeLeft | Cmd::NudgeRight | Cmd::NudgeUp | Cmd::NudgeDown => match self.selected() {
+ Some(_) => editing.or(self
+ .path_commit
+ .as_ref()
+ .map(|_| "writing the last edit...".to_string())),
+ None => Some("select strokes (S), a shape (V) or points (A) first".to_string()),
+ },
+ Cmd::FlipView | Cmd::ResetRotation => {
+ self.view.is_none().then(|| "the canvas is not shown yet".to_string())
+ }
+ Cmd::Corner | Cmd::Smooth => direct
+ .filter(|d| !d.points.is_empty())
+ .is_none()
+ .then(|| "select points with A first".to_string())
+ .or(self
+ .path_commit
+ .as_ref()
+ .map(|_| "writing the last edit...".to_string())),
+ Cmd::Simplify => direct
+ .is_none()
+ .then(|| "pick a shape with A first".to_string())
+ .or(self
+ .path_commit
+ .as_ref()
+ .map(|_| "writing the last edit...".to_string())),
+ Cmd::MakePath => match direct.and_then(|d| self.scene.bundle.doc.item(&d.node)) {
+ Some(klad_core::doc::Item::Node(_, _, n)) if matches!(n.shape, Shape::Path { .. }) => {
+ Some("it is a path already".into())
+ }
+ Some(_) => None,
+ None => Some("pick a rect or ellipse with A first".into()),
+ },
+ Cmd::ToggleVisible | Cmd::ToggleLocked | Cmd::ToggleClip => layer.is_none().then(pick_layer).flatten(),
+ Cmd::ToggleLockAlpha => match layer {
+ None => pick_layer(),
+ Some(l) if l.kind() != LayerKind::Paint => Some("only paint layers lock their alpha".into()),
+ _ => None,
+ },
+ Cmd::AddMask | Cmd::AddMaskHiding => match layer {
+ None => pick_layer(),
+ Some(_) if self.scene.active_is_mask() => Some("this is a mask already".into()),
+ Some(l) if l.mask.is_some() => Some(format!("{} has a mask already", l.name)),
+ _ => None,
+ },
+ Cmd::PaintMask | Cmd::ToggleMask | Cmd::RemoveMask | Cmd::TintMask => {
+ match (mask.is_some(), self.scene.active_is_mask()) {
+ (_, true) if cmd == Cmd::PaintMask => Some("you are painting on the mask".into()),
+ (false, false) => Some("the active layer has no mask".into()),
+ _ => None,
+ }
+ }
+ Cmd::BackToLayer => (!self.scene.active_is_mask()).then(|| "you are not painting on a mask".to_string()),
+ Cmd::OnionLayer => match layer {
+ None => pick_layer(),
+ Some(l) if matches!(l.kind(), LayerKind::Paint | LayerKind::Vector) => None,
+ Some(_) => Some("only paint and vector layers have an onion".into()),
+ },
+ Cmd::NewDrawing | Cmd::NewDrawingAfter | Cmd::InsertFrame | Cmd::InsertFrameAll => {
+ self.timeline_edit().or_else(|| {
+ self.here()
+ .is_none()
+ .then(|| "pick a paint or vector layer first".to_string())
+ })
+ }
+ Cmd::Duplicate | Cmd::DeleteDrawing => self.timeline_edit().or_else(|| {
+ self.drawing_here()
+ .is_none()
+ .then(|| "no drawing on this frame of the active layer".to_string())
+ }),
+ Cmd::Unlink => self.timeline_edit().or_else(|| {
+ self.drawing_here()
+ .filter(|(c, _)| c.link.is_some())
+ .is_none()
+ .then(|| "this frame does not show a link".to_string())
+ }),
+ Cmd::Link => self.timeline_edit().or_else(|| {
+ layer
+ .filter(|l| l.cels().iter().any(|c| c.link.is_none()) && l.kind() != LayerKind::Group)
+ .is_none()
+ .then(|| "the active layer has no drawings to show".to_string())
+ }),
+ Cmd::HoldLonger => self.timeline_edit().or_else(|| {
+ self.drawing_here()
+ .is_none()
+ .then(|| "no drawing on this frame".to_string())
+ }),
+ Cmd::HoldShorter => self.timeline_edit().or_else(|| match self.drawing_here() {
+ None => Some("no drawing on this frame".into()),
+ Some((cel, end)) if end != OPEN && end - cel.frame <= 1 => {
+ Some(format!("{} already shows for one frame", cel.id))
+ }
+ _ => None,
+ }),
+ Cmd::RemoveFrame | Cmd::RemoveFrameAll => self.timeline_edit().or_else(|| {
+ if layer.is_none() {
+ pick_layer()
+ } else {
+ (self.scene.bundle.doc.timeline.frames == 1).then(|| "the timeline has one frame".to_string())
+ }
+ }),
+ Cmd::NewPaintLayer | Cmd::NewVectorLayer | Cmd::NewGroupLayer | Cmd::NewAdjustLayer => self.timeline_edit(),
+ Cmd::Unwrap => match self.selection.as_deref().map(|id| self.scene.bundle.doc.item(id)) {
+ Some(Some(klad_core::doc::Item::Node(_, _, n))) if n.shape.generates() => None,
+ _ => Some("select a repeat, scatter or mirror with V first".to_string()),
+ },
+ Cmd::MakeRepeat | Cmd::MakeScatter | Cmd::MakeMirror => match &self.selection {
+ Some(id) if matches!(self.scene.bundle.doc.item(id), Some(klad_core::doc::Item::Node(..))) => None,
+ _ => Some("select a shape with V first".to_string()),
+ },
+ Cmd::DuplicateLayer | Cmd::GroupLayer | Cmd::RenameLayer => match layer {
+ None => pick_layer(),
+ Some(_) if self.scene.active_is_mask() => {
+ Some("a mask goes with its layer: pick the layer itself".into())
+ }
+ _ => self.timeline_edit(),
+ },
+ Cmd::DeleteLayer => match layer {
+ None => pick_layer(),
+ Some(_) if self.scene.active_is_mask() => Some("this is a mask: remove the mask instead".into()),
+ _ => self.timeline_edit(),
+ },
+ Cmd::MoveEarlier | Cmd::MoveLater => self.timeline_edit().or_else(|| match self.drawing_here() {
+ None => Some("no drawing on this frame of the active layer".into()),
+ Some((c, _)) if cmd == Cmd::MoveEarlier && c.frame == 0 => {
+ Some("the drawing starts at frame 0 already".into())
+ }
+ _ => None,
+ }),
+ Cmd::CopyCells => span.is_none().then_some(()).and_then(|_| {
+ self.drawing_here()
+ .is_none()
+ .then(|| "select cells first: drag over them in the timeline".to_string())
+ }),
+ Cmd::PasteCells | Cmd::PasteCellsLinked => match &self.timeline.cells {
+ None => Some("copy cells first: select them and copy the cells".into()),
+ Some(_) => self.timeline_edit(),
+ },
+ Cmd::OnOnes | Cmd::OnTwos | Cmd::OnThrees | Cmd::FitFrames | Cmd::Reverse | Cmd::Pingpong => {
+ need_span().or_else(|| self.timeline_edit())
+ }
+ Cmd::Inbetween => need_span()
+ .or_else(|| self.timeline_edit())
+ .or_else(|| {
+ span.and_then(|s| tweens::keys(&self.scene.bundle.doc, s))
+ .is_none()
+ .then(|| {
+ "select from one drawing to the frame where another starts, on a paint layer".to_string()
+ })
+ })
+ .or_else(|| self.tweening().then(|| "in-betweens are being made".to_string())),
+ Cmd::RedoInbetweens => self.tweening().then(|| "in-betweens are being made".to_string()),
+ Cmd::NewClip => (span.is_none() && self.timeline.range.is_none())
+ .then(|| "select frames or mark a loop range first".to_string()),
+ Cmd::DeleteClip | Cmd::ClipLoops | Cmd::ClipOwnFps => need_clip(),
+ Cmd::ExportGodot => {
+ if self.jobs.busy(crate::jobs::Tag::Export) {
+ Some("an export is running".into())
+ } else {
+ self.godot_folder()
+ .is_empty()
+ .then(|| "type the Godot folder in the clip row first".to_string())
+ }
+ }
+ Cmd::Play => self.busy().then(|| "finish the stroke or drag first".to_string()),
+ _ => None,
+ }
+ }
+
+ fn tweening(&self) -> bool {
+ self.jobs.busy(crate::jobs::Tag::Inbetween)
+ }
+
+ pub(super) fn is_on(&self, cmd: Cmd) -> Option<bool> {
+ let layer = self.scene.active_layer();
+ let layout = &self.settings.layout;
+ let erasing = self.brush == "eraser" || (self.readout.eraser && self.readout.tablet);
+ let on = match cmd {
+ Cmd::Brush => self.tool == Tool::Brush && !erasing,
+ Cmd::Eraser => self.tool == Tool::Brush && erasing,
+ Cmd::FlipView => self.view.is_some_and(|v| v.flip),
+ Cmd::Fill => self.tool == Tool::Fill,
+ Cmd::Shapes => self.tool == Tool::Select,
+ Cmd::Strokes => self.tool == Tool::Strokes,
+ Cmd::Points => self.tool == Tool::Direct,
+ Cmd::Pen => self.tool == Tool::Pen,
+ Cmd::ShapeTool => self.tool == Tool::Shape,
+ Cmd::Symmetry => self.mirror.is_some(),
+ Cmd::Note => self.tool == Tool::Note,
+ Cmd::CutLasso => self.cut_lasso,
+ Cmd::ToggleVisible => layer.is_some_and(|l| l.visible),
+ Cmd::ToggleLocked => layer.is_some_and(|l| l.locked),
+ Cmd::ToggleClip => layer.is_some_and(|l| l.clip),
+ Cmd::ToggleLockAlpha => layer.is_some_and(|l| l.lock_alpha),
+ Cmd::ToggleMask => self.mask_of_active().is_some_and(|m| m.visible),
+ Cmd::TintMask => self.scene.tint_mask,
+ Cmd::OnionLayer => layer.is_some_and(|l| self.scene.onion_marked.contains(&l.id)),
+ Cmd::ExposeOnes => self.timeline.on == 1,
+ Cmd::ExposeTwos => self.timeline.on == 2,
+ Cmd::ExposeThrees => self.timeline.on == 3,
+ Cmd::Play => self.timeline.player.is_some(),
+ Cmd::LoopRange => self.timeline.range.is_some(),
+ Cmd::Prepare => self.buffering.preparing.is_some(),
+ Cmd::Onion => self.scene.onion_on,
+ Cmd::OnionSettings => self.windows.onion,
+ Cmd::EveryLayer => self.timeline.ask.every_layer,
+ Cmd::ClipLoops => self.current_clip().is_some_and(|c| c.looping),
+ Cmd::ClipOwnFps => self.current_clip().is_some_and(|c| c.fps.is_some()),
+ Cmd::HideAll => layout.hidden,
+ Cmd::HideDock => !layout.dock,
+ Cmd::LayersPane => layout.dock && layout.is_open(Pane::Layers),
+ Cmd::ToolPane => layout.dock && layout.is_open(Pane::Tool),
+ Cmd::InspectorPane => layout.dock && layout.is_open(Pane::Inspector),
+ Cmd::NotesPane => layout.dock && layout.is_open(Pane::Notes),
+ Cmd::HistoryPane => layout.dock && layout.is_open(Pane::History),
+ Cmd::Timeline => layout.timeline,
+ Cmd::Numbers => layout.numbers,
+ Cmd::Settings => self.windows.settings,
+ Cmd::About => self.windows.about,
+ Cmd::BrushWindow => self.windows.brush,
+ Cmd::MessageLog => self.windows.log,
+ Cmd::Spin => self.spin,
+ Cmd::Link => self.windows.link,
+ _ => return None,
+ };
+ Some(on)
+ }
+
+ fn mask_of_active(&self) -> Option<&klad_core::doc::Layer> {
+ match self.scene.active_is_mask() {
+ true => self.scene.active_layer(),
+ false => self.scene.active_layer().and_then(|l| l.mask.as_deref()),
+ }
+ }
+
+ fn owner_path(&self) -> Vec<usize> {
+ match self.scene.active.last() {
+ Some(&MASK) => self.scene.active[..self.scene.active.len() - 1].to_vec(),
+ _ => self.scene.active.clone(),
+ }
+ }
+
+ fn set_active(&mut self, key: &str, value: serde_json::Value) -> Result<()> {
+ let Some(id) = self.scene.active_id() else {
+ return Ok(());
+ };
+ self.set(&id, vec![(key.to_string(), value)])
+ }
+
+ fn pane(&mut self, pane: Pane) {
+ self.settings.layout.toggle(pane);
+ self.settings_dirty = true;
+ }
+
+ fn retime(&mut self, how: Retime) -> Result<()> {
+ self.span_action(SpanAction::Retime(how))
+ }
+
+ pub(super) fn invoke(&mut self, cmd: Cmd) -> Result<()> {
+ if let Some(reason) = self.can_run(cmd) {
+ self.say(Tone::Refused, reason);
+ return Ok(());
+ }
+ let id = cmd.spec().id.to_string();
+ let recent = &mut self.settings.recent_commands;
+ if recent.first() != Some(&id) {
+ recent.retain(|r| *r != id);
+ recent.insert(0, id);
+ recent.truncate(RECENT);
+ self.settings_dirty = true;
+ }
+ self.run(cmd)
+ }
+
+ pub(super) fn recent_commands(&self) -> Vec<Cmd> {
+ self.settings
+ .recent_commands
+ .iter()
+ .filter_map(|id| Cmd::find(id))
+ .collect()
+ }
+
+ fn run(&mut self, cmd: Cmd) -> Result<()> {
+ let area = self.canvas_rect.size();
+ let frame = self.shown_frame();
+ let last = self.scene.bundle.doc.timeline.frames - 1;
+ match cmd {
+ Cmd::Brush => {
+ self.tool = Tool::Brush;
+ if self.brush == "eraser" {
+ let back = self.previous_brush.clone();
+ self.pick(&back);
+ }
+ }
+ Cmd::Eraser => {
+ self.tool = Tool::Brush;
+ if self.brush == "eraser" {
+ let back = self.previous_brush.clone();
+ self.pick(&back);
+ } else {
+ self.previous_brush = self.brush.clone();
+ self.pick("eraser");
+ }
+ }
+ Cmd::Fill => self.tool = Tool::Fill,
+ Cmd::Shapes => self.tool = Tool::Select,
+ Cmd::Strokes => self.tool = Tool::Strokes,
+ Cmd::Points => self.tool = Tool::Direct,
+ Cmd::Pen => self.tool = Tool::Pen,
+ Cmd::ShapeTool => self.tool = Tool::Shape,
+ Cmd::Symmetry => {
+ self.mirror = match self.mirror {
+ Some(_) => None,
+ None => Some(self.scene.size().0 as f32 / 2.0),
+ }
+ }
+ Cmd::MakeRepeat => self.wrap("repeat")?,
+ Cmd::MakeScatter => self.wrap("scatter")?,
+ Cmd::MakeMirror => self.wrap("mirror")?,
+ Cmd::Unwrap => self.unwrap()?,
+ Cmd::ImportPicture => self.windows.import = !self.windows.import,
+ Cmd::Parallax => {}
+ Cmd::Note => self.tool = Tool::Note,
+ Cmd::Smaller => self.size = (self.size / 1.25).max(0.5),
+ Cmd::Bigger => self.size = (self.size * 1.25).min(800.0),
+ Cmd::Fit => self.view = Some(View::fit(self.canvas_size(), area)),
+ Cmd::ActualSize => {
+ let ppp = self.ctx.pixels_per_point();
+ if let Some(view) = self.view.as_mut() {
+ view.zoom_at(1.0 / (view.zoom * ppp), area / 2.0, area);
+ }
+ }
+ Cmd::TurnRight | Cmd::TurnLeft => {
+ let step = if cmd == Cmd::TurnLeft { -15.0f32 } else { 15.0 };
+ if let Some(view) = self.view.as_mut() {
+ view.rotate_at(step.to_radians(), area / 2.0, area);
+ }
+ }
+ Cmd::Undo => self.step(Stack::Undo)?,
+ Cmd::Redo => self.step(Stack::Redo)?,
+ Cmd::Delete => match self.tool {
+ Tool::Note => self.remove_open_pin()?,
+ _ if self.on_marks() => self.edit_picked(LassoAction::Remove)?,
+ Tool::Direct => {
+ let points: Vec<usize> = self
+ .direct
+ .as_ref()
+ .map_or(Vec::new(), |d| d.points.iter().copied().collect());
+ self.commit_path(PathEdit::Remove { points })?;
+ }
+ _ => {
+ if let Some(id) = self.selection.take() {
+ self.apply(vec![Op::Remove { ids: vec![id] }])?;
+ }
+ }
+ },
+ Cmd::Deselect => {
+ self.timeline.span = None;
+ match self.tool {
+ Tool::Strokes => self.picked = None,
+ Tool::Direct => self.direct = None,
+ Tool::Select => {
+ self.selection = None;
+ self.picked = None;
+ }
+ _ => self.selection = None,
+ }
+ self.note_at = None;
+ self.lasso = None;
+ self.point_drag = None;
+ }
+ Cmd::Copy => {
+ let ctx = self.ctx.clone();
+ self.copy_picked(&ctx);
+ }
+ Cmd::Paste => self.paste()?,
+ Cmd::SelectAll => self.select_all_strokes(),
+ Cmd::CutLasso => self.cut_lasso = !self.cut_lasso,
+ Cmd::Recolour => self.recolour_picked()?,
+ Cmd::Thinner => self.size_picked(0.8)?,
+ Cmd::Thicker => self.size_picked(1.25)?,
+ Cmd::FlipH => self.flip(true)?,
+ Cmd::FlipV => self.flip(false)?,
+ Cmd::TurnLeft90 => self.turn(-90.0)?,
+ Cmd::TurnRight90 => self.turn(90.0)?,
+ Cmd::DuplicateInPlace => self.duplicate_in_place()?,
+ Cmd::NudgeLeft => self.nudge(-1.0, 0.0)?,
+ Cmd::NudgeRight => self.nudge(1.0, 0.0)?,
+ Cmd::NudgeUp => self.nudge(0.0, -1.0)?,
+ Cmd::NudgeDown => self.nudge(0.0, 1.0)?,
+ Cmd::FlipView => {
+ if let Some(view) = self.view.as_mut() {
+ view.flip_at(area / 2.0, area);
+ }
+ }
+ Cmd::ResetRotation => {
+ if let Some(view) = self.view.as_mut() {
+ let angle = view.angle;
+ view.rotate_at(-angle, area / 2.0, area);
+ }
+ }
+ Cmd::SwapColours => self.swap_colours(),
+ Cmd::Corner | Cmd::Smooth => {
+ let points: Vec<usize> = self
+ .direct
+ .as_ref()
+ .map_or(Vec::new(), |d| d.points.iter().copied().collect());
+ self.commit_path(match cmd {
+ Cmd::Corner => PathEdit::Corner { points },
+ _ => PathEdit::Smooth { points },
+ })?;
+ }
+ Cmd::Simplify => self.commit_path(PathEdit::Simplify {
+ tolerance: self.simplify_px,
+ })?,
+ Cmd::MakePath => self.commit_path(PathEdit::Convert)?,
+ Cmd::AddSwatch => {
+ let edit = PaletteEdit::Add {
+ color: crate::color::hex(self.color),
+ name: self.swatch_name.trim().to_string(),
+ index: None,
+ };
+ self.swatch_name.clear();
+ self.apply(vec![Op::Palette(edit)])?;
+ }
+ Cmd::NewPaintLayer => self.add_layer("paint")?,
+ Cmd::NewGroupLayer => self.new_group(false)?,
+ Cmd::NewAdjustLayer => {
+ self.add_layer_value(json!({"kind": "adjust", "name": "curves", "adjust": {"curves": {}}}))?
+ }
+ Cmd::GroupLayer => self.new_group(true)?,
+ Cmd::DuplicateLayer => self.duplicate_layer()?,
+ Cmd::DeleteLayer => self.delete_layer()?,
+ Cmd::RenameLayer => {
+ if let Some(l) = self.scene.active_layer() {
+ let place = match self.settings.layout.is_open(crate::layout::Pane::Layers) {
+ true => super::layers::Where::Panel,
+ false => super::layers::Where::Timeline,
+ };
+ self.renaming = Some(super::layers::Rename {
+ id: l.id.clone(),
+ text: l.name.clone(),
+ place,
+ });
+ }
+ }
+ Cmd::MoveEarlier => self.move_drawing(-1)?,
+ Cmd::MoveLater => self.move_drawing(1)?,
+ Cmd::CopyCells => self.copy_selected_cells(),
+ Cmd::PasteCells => self.paste_cells(false)?,
+ Cmd::PasteCellsLinked => self.paste_cells(true)?,
+ Cmd::ClipSettings => self.windows.clip = !self.windows.clip,
+ Cmd::NewDocument => self.wants = Some(super::Want::New),
+ Cmd::OpenDocument => self.wants = Some(super::Want::Open),
+ Cmd::OpenRecent => self.wants = Some(super::Want::Recent),
+ Cmd::About => self.windows.about = !self.windows.about,
+ Cmd::CopyPath => {
+ let path = self.scene.bundle.root.display().to_string();
+ self.ctx.copy_text(path.clone());
+ self.say(Tone::Done, format!("copied {path}"));
+ }
+ Cmd::NewVectorLayer => self.add_layer("vector")?,
+ Cmd::ToggleVisible => {
+ let on = self.is_on(cmd) == Some(true);
+ self.set_active("visible", json!(!on))?;
+ }
+ Cmd::ToggleLocked => {
+ let on = self.is_on(cmd) == Some(true);
+ self.set_active("locked", json!(!on))?;
+ }
+ Cmd::ToggleClip => {
+ let on = self.is_on(cmd) == Some(true);
+ self.set_active("clip", json!(!on))?;
+ }
+ Cmd::ToggleLockAlpha => {
+ let on = self.is_on(cmd) == Some(true);
+ self.set_active("lockAlpha", json!(!on))?;
+ }
+ Cmd::AddMask | Cmd::AddMaskHiding => {
+ if let Some(id) = self.scene.active_id() {
+ self.apply(vec![Op::AddMask {
+ mask: json!({}),
+ layer: id,
+ hide: cmd == Cmd::AddMaskHiding,
+ }])?;
+ let mut path = self.scene.active.clone();
+ path.push(MASK);
+ self.activate(path)?;
+ }
+ }
+ Cmd::PaintMask => {
+ let mut path = self.owner_path();
+ path.push(MASK);
+ self.activate(path)?;
+ }
+ Cmd::BackToLayer => {
+ let path = self.owner_path();
+ self.activate(path)?;
+ }
+ Cmd::RemoveMask => {
+ if let Some(id) = self.mask_of_active().map(|m| m.id.clone()) {
+ let path = self.owner_path();
+ self.activate(path)?;
+ self.apply(vec![Op::Remove { ids: vec![id] }])?;
+ }
+ }
+ Cmd::ToggleMask => {
+ if let Some((id, on)) = self.mask_of_active().map(|m| (m.id.clone(), m.visible)) {
+ self.apply(vec![Op::Set {
+ id,
+ props: Map::from_iter([("visible".to_string(), json!(!on))]),
+ }])?;
+ }
+ }
+ Cmd::TintMask => {
+ self.scene.tint_mask = !self.scene.tint_mask;
+ self.dirty.extend(self.scene.all_tiles());
+ }
+ Cmd::OnionLayer => {
+ if let Some(id) = self.scene.active_id() {
+ if !self.scene.onion_marked.remove(&id) {
+ self.scene.onion_marked.insert(id);
+ }
+ self.onion_changed()?;
+ }
+ }
+ Cmd::NextFrame => self.go_to((frame + 1).min(last))?,
+ Cmd::PrevFrame => self.go_to(frame.saturating_sub(1))?,
+ Cmd::NextDrawing => {
+ if let Some(next) = self.drawing_starts().into_iter().find(|f| *f > frame) {
+ self.go_to(next)?;
+ }
+ }
+ Cmd::PrevDrawing => {
+ if let Some(previous) = self.drawing_starts().into_iter().rev().find(|f| *f < frame) {
+ self.go_to(previous)?;
+ }
+ }
+ Cmd::FirstFrame => self.go_to(0)?,
+ Cmd::LastFrame => self.go_to(last)?,
+ Cmd::NewDrawing => self.new_drawing()?,
+ Cmd::NewDrawingAfter => self.next_drawing()?,
+ Cmd::Duplicate => self.duplicate_next()?,
+ Cmd::Link => self.windows.link = !self.windows.link,
+ Cmd::Unlink => self.unlink_here()?,
+ Cmd::DeleteDrawing => self.delete_here()?,
+ Cmd::HoldLonger => self.hold(1)?,
+ Cmd::HoldShorter => self.hold(-1)?,
+ Cmd::InsertFrame => self.frames_at(true, false)?,
+ Cmd::InsertFrameAll => self.frames_at(true, true)?,
+ Cmd::RemoveFrame => self.frames_at(false, false)?,
+ Cmd::RemoveFrameAll => self.frames_at(false, true)?,
+ Cmd::ExposeOnes => self.timeline.on = 1,
+ Cmd::ExposeTwos => self.timeline.on = 2,
+ Cmd::ExposeThrees => self.timeline.on = 3,
+ Cmd::Play => self.play()?,
+ Cmd::Prepare => self.prepare_frames()?,
+ Cmd::LoopRange => {
+ self.timeline.range = match self.timeline.range {
+ Some(_) => None,
+ None => {
+ let f = self.scene.frame;
+ Some((f.saturating_sub(3), (f + 4).min(last)))
+ }
+ };
+ self.onion_changed()?;
+ }
+ Cmd::Onion => self.toggle_onion()?,
+ Cmd::OnionSettings => self.windows.onion = !self.windows.onion,
+ Cmd::OnOnes => self.retime(Retime::On(1))?,
+ Cmd::OnTwos => self.retime(Retime::On(2))?,
+ Cmd::OnThrees => self.retime(Retime::On(3))?,
+ Cmd::FitFrames => self.retime(Retime::Fit(self.timeline.ask.fit))?,
+ Cmd::Reverse => self.retime(Retime::Reverse)?,
+ Cmd::Pingpong => self.retime(Retime::Pingpong)?,
+ Cmd::EveryLayer => self.timeline.ask.every_layer = !self.timeline.ask.every_layer,
+ Cmd::Inbetween => self.span_action(SpanAction::Inbetween)?,
+ Cmd::RedoInbetweens => self.span_action(SpanAction::Redo)?,
+ Cmd::NewClip => {
+ let (from, to) = match (&self.timeline.span, self.timeline.range) {
+ (Some(s), _) => (s.from, s.to),
+ (None, Some(range)) => range,
+ (None, None) => return Ok(()),
+ };
+ self.add_clip(from, to)?;
+ }
+ Cmd::DeleteClip | Cmd::ClipLoops | Cmd::ClipOwnFps => {
+ if let Some(clip) = self.current_clip() {
+ let fps = self.scene.bundle.doc.timeline.fps;
+ let set = |looping, fps| {
+ Op::Clip(ClipEdit::Set {
+ name: clip.name.clone(),
+ rename: None,
+ from: None,
+ to: None,
+ looping,
+ fps,
+ })
+ };
+ let op = match cmd {
+ Cmd::DeleteClip => Op::Clip(ClipEdit::Remove {
+ name: clip.name.clone(),
+ }),
+ Cmd::ClipLoops => set(Some(!clip.looping), None),
+ _ => set(None, Some(clip.fps.is_none().then_some(fps))),
+ };
+ self.timeline_apply(vec![op])?;
+ }
+ }
+ Cmd::ExportGodot => self.export_godot(),
+ Cmd::Palette | Cmd::Keys => {
+ self.palette = match self.palette {
+ Some(_) => None,
+ None => Some(super::PaletteState::default()),
+ }
+ }
+ Cmd::HideAll => self.settings.layout.hidden = !self.settings.layout.hidden,
+ Cmd::HideDock => {
+ let layout = &mut self.settings.layout;
+ layout.dock = !(layout.dock && !layout.hidden);
+ layout.hidden = false;
+ self.settings_dirty = true;
+ }
+ Cmd::LayersPane => self.pane(Pane::Layers),
+ Cmd::ToolPane => self.pane(Pane::Tool),
+ Cmd::InspectorPane => self.pane(Pane::Inspector),
+ Cmd::NotesPane => self.pane(Pane::Notes),
+ Cmd::HistoryPane => self.pane(Pane::History),
+ Cmd::Timeline => {
+ self.settings.layout.timeline = !self.settings.layout.timeline;
+ self.settings_dirty = true;
+ }
+ Cmd::Numbers => {
+ self.settings.layout.numbers = !self.settings.layout.numbers;
+ self.settings_dirty = true;
+ }
+ Cmd::Settings => self.windows.settings = !self.windows.settings,
+ Cmd::BrushWindow => self.windows.brush = !self.windows.brush,
+ Cmd::MessageLog => self.windows.log = !self.windows.log,
+ Cmd::Spin => self.spin = !self.spin,
+ Cmd::ResetNumbers => *lock(&self.stats) = Stats::default(),
+ Cmd::Eyedropper | Cmd::Pan | Cmd::Zoom | Cmd::FlipFrames | Cmd::Roll | Cmd::SizeDrag => {}
+ }
+ Ok(())
+ }
+
+ pub(super) fn command_keys(&mut self, ui: &egui::Ui) -> Result<()> {
+ if ui.ctx().egui_wants_keyboard_input() {
+ return Ok(());
+ }
+ if self.capturing.is_some() {
+ self.capture_key(ui);
+ return Ok(());
+ }
+ self.flip_and_roll(ui)?;
+ let bindings = self.bindings.clone();
+ let pressed: Vec<(Option<Cmd>, bool, bool)> = ui.input(|i| {
+ i.events
+ .iter()
+ .filter_map(|e| match e {
+ egui::Event::Copy => Some((Some(Cmd::Copy), false, false)),
+ egui::Event::Paste(_) => Some((Some(Cmd::Paste), false, false)),
+ egui::Event::Key {
+ key,
+ pressed: true,
+ repeat,
+ modifiers,
+ ..
+ } => Some((bindings.for_key(*key, *modifiers), *repeat, modifiers.shift)),
+ _ => None,
+ })
+ .collect()
+ });
+ let mut done = BTreeSet::new();
+ pressed
+ .into_iter()
+ .filter_map(|(cmd, repeat, shift)| cmd.map(|c| (c, repeat, shift)))
+ .try_for_each(|(cmd, repeat, shift)| {
+ self.key_shift = shift;
+ let skip = repeat
+ && match cmd.spec().repeat {
+ Repeat::No => true,
+ Repeat::Yes => false,
+ Repeat::WhenShown => self.waiting(),
+ };
+ let once = matches!(cmd, Cmd::Copy | Cmd::Paste);
+ if skip || (once && !done.insert(cmd)) {
+ return Ok(());
+ }
+ match cmd {
+ Cmd::Copy if !self.on_marks() => Ok(()),
+ Cmd::Paste if self.clipboard.is_none() => Ok(()),
+ _ => self.invoke(cmd),
+ }
+ })
+ }
+
+ pub(super) fn tab_keys(&mut self) -> Result<()> {
+ std::mem::take(&mut self.tabs)
+ .into_iter()
+ .try_for_each(|shift| self.invoke(if shift { Cmd::HideDock } else { Cmd::HideAll }))
+ }
+
+ pub(super) fn run_queued(&mut self) -> Result<()> {
+ std::mem::take(&mut self.queued)
+ .into_iter()
+ .try_for_each(|cmd| self.invoke(cmd))
+ }
+
+ pub(super) fn command_hint(&self, cmd: Cmd) -> String {
+ let hint = cmd.spec().hint_with(&self.bindings.label(cmd));
+ match self.can_run(cmd) {
+ Some(reason) if !cmd.spec().is_hold() => format!("{hint}\n\nnot now: {reason}"),
+ _ => hint,
+ }
+ }
+
+ pub(super) fn command_button(&mut self, ui: &mut egui::Ui, cmd: Cmd, label: Option<&str>) -> egui::Response {
+ let size = match label {
+ Some(_) => theme::BODY,
+ None => theme::ICON,
+ };
+ self.command_sized(ui, cmd, label, size, egui::vec2(theme::TARGET, theme::TARGET))
+ }
+
+ pub(super) fn command_sized(
+ &mut self,
+ ui: &mut egui::Ui,
+ cmd: Cmd,
+ label: Option<&str>,
+ size: f32,
+ min: egui::Vec2,
+ ) -> egui::Response {
+ let spec = cmd.spec();
+ let text = match label {
+ Some(label) => format!("{} {label}", spec.icon),
+ None => spec.icon.to_string(),
+ };
+ let button = egui::Button::new(RichText::new(text).size(size))
+ .selected(self.is_on(cmd) == Some(true))
+ .min_size(min);
+ let response = ui
+ .add_enabled(self.can_run(cmd).is_none(), button)
+ .hint(self.command_hint(cmd));
+ if response.clicked() {
+ self.queued.push(cmd);
+ }
+ response
+ }
+
+ pub(super) fn command_check(&mut self, ui: &mut egui::Ui, cmd: Cmd, label: &str) -> egui::Response {
+ let mut on = self.is_on(cmd) == Some(true);
+ let response = ui
+ .add_enabled(self.can_run(cmd).is_none(), egui::Checkbox::new(&mut on, label))
+ .hint(self.command_hint(cmd));
+ if response.changed() {
+ self.queued.push(cmd);
+ }
+ response
+ }
+
+ pub(super) fn key_letter(&self, ui: &egui::Ui, rect: egui::Rect, cmd: Cmd) {
+ if let Some(k) = self
+ .bindings
+ .keys(cmd)
+ .first()
+ .filter(|k| !k.command && !k.alt && !k.shift)
+ {
+ ui.painter().text(
+ rect.right_bottom() - egui::vec2(3.0, 2.0),
+ egui::Align2::RIGHT_BOTTOM,
+ k.label(),
+ egui::FontId::proportional(9.0),
+ theme::WEAK,
+ );
+ }
+ }
+}
diff --git a/crates/app/src/editor/copy.rs b/crates/app/src/editor/copy.rs
new file mode 100644
index 0000000..966e4f4
--- /dev/null
+++ b/crates/app/src/editor/copy.rs
@@ -0,0 +1,267 @@
+use super::{Editor, Part, Picked, Tool, ms};
+use crate::messages::Tone;
+use anyhow::Result;
+use klad_core::doc::Kind;
+use klad_core::markedit::{self, MarkChange, Side, address};
+use klad_core::ops::{CopySpec, CopyTarget, Op};
+use klad_core::stroke::Mark;
+use std::time::Instant;
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Piece {
+ layer: String,
+ cel: String,
+ cut: Option<Vec<[f32; 2]>>,
+ around: Vec<u32>,
+ whole: Vec<u32>,
+}
+
+impl Piece {
+ fn count(&self) -> usize {
+ self.around.len() + self.whole.len()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Copied {
+ pieces: Vec<Piece>,
+}
+
+impl Copied {
+ fn count(&self) -> usize {
+ self.pieces.iter().map(Piece::count).sum()
+ }
+
+ fn whence(&self) -> String {
+ match &self.pieces[..] {
+ [one] => one.cel.clone(),
+ many => format!("{} layers", many.len()),
+ }
+ }
+}
+
+pub(super) fn piece(layer: &str, cel: &str, ids: &[u32], cut: Option<&Vec<[f32; 2]>>, marks: &[Mark]) -> Piece {
+ let (around, whole, cut) = match cut {
+ Some(polygon) => {
+ let around: Vec<u32> = markedit::sides(marks, polygon)
+ .into_iter()
+ .filter(|(_, side)| *side != Side::Outside)
+ .map(|(id, _)| id)
+ .collect();
+ let whole = ids.iter().copied().filter(|id| !around.contains(id)).collect();
+ let cut = (!around.is_empty()).then(|| polygon.clone());
+ (around, whole, cut)
+ }
+ None => (Vec::new(), ids.to_vec(), None),
+ };
+ Piece {
+ layer: layer.to_string(),
+ cel: cel.to_string(),
+ cut,
+ around,
+ whole,
+ }
+}
+
+pub(super) fn paste_ops(piece: &Piece, to: &CopyTarget) -> Vec<Op> {
+ let op = |ids: &[u32], cut: Option<Vec<[f32; 2]>>| {
+ Op::Copy(CopySpec {
+ ids: ids.iter().map(|id| address(&piece.cel, *id)).collect(),
+ to: to.clone(),
+ transform: None,
+ cut,
+ })
+ };
+ let around = (!piece.around.is_empty()).then(|| op(&piece.around, piece.cut.clone()));
+ let whole = (!piece.whole.is_empty()).then(|| op(&piece.whole, None));
+ around.into_iter().chain(whole).collect()
+}
+
+impl Editor {
+ pub(super) fn copied(&self) -> Option<Copied> {
+ let picked = self.picked.as_ref()?;
+ let layer = self.scene.active_id()?;
+ let pieces: Vec<Piece> = std::iter::once(piece(
+ &layer,
+ &picked.cel,
+ &picked.ids,
+ picked.cut.as_ref(),
+ self.scene.active_marks(),
+ ))
+ .chain(picked.more.iter().map(|p| {
+ piece(
+ &p.layer,
+ &p.cel,
+ &p.ids,
+ picked.cut.as_ref(),
+ self.scene.marks_of(&p.cel),
+ )
+ }))
+ .filter(|p| p.count() > 0)
+ .collect();
+ (!pieces.is_empty()).then_some(Copied { pieces })
+ }
+
+ pub(super) fn copy_picked(&mut self, ctx: &egui::Context) {
+ let Some(copied) = self.copied() else {
+ self.say(Tone::Refused, "select strokes with S first; cmd C copies them");
+ return;
+ };
+ ctx.copy_text(format!("klad: {} marks of {}", copied.count(), copied.whence()));
+ self.say(
+ Tone::Done,
+ format!(
+ "copied {} marks of {}: go to another frame and cmd V puts them there, in place",
+ copied.count(),
+ copied.whence()
+ ),
+ );
+ self.clipboard = Some(copied);
+ }
+
+ pub(super) fn paste(&mut self) -> Result<()> {
+ match self.clipboard.clone() {
+ Some(copied) => self.paste_copied(copied, "pasted"),
+ None => Ok(()),
+ }
+ }
+
+ fn target(&self, layer: &klad_core::doc::Layer) -> CopyTarget {
+ let frame = self.scene.frame;
+ match layer.content_at(frame) {
+ Some(cel) => CopyTarget::Cel(cel.id.clone()),
+ None => CopyTarget::Frame {
+ frame,
+ layer: Some(layer.id.clone()),
+ },
+ }
+ }
+
+ pub(super) fn paste_copied(&mut self, copied: Copied, word: &str) -> Result<()> {
+ let doc = &self.scene.bundle.doc;
+ let paintable = |l: &&klad_core::doc::Layer| l.kind() == Kind::Paint && !l.locked;
+ let targets: Vec<(&Piece, CopyTarget)> = match &copied.pieces[..] {
+ [one] => {
+ let Some(layer) = self.scene.active_layer().filter(paintable) else {
+ self.say(Tone::Refused, "make a paint layer active to paste strokes into it");
+ return Ok(());
+ };
+ vec![(one, self.target(layer))]
+ }
+ many => {
+ let missing: Vec<&str> = many
+ .iter()
+ .filter(|p| doc.layer(&p.layer).filter(paintable).is_none())
+ .map(|p| p.layer.as_str())
+ .collect();
+ if !missing.is_empty() {
+ self.say(
+ Tone::Refused,
+ format!("{word}: the layers {} are gone or locked", missing.join(", ")),
+ );
+ return Ok(());
+ }
+ many.iter()
+ .filter_map(|p| doc.layer(&p.layer).map(|l| (p, self.target(l))))
+ .collect()
+ }
+ };
+ let frame = self.scene.frame;
+ let start = Instant::now();
+ let ops: Vec<Op> = targets.iter().flat_map(|(p, to)| paste_ops(p, to)).collect();
+ let (dirty, applied) = match self.scene.apply_with(&ops, &self.brushes) {
+ Ok(done) => done,
+ Err(e) => {
+ self.say(Tone::Refused, format!("{word}: failed, {e:#}"));
+ return Ok(());
+ }
+ };
+ self.dirty.extend(dirty);
+ let made: Vec<(String, String, u32)> = applied
+ .marks
+ .iter()
+ .flat_map(|p| {
+ p.changes.iter().flat_map(move |c| match c {
+ MarkChange::Paste { made, .. } => {
+ made.iter().map(|m| (p.layer.clone(), p.cel.clone(), m.to)).collect()
+ }
+ _ => Vec::new(),
+ })
+ })
+ .collect();
+ let active = self.scene.active_cel();
+ if let Some(cel) = active.clone().filter(|_| !made.is_empty()) {
+ if self.tool != Tool::Select {
+ self.tool = Tool::Strokes;
+ }
+ self.selection = None;
+ let ids = made
+ .iter()
+ .filter(|(_, c, _)| *c == cel)
+ .map(|(_, _, id)| *id)
+ .collect();
+ let more =
+ made.iter()
+ .filter(|(_, c, _)| *c != cel)
+ .fold(Vec::<Part>::new(), |mut parts, (layer, c, id)| {
+ match parts.iter_mut().find(|p| p.cel == *c) {
+ Some(p) => p.ids.push(*id),
+ None => parts.push(Part {
+ layer: layer.clone(),
+ cel: c.clone(),
+ ids: vec![*id],
+ }),
+ }
+ parts
+ });
+ self.picked = Some(Picked {
+ more,
+ ..Picked::whole(cel.clone(), ids)
+ });
+ self.say(
+ Tone::Done,
+ format!(
+ "{word} {} marks into {} on frame {frame} in {:.0} ms (one cmd Z takes them off)",
+ made.len(),
+ copied.whence(),
+ ms(start)
+ ),
+ );
+ }
+ self.forget_missing_selection();
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::stroke::Stroke;
+
+ fn line(id: u32, x: f32) -> Mark {
+ Stroke::new(id, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1)
+ .with_points(&[(x, 10.0, 1.0), (x, 90.0, 1.0)], 8.0)
+ .into()
+ }
+
+ #[test]
+ fn a_cut_selection_copies_the_parts_inside_and_whole_picks_whole() {
+ let marks = vec![line(1, 20.0), line(2, 50.0), line(3, 200.0)];
+ let polygon = vec![[0.0, 0.0], [100.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
+ let cut = piece("l4", "c4", &[3], Some(&polygon), &marks);
+ assert_eq!((cut.around.clone(), cut.whole.clone()), (vec![1, 2], vec![3]));
+ let ops = paste_ops(&cut, &CopyTarget::Cel("c9".into()));
+ assert_eq!(ops.len(), 2);
+ let Op::Copy(first) = &ops[0] else { panic!() };
+ assert_eq!(first.ids, ["c4:s1", "c4:s2"]);
+ assert_eq!(first.cut.as_deref(), Some(&polygon[..]));
+ let Op::Copy(second) = &ops[1] else { panic!() };
+ assert_eq!(
+ (second.ids.clone(), second.cut.clone()),
+ (vec!["c4:s3".to_string()], None)
+ );
+ let plain = piece("l4", "c4", &[2], None, &marks);
+ assert_eq!(paste_ops(&plain, &CopyTarget::Cel("c9".into())).len(), 1);
+ assert_eq!(piece("l4", "c4", &[], None, &marks).count(), 0);
+ }
+}
diff --git a/crates/app/src/editor/depth.rs b/crates/app/src/editor/depth.rs
new file mode 100644
index 0000000..2777357
--- /dev/null
+++ b/crates/app/src/editor/depth.rs
@@ -0,0 +1,186 @@
+use super::Editor;
+use crate::color;
+use crate::messages::Tone;
+use crate::theme::Hint;
+use anyhow::Result;
+use egui::{Color32, Key, Rect, TextureHandle, TextureOptions, pos2, vec2};
+use klad_core::doc::Layer;
+use klad_core::look::Atmosphere;
+use klad_core::ops::Op;
+use serde_json::json;
+use std::sync::mpsc::Receiver;
+
+type Planes = Vec<(f32, egui::ColorImage)>;
+
+#[derive(Default)]
+pub(super) struct Parallax {
+ key: (u64, u32),
+ pub(super) planes: Vec<(f32, TextureHandle)>,
+ job: Option<Receiver<Result<Planes>>>,
+}
+
+pub(super) const SHIFT: f32 = 0.08;
+
+impl Editor {
+ pub(super) fn depth_section(&mut self, ui: &mut egui::Ui, layer: &Layer) -> Result<()> {
+ if !self.scene.bundle.doc.layers.iter().any(|l| l.id == layer.id) {
+ return Ok(());
+ }
+ ui.separator();
+ let id = layer.id.clone();
+ ui.horizontal(|ui| {
+ let depth = layer.depth.unwrap_or(0.0);
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.depth"),
+ "depth ",
+ depth,
+ 0.0..=100.0,
+ 0.02,
+ "how far away this plane is: 0 is near; deeper planes take more of the atmosphere and move less in the parallax preview (hold D)",
+ ) {
+ let value = if v <= 0.0 { json!(null) } else { json!(v) };
+ self.check(|e| e.set(&id, vec![("depth".into(), value)]));
+ }
+ });
+ let air = self.scene.bundle.doc.atmosphere.clone();
+ let mut on = air.is_some();
+ if ui
+ .checkbox(&mut on, "atmosphere")
+ .hint("fog, blur and paler colour for the planes with a depth, more the deeper they are")
+ .changed()
+ {
+ return self.apply(vec![Op::Atmosphere(on.then(Atmosphere::default))]);
+ }
+ let Some(air) = air else {
+ return Ok(());
+ };
+ let mut next = air.clone();
+ let current = self.color;
+ ui.horizontal_wrapped(|ui| {
+ let fog = color::rgba_of(&air.color).unwrap_or([0.6, 0.65, 0.7, 1.0]);
+ if color::swatch(ui, fog, false, crate::theme::TARGET)
+ .hint(format!(
+ "the fog colour, {}; click to use the current colour",
+ air.color
+ ))
+ .clicked()
+ {
+ next.color = color::hex(current);
+ }
+ let mut graded = air.top.is_some();
+ if ui
+ .checkbox(&mut graded, "by height")
+ .hint("a second fog colour at the top of the picture, blending down to the first")
+ .changed()
+ {
+ next.top = graded.then(|| color::hex(current));
+ }
+ if let Some(top) = &air.top {
+ let rgba = color::rgba_of(top).unwrap_or([0.8, 0.85, 0.9, 1.0]);
+ if color::swatch(ui, rgba, false, crate::theme::TARGET)
+ .hint(format!(
+ "the fog colour at the top, {top}; click to use the current colour"
+ ))
+ .clicked()
+ {
+ next.top = Some(color::hex(current));
+ }
+ }
+ });
+ ui.horizontal_wrapped(|ui| {
+ [
+ ("density ", air.density, "how fast the fog thickens with depth"),
+ ("blur ", air.blur, "px of blur per unit of depth"),
+ ("paler ", air.desaturate, "how much colour each unit of depth takes out"),
+ ]
+ .iter()
+ .enumerate()
+ .for_each(|(i, (label, value, hint))| {
+ if let Some(v) = self.number(ui, &format!("air.{i}"), label, *value, 0.0..=20.0, 0.01, hint) {
+ match i {
+ 0 => next.density = v,
+ 1 => next.blur = v,
+ _ => next.desaturate = v,
+ }
+ }
+ });
+ });
+ if next != air {
+ return self.apply(vec![Op::Atmosphere(Some(next))]);
+ }
+ Ok(())
+ }
+
+ pub(super) fn parallax(&mut self, ui: &egui::Ui, view: crate::view::View, rect: Rect) {
+ let typing = ui.ctx().egui_wants_keyboard_input();
+ let held = !typing && ui.input(|i| i.key_down(Key::D) && !i.modifiers.any());
+ if !held {
+ return;
+ }
+ let key = (self.scene.bundle.doc.rev, self.scene.frame);
+ if self.depth.key != key || (self.depth.planes.is_empty() && self.depth.job.is_none()) {
+ let job = self.scene.planes_job();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let ctx = ui.ctx().clone();
+ std::thread::spawn(move || {
+ let _ = tx.send(job());
+ ctx.request_repaint();
+ });
+ self.depth = Parallax {
+ key,
+ planes: Vec::new(),
+ job: Some(rx),
+ };
+ }
+ if let Some(done) = self.depth.job.as_ref().and_then(|rx| rx.try_recv().ok()) {
+ self.depth.job = None;
+ match done {
+ Ok(images) => {
+ self.depth.planes = images
+ .into_iter()
+ .enumerate()
+ .map(|(i, (depth, image))| {
+ (
+ depth,
+ ui.ctx()
+ .load_texture(format!("plane {i}"), image, TextureOptions::LINEAR),
+ )
+ })
+ .collect();
+ }
+ Err(e) => self.say(Tone::Error, format!("the parallax preview: {e:#}")),
+ }
+ }
+ let painter = ui.painter().with_clip_rect(rect);
+ if self.depth.planes.is_empty() {
+ painter.text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ "preparing the planes...",
+ egui::FontId::proportional(16.0),
+ Color32::WHITE,
+ );
+ ui.ctx().request_repaint();
+ return;
+ }
+ let (w, h) = self.scene.size();
+ let canvas = Rect::from_two_pos(
+ self.screen(view, rect, vec2(0.0, 0.0)),
+ self.screen(view, rect, vec2(w as f32, h as f32)),
+ );
+ let pointer = ui.input(|i| i.pointer.hover_pos()).unwrap_or(rect.center());
+ let offset = pointer - rect.center();
+ painter.rect_filled(rect, 0.0, Color32::from_gray(30));
+ self.depth.planes.iter().for_each(|(depth, texture)| {
+ let shift = offset * SHIFT / (1.0 + depth.max(0.0));
+ painter.image(
+ texture.id(),
+ canvas.translate(shift),
+ Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
+ Color32::WHITE,
+ );
+ });
+ ui.ctx().request_repaint();
+ }
+}
diff --git a/crates/app/src/editor/history.rs b/crates/app/src/editor/history.rs
new file mode 100644
index 0000000..d24be15
--- /dev/null
+++ b/crates/app/src/editor/history.rs
@@ -0,0 +1,172 @@
+use super::Editor;
+use crate::commands::Cmd;
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use anyhow::Result;
+use egui::{Color32, RichText};
+use klad_core::bundle::{Bundle, now_ms};
+use klad_core::history::{self, Stack};
+use std::time::Instant;
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Row {
+ pub seq: u64,
+ pub who: String,
+ pub what: String,
+ pub at_ms: u64,
+ pub undone: bool,
+}
+
+pub(super) fn who(author: &str) -> String {
+ match author {
+ "editor" => "you".into(),
+ "cli" => "agent".into(),
+ other => other.into(),
+ }
+}
+
+pub(super) fn rows(bundle: &Bundle) -> Result<Vec<Row>> {
+ let row = |e: history::Entry, undone: bool| Row {
+ seq: e.seq,
+ who: who(&e.author),
+ what: e.summary,
+ at_ms: e.at_ms,
+ undone,
+ };
+ let mut redo: Vec<Row> = history::entries(bundle, Stack::Redo)?
+ .into_iter()
+ .map(|e| row(e, true))
+ .collect();
+ redo.reverse();
+ Ok(redo
+ .into_iter()
+ .chain(
+ history::entries(bundle, Stack::Undo)?
+ .into_iter()
+ .map(|e| row(e, false)),
+ )
+ .collect())
+}
+
+pub(super) fn steps_to(rows: &[Row], clicked: usize) -> Option<(Stack, usize)> {
+ let undone = rows.iter().filter(|r| r.undone).count();
+ match clicked.checked_sub(undone) {
+ Some(0) => None,
+ Some(below) if clicked < rows.len() => Some((Stack::Undo, below)),
+ Some(_) => None,
+ None => Some((Stack::Redo, undone - clicked)),
+ }
+}
+
+pub(super) fn ago(at_ms: u64, now: u64) -> String {
+ let s = now.saturating_sub(at_ms) / 1000;
+ match s {
+ 0..=59 => format!("{s} s ago"),
+ 60..=3599 => format!("{} min ago", s / 60),
+ 3600..=86_399 => format!("{} h ago", s / 3600),
+ _ => format!("{} days ago", s / 86_400),
+ }
+}
+
+impl Editor {
+ pub(super) fn history_rows(&mut self) -> Vec<Row> {
+ let rev = self.scene.bundle.doc.rev;
+ match &self.history {
+ Some((r, rows)) if *r == rev => rows.clone(),
+ _ => {
+ let rows = rows(&self.scene.bundle).unwrap_or_default();
+ self.history = Some((rev, rows.clone()));
+ rows
+ }
+ }
+ }
+
+ pub(super) fn step_to(&mut self, stack: Stack, count: usize) -> Result<()> {
+ let start = Instant::now();
+ (0..count).try_for_each(|_| self.step(stack))?;
+ self.history = None;
+ let word = if stack == Stack::Undo { "undid" } else { "redid" };
+ let text = format!(
+ "{word} {count} step{} in {:.0} ms",
+ if count == 1 { "" } else { "s" },
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ self.measure("undo", text.clone());
+ self.say(Tone::Done, text);
+ Ok(())
+ }
+
+ pub(super) fn history_pane(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ ui.horizontal_wrapped(|ui| {
+ self.command_button(ui, Cmd::Undo, Some("undo"));
+ self.command_button(ui, Cmd::Redo, Some("redo"));
+ });
+ let rows = self.history_rows();
+ if rows.is_empty() {
+ ui.label(RichText::new("nothing done yet").color(theme::WEAK));
+ return Ok(());
+ }
+ let now = now_ms();
+ let mut clicked = None;
+ let undone = rows.iter().filter(|r| r.undone).count();
+ rows.iter().enumerate().for_each(|(i, r)| {
+ if i == undone {
+ ui.label(RichText::new("the document is here").small().color(theme::ACCENT));
+ }
+ let colour = match (r.undone, r.who.as_str()) {
+ (true, _) => theme::WEAK,
+ (_, "agent") => Color32::from_rgb(150, 200, 255),
+ _ => theme::TEXT,
+ };
+ let text = match r.undone {
+ true => format!("undone {} {} {}", r.who, r.what, ago(r.at_ms, now)),
+ false => format!("{} {} {}", r.who, r.what, ago(r.at_ms, now)),
+ };
+ let hint = match steps_to(&rows, i) {
+ Some((Stack::Undo, n)) => format!("undo {n} step{} to come back here", if n == 1 { "" } else { "s" }),
+ Some((Stack::Redo, n)) => format!("redo {n} step{} to come back here", if n == 1 { "" } else { "s" }),
+ None => "the latest step, where the document is".to_string(),
+ };
+ if ui
+ .add(egui::Button::new(RichText::new(text).color(colour)).frame(false))
+ .hint(hint)
+ .clicked()
+ {
+ clicked = Some(i);
+ }
+ });
+ if let Some((stack, n)) = clicked.and_then(|i| steps_to(&rows, i)) {
+ self.step_to(stack, n)?;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn row(seq: u64, undone: bool) -> Row {
+ Row {
+ seq,
+ who: "agent".into(),
+ what: format!("step {seq}"),
+ at_ms: 0,
+ undone,
+ }
+ }
+
+ #[test]
+ fn a_click_on_a_step_undoes_or_redoes_back_to_it() {
+ let rows = vec![row(9, true), row(8, true), row(7, false), row(6, false), row(5, false)];
+ assert_eq!(steps_to(&rows, 0), Some((Stack::Redo, 2)));
+ assert_eq!(steps_to(&rows, 1), Some((Stack::Redo, 1)));
+ assert_eq!(steps_to(&rows, 2), None);
+ assert_eq!(steps_to(&rows, 3), Some((Stack::Undo, 1)));
+ assert_eq!(steps_to(&rows, 4), Some((Stack::Undo, 2)));
+ assert_eq!(steps_to(&rows, 5), None);
+ assert_eq!(who("editor"), "you");
+ assert_eq!(who("cli"), "agent");
+ assert_eq!(ago(1_000, 61_000), "1 min ago");
+ }
+}
diff --git a/crates/app/src/editor/layers.rs b/crates/app/src/editor/layers.rs
new file mode 100644
index 0000000..70df220
--- /dev/null
+++ b/crates/app/src/editor/layers.rs
@@ -0,0 +1,749 @@
+use super::Editor;
+use crate::commands::Cmd;
+use crate::messages::Tone;
+use crate::theme::{self, Hint, icon};
+use anyhow::Result;
+use egui::{Color32, ColorImage, Rect, RichText, Sense, TextureHandle, TextureOptions, UiBuilder, vec2};
+use klad_brush::Raster;
+use klad_core::doc::{Blend, Kind, Layer, Loc, MASK};
+use klad_core::ops::{Op, Place};
+use rayon::prelude::*;
+use serde_json::{Map, json};
+use std::collections::BTreeMap;
+use std::sync::mpsc::{Receiver, channel};
+
+pub use crate::composite::{THUMB, thumbnail};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum Where {
+ Panel,
+ Timeline,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct LayerRow {
+ pub path: Vec<usize>,
+ pub id: String,
+ pub name: String,
+ pub kind: Kind,
+ pub depth: usize,
+ pub visible: bool,
+ pub locked: bool,
+ pub clip: bool,
+ pub lock_alpha: bool,
+ pub has_mask: bool,
+ pub mask: bool,
+ pub folded: bool,
+ pub cel: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Rename {
+ pub id: String,
+ pub text: String,
+ pub place: Where,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) enum Drop {
+ Above(String),
+ Below(String),
+ Into(String),
+}
+
+impl Drop {
+ fn place(&self) -> Place {
+ match self {
+ Drop::Above(id) => Place {
+ above: Some(id.clone()),
+ ..Place::default()
+ },
+ Drop::Below(id) => Place {
+ below: Some(id.clone()),
+ ..Place::default()
+ },
+ Drop::Into(id) => Place {
+ into: Some(id.clone()),
+ ..Place::default()
+ },
+ }
+ }
+}
+
+pub(super) fn drop_at(rows: &[(Rect, LayerRow)], dragged: &LayerRow, y: f32) -> Option<Result<Drop, String>> {
+ let (rect, target) = rows.iter().find(|(r, _)| r.top() <= y && y < r.bottom())?;
+ if dragged.mask {
+ return Some(Err("a mask stays with its layer; drag the layer".into()));
+ }
+ if target.id == dragged.id {
+ return None;
+ }
+ if target.path.starts_with(&dragged.path) {
+ return Some(Err(format!("{} cannot go inside itself", dragged.name)));
+ }
+ if target.mask {
+ return Some(Err("nothing goes beside a mask; drop on the layer it masks".into()));
+ }
+ let k = (y - rect.top()) / rect.height().max(1.0);
+ Some(Ok(match (target.kind == Kind::Group, k) {
+ (true, k) if (0.25..0.75).contains(&k) => Drop::Into(target.id.clone()),
+ (_, k) if k < 0.5 => Drop::Above(target.id.clone()),
+ _ => Drop::Below(target.id.clone()),
+ }))
+}
+
+type Made = Vec<(String, ColorImage)>;
+
+#[derive(Default)]
+pub(super) struct Thumbs {
+ made: BTreeMap<String, (u64, TextureHandle)>,
+ wanted: BTreeMap<String, Raster>,
+ making: Option<(u64, Receiver<Made>)>,
+}
+
+impl Editor {
+ pub(super) fn layer_rows(&self, place: Where) -> Vec<LayerRow> {
+ fn walk(
+ ed: &Editor,
+ place: Where,
+ layers: &[Layer],
+ path: &mut Vec<usize>,
+ depth: usize,
+ out: &mut Vec<LayerRow>,
+ ) {
+ layers.iter().enumerate().rev().for_each(|(i, layer)| {
+ path.push(i);
+ let folded = place == Where::Timeline && ed.timeline.folded.contains(&layer.id);
+ out.push(ed.row_of(layer, path, depth, false, folded));
+ if let Some(mask) = layer.mask.as_deref() {
+ path.push(MASK);
+ let shown =
+ place == Where::Panel || ed.timeline.masks.contains(&layer.id) || ed.scene.active == *path;
+ if shown {
+ out.push(ed.row_of(mask, path, depth + 1, true, false));
+ }
+ path.pop();
+ }
+ if !folded {
+ walk(ed, place, layer.children(), path, depth + 1, out);
+ }
+ path.pop();
+ });
+ }
+ let mut out = Vec::new();
+ walk(self, place, &self.scene.bundle.doc.layers, &mut Vec::new(), 0, &mut out);
+ out
+ }
+
+ fn row_of(&self, layer: &Layer, path: &[usize], depth: usize, mask: bool, folded: bool) -> LayerRow {
+ let cel = layer
+ .content_at(self.scene.frame)
+ .map(|c| c.link.clone().unwrap_or_else(|| c.id.clone()));
+ LayerRow {
+ path: path.to_vec(),
+ id: layer.id.clone(),
+ name: layer.name.clone(),
+ kind: layer.kind(),
+ depth,
+ visible: layer.visible,
+ locked: layer.locked,
+ clip: layer.clip,
+ lock_alpha: layer.lock_alpha,
+ has_mask: layer.mask.is_some(),
+ mask,
+ folded,
+ cel,
+ }
+ }
+
+ fn thumb_key(&self) -> u64 {
+ self.scene.bundle.doc.rev ^ ((self.scene.frame as u64) << 40)
+ }
+
+ pub(super) fn thumb(&mut self, _ctx: &egui::Context, cel: &str) -> Option<TextureHandle> {
+ let key = self.thumb_key();
+ let made = self.thumbs.made.get(cel).map(|(k, t)| (*k == key, t.clone()));
+ if let Some((true, texture)) = made {
+ return Some(texture);
+ }
+ if let Some(raster) = self.scene.raster_of(cel) {
+ self.thumbs.wanted.insert(cel.to_string(), raster.clone());
+ }
+ made.map(|(_, texture)| texture)
+ }
+
+ pub(super) fn keep_thumbs(&mut self, images: Made) {
+ let key = self.thumb_key();
+ images.into_iter().for_each(|(cel, image)| {
+ let texture = self
+ .ctx
+ .load_texture(format!("thumb {cel}"), image, TextureOptions::LINEAR);
+ self.thumbs.made.insert(cel, (key, texture));
+ });
+ }
+
+ pub(super) fn tend_thumbs(&mut self, ctx: &egui::Context) {
+ let finished = self
+ .thumbs
+ .making
+ .as_ref()
+ .and_then(|(key, rx)| rx.try_recv().ok().map(|images| (*key, images)));
+ if let Some((key, images)) = finished {
+ self.thumbs.making = None;
+ images.into_iter().for_each(|(cel, image)| {
+ let texture = ctx.load_texture(format!("thumb {cel}"), image, TextureOptions::LINEAR);
+ self.thumbs.made.insert(cel, (key, texture));
+ });
+ }
+ if self.thumbs.making.is_some() || self.thumbs.wanted.is_empty() {
+ return;
+ }
+ let wanted = std::mem::take(&mut self.thumbs.wanted);
+ let size = self.scene.size();
+ let (tx, rx) = channel();
+ let ctx = ctx.clone();
+ std::thread::spawn(move || {
+ let images: Vec<(String, ColorImage)> = crate::background().install(|| {
+ wanted
+ .into_par_iter()
+ .map(|(cel, raster)| (cel, thumbnail(&raster, size, THUMB)))
+ .collect()
+ });
+ let _ = tx.send(images);
+ ctx.request_repaint();
+ });
+ self.thumbs.making = Some((self.thumb_key(), rx));
+ }
+
+ fn small_toggle(ui: &mut egui::Ui, glyph: &str, on: bool, hint: String) -> bool {
+ let colour = if on { theme::TEXT } else { theme::WEAK };
+ ui.add(
+ egui::Button::new(RichText::new(glyph).size(15.0).color(colour))
+ .frame(false)
+ .min_size(vec2(22.0, theme::TARGET)),
+ )
+ .hint(hint)
+ .clicked()
+ }
+
+ pub(super) fn layer_row(&mut self, ui: &mut egui::Ui, row: &LayerRow, place: Where, rect: Rect) -> egui::Response {
+ let id = ui.scope_id().with(("layer row", &row.id, place == Where::Panel));
+ let response = ui.interact(rect, id, Sense::click_and_drag());
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &row.name));
+ let response = response.hint(format!(
+ "{}: click to draw on it, cmd click to select strokes on it too (S), double-click its name to rename it, drag it to move it",
+ row.name
+ ));
+ let active = self.scene.active == row.path;
+ let also = self.also.contains(&row.id);
+ let painter = ui.painter_at(rect);
+ if active {
+ painter.rect_filled(rect, 3.0, Color32::from_gray(54));
+ } else if also {
+ painter.rect_filled(rect, 3.0, Color32::from_gray(47));
+ } else if response.hovered() {
+ painter.rect_filled(rect, 3.0, Color32::from_gray(42));
+ }
+ if also {
+ painter.rect_filled(
+ egui::Rect::from_min_size(rect.min, vec2(3.0, rect.height())),
+ 1.0,
+ theme::ACCENT,
+ );
+ }
+ let mut child = ui.new_child(
+ UiBuilder::new()
+ .max_rect(rect.shrink2(vec2(2.0, 0.0)))
+ .layout(egui::Layout::left_to_right(egui::Align::Center)),
+ );
+ child.spacing_mut().item_spacing.x = 2.0;
+ let mut ops: Vec<Op> = Vec::new();
+ if !row.mask {
+ let eye = if row.visible { icon::EYE } else { icon::EYE_OFF };
+ if Self::small_toggle(&mut child, eye, row.visible, format!("show or hide {}", row.name)) {
+ ops.push(set(&row.id, "visible", json!(!row.visible)));
+ }
+ if Self::small_toggle(
+ &mut child,
+ icon::LOCK,
+ row.locked,
+ format!("lock or unlock {}", row.name),
+ ) {
+ ops.push(set(&row.id, "locked", json!(!row.locked)));
+ }
+ } else {
+ child.add_space(46.0);
+ }
+ child.add_space(row.depth as f32 * 12.0);
+ if row.kind == Kind::Group && place == Where::Timeline {
+ let caret = if row.folded { icon::FOLDED } else { icon::OPEN };
+ if Self::small_toggle(&mut child, caret, true, format!("fold or open the group {}", row.name))
+ && !self.timeline.folded.remove(&row.id)
+ {
+ self.timeline.folded.insert(row.id.clone());
+ }
+ }
+ let kind = match (row.mask, row.kind) {
+ (true, _) => icon::MASK,
+ (_, Kind::Group) => icon::LAYERS,
+ (_, Kind::Adjust) => icon::ADJUST,
+ (_, Kind::Vector) => icon::POINTS,
+ _ => icon::BRUSH,
+ };
+ child.label(RichText::new(kind).color(theme::WEAK));
+ let rename = |text: String| Rename {
+ id: row.id.clone(),
+ text,
+ place,
+ };
+ let renaming = self
+ .renaming
+ .as_ref()
+ .is_some_and(|r| r.id == row.id && r.place == place);
+ if renaming {
+ let mut text = self.renaming.as_ref().map(|r| r.text.clone()).unwrap_or_default();
+ let label = child.label("rename");
+ let edit = child
+ .add(egui::TextEdit::singleline(&mut text).desired_width(90.0))
+ .labelled_by(label.id)
+ .hint("the new name; Return keeps it, Esc leaves it");
+ edit.request_focus();
+ let (enter, escape) = child.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
+ match (enter || edit.lost_focus(), escape) {
+ (_, true) => self.renaming = None,
+ (true, _) => {
+ let name = text.trim().to_string();
+ if !name.is_empty() && name != row.name {
+ ops.push(set(&row.id, "name", json!(name)));
+ }
+ self.renaming = None;
+ }
+ _ => self.renaming = Some(rename(text)),
+ }
+ } else {
+ let name = child.add(
+ egui::Label::new(RichText::new(&row.name).color(if active { Color32::WHITE } else { theme::TEXT }))
+ .truncate()
+ .sense(Sense::click()),
+ );
+ if name.double_clicked() {
+ self.renaming = Some(rename(row.name.clone()));
+ }
+ if name.clicked() {
+ self.row_click(ui, row);
+ }
+ }
+ child.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ if place == Where::Panel && row.path.len() == 1 && !row.mask {
+ let depth = self.scene.bundle.doc.layer(&row.id).and_then(|l| l.depth).unwrap_or(0.0);
+ if let Some(v) = self.number(
+ ui,
+ &format!("{}.row.depth", row.id),
+ "",
+ depth,
+ 0.0..=100.0,
+ 0.02,
+ &format!("{}'s depth: 0 is near; deeper planes take more fog and move less when you hold D", row.name),
+ ) {
+ ops.push(set(&row.id, "depth", if v <= 0.0 { json!(null) } else { json!(v) }));
+ }
+ }
+ if place == Where::Panel
+ && let Some(cel) = row.cel.clone()
+ && let Some(texture) = self.thumb(ui.ctx(), &cel)
+ {
+ ui.add(egui::Image::new(&texture).fit_to_exact_size(vec2(THUMB.0 as f32, THUMB.1 as f32)));
+ }
+ if place == Where::Timeline && matches!(row.kind, Kind::Paint | Kind::Vector) && !row.mask {
+ let marked = self.scene.onion_marked.contains(&row.id);
+ if Self::small_toggle(
+ ui,
+ icon::ONION,
+ marked,
+ format!("show the onion of {} too, not only the active layer's", row.name),
+ ) {
+ if !self.scene.onion_marked.remove(&row.id) {
+ self.scene.onion_marked.insert(row.id.clone());
+ }
+ self.check(|e| e.onion_changed());
+ }
+ }
+ if row.has_mask {
+ let r = ui
+ .add(
+ egui::Button::new(RichText::new(icon::MASK).size(14.0))
+ .selected(self.scene.active.last() == Some(&MASK) && self.scene.active.starts_with(&row.path))
+ .min_size(vec2(22.0, theme::TARGET)),
+ )
+ .hint("the mask: click to paint on it, alt click turns it on or off, right-click shows its row in the timeline");
+ if r.clicked() {
+ match ui.input(|i| i.modifiers.alt) {
+ true => {
+ let mask = self.scene.bundle.doc.layer_at(&row.path).mask.as_deref().map(|m| (m.id.clone(), m.visible));
+ if let Some((mask, on)) = mask {
+ ops.push(set(&mask, "visible", json!(!on)));
+ }
+ }
+ false => {
+ let mut path = row.path.clone();
+ path.push(MASK);
+ self.queued_activate = Some(path);
+ }
+ }
+ }
+ if r.secondary_clicked() && !self.timeline.masks.remove(&row.id) {
+ self.timeline.masks.insert(row.id.clone());
+ }
+ }
+ [(row.clip, icon::CLIP, "clipped to the layer below"), (row.lock_alpha, icon::LOCK, "alpha locked")]
+ .iter()
+ .filter(|(on, _, _)| *on)
+ .for_each(|(_, glyph, what)| {
+ ui.label(RichText::new(*glyph).size(12.0).color(theme::ACCENT)).on_hover_text(*what);
+ });
+ });
+ if response.clicked() && !renaming {
+ self.row_click(ui, row);
+ }
+ if response.double_clicked() && !row.mask {
+ self.renaming = Some(rename(row.name.clone()));
+ }
+ if !ops.is_empty() {
+ self.check(|e| e.apply(ops));
+ }
+ response
+ }
+
+ fn row_click(&mut self, ui: &egui::Ui, row: &LayerRow) {
+ let adding = ui.input(|i| i.modifiers.command || i.modifiers.shift);
+ if !adding || row.mask {
+ self.also.clear();
+ self.queued_activate = Some(row.path.clone());
+ return;
+ }
+ if self.scene.active == row.path {
+ return;
+ }
+ if row.kind != Kind::Paint {
+ self.say(
+ Tone::Refused,
+ format!(
+ "{} is a {} layer: strokes to select are on paint layers",
+ row.name,
+ row.kind.name()
+ ),
+ );
+ return;
+ }
+ match self.also.iter().position(|id| *id == row.id) {
+ Some(i) => {
+ self.also.remove(i);
+ }
+ None => self.also.push(row.id.clone()),
+ }
+ self.say(
+ Tone::Info,
+ match self.also.len() {
+ 0 => "strokes select on the active layer only".to_string(),
+ n => format!("S selects strokes on the active layer and {n} more; drag them together"),
+ },
+ );
+ }
+
+ pub(super) fn layer_drags(
+ &mut self,
+ ui: &egui::Ui,
+ place: Where,
+ placed: &[(Rect, LayerRow)],
+ responses: &[egui::Response],
+ ) {
+ if let Some(i) = responses.iter().position(|r| r.drag_started()) {
+ self.layer_drag = Some((placed[i].1.clone(), place));
+ }
+ let Some(dragged) = self
+ .layer_drag
+ .as_ref()
+ .filter(|(_, from)| *from == place)
+ .map(|(row, _)| row.clone())
+ else {
+ return;
+ };
+ let pointer = ui.input(|i| i.pointer.interact_pos().or(i.pointer.hover_pos()));
+ let target = pointer.and_then(|p| drop_at(placed, &dragged, p.y));
+ if let (Some(Ok(drop)), Some(p)) = (&target, pointer) {
+ let painter = ui.painter();
+ let row = placed
+ .iter()
+ .find(|(r, _)| r.top() <= p.y && p.y < r.bottom())
+ .map(|(r, _)| *r);
+ if let Some(r) = row {
+ match drop {
+ Drop::Above(_) => {
+ painter.line_segment([r.left_top(), r.right_top()], egui::Stroke::new(2.5, theme::ACCENT));
+ }
+ Drop::Below(_) => {
+ painter.line_segment(
+ [r.left_bottom(), r.right_bottom()],
+ egui::Stroke::new(2.5, theme::ACCENT),
+ );
+ }
+ Drop::Into(_) => {
+ painter.rect_stroke(r, 3.0, egui::Stroke::new(2.0, theme::ACCENT), egui::StrokeKind::Inside);
+ }
+ }
+ }
+ }
+ if ui.input(|i| i.pointer.any_released()) {
+ self.layer_drag = None;
+ match target {
+ Some(Ok(drop)) => {
+ let op = Op::Move {
+ id: dragged.id.clone(),
+ place: drop.place(),
+ };
+ self.check(|e| e.apply(vec![op]));
+ }
+ Some(Err(why)) => self.say(Tone::Refused, why),
+ None => {}
+ }
+ }
+ }
+
+ pub(super) fn layer_header(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let Some(layer) = self
+ .scene
+ .active_layer()
+ .cloned()
+ .filter(|_| !self.scene.active_is_mask())
+ else {
+ return Ok(());
+ };
+ let id = layer.id.clone();
+ let mut props = Vec::new();
+ let mut blend = layer.blend;
+ egui::ComboBox::from_id_salt(format!("{id}.blend.panel"))
+ .width(84.0)
+ .selected_text(layer.blend.name())
+ .show_ui(ui, |ui| {
+ Blend::ALL.iter().for_each(|b| {
+ ui.selectable_value(&mut blend, *b, b.name());
+ });
+ })
+ .response
+ .hint("how the active layer mixes with what is below it");
+ if blend != layer.blend {
+ props.push(("blend".to_string(), json!(blend)));
+ }
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.o"),
+ "opacity ",
+ layer.opacity,
+ 0.0..=1.0,
+ 0.01,
+ "the active layer's opacity",
+ ) {
+ props.push(("opacity".to_string(), json!(v)));
+ }
+ self.set(&id, props)
+ }
+
+ pub(super) fn layers_pane(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ ui.horizontal_wrapped(|ui| {
+ [
+ (Cmd::NewPaintLayer, Some("paint")),
+ (Cmd::NewVectorLayer, Some("vector")),
+ (Cmd::NewGroupLayer, Some("group")),
+ (Cmd::NewAdjustLayer, Some("adjust")),
+ (Cmd::DuplicateLayer, None),
+ (Cmd::GroupLayer, None),
+ (Cmd::DeleteLayer, None),
+ ]
+ .into_iter()
+ .for_each(|(cmd, label)| {
+ self.command_button(ui, cmd, label);
+ });
+ });
+ let rows = self.layer_rows(Where::Panel);
+ let width = ui.available_width();
+ let mut placed = Vec::new();
+ let mut responses = Vec::new();
+ ui.spacing_mut().item_spacing.y = 0.0;
+ rows.into_iter().for_each(|row| {
+ let (rect, _) = ui.allocate_exact_size(vec2(width, 32.0), Sense::hover());
+ responses.push(self.layer_row(ui, &row, Where::Panel, rect));
+ placed.push((rect, row));
+ });
+ self.layer_drags(ui, Where::Panel, &placed, &responses);
+ Ok(())
+ }
+
+ pub(super) fn duplicate_layer(&mut self) -> Result<()> {
+ let Some(id) = self.scene.active_id().filter(|_| !self.scene.active_is_mask()) else {
+ return Ok(());
+ };
+ let Some(applied) = self.timeline_apply(vec![Op::Duplicate { layer: id }])? else {
+ return Ok(());
+ };
+ if let Some(Loc::Layer(path)) = applied.added.first().and_then(|id| self.scene.bundle.doc.locate(id)) {
+ self.activate(path)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn delete_layer(&mut self) -> Result<()> {
+ let Some(layer) = self.scene.active_layer().cloned() else {
+ return Ok(());
+ };
+ let parent = self.scene.active[..self.scene.active.len() - 1].to_vec();
+ self.apply(vec![Op::Remove {
+ ids: vec![layer.id.clone()],
+ }])?;
+ let fallback = self
+ .layer_rows(Where::Panel)
+ .into_iter()
+ .find(|r| !r.mask)
+ .map(|r| r.path);
+ if let Some(path) = (!parent.is_empty() && self.scene.bundle.doc.locate_path(&parent).is_some())
+ .then_some(parent)
+ .or(fallback)
+ {
+ self.activate(path)?;
+ }
+ self.say(Tone::Done, format!("deleted {} (cmd Z brings it back)", layer.name));
+ Ok(())
+ }
+
+ pub(super) fn new_group(&mut self, wrap: bool) -> Result<()> {
+ let active = self.scene.active_layer().cloned();
+ let mut taken = self.scene.bundle.doc.ids();
+ let group = (0..)
+ .map(|n| format!("group{n}"))
+ .find(|id| !taken.contains(id))
+ .unwrap_or_default();
+ taken.insert(group.clone());
+ let place = match &active {
+ Some(l) if !self.scene.active_is_mask() => Place {
+ above: Some(l.id.clone()),
+ ..Place::default()
+ },
+ _ => Place::default(),
+ };
+ let mut ops = vec![Op::AddLayer {
+ layer: json!({"kind": "group", "id": group, "name": if wrap { active.as_ref().map_or("group".to_string(), |l| format!("{} group", l.name)) } else { "group".to_string() }}),
+ place,
+ }];
+ if let Some(l) = active.filter(|_| wrap && !self.scene.active_is_mask()) {
+ ops.push(Op::Move {
+ id: l.id.clone(),
+ place: Place {
+ into: Some(group.clone()),
+ ..Place::default()
+ },
+ });
+ }
+ self.apply(ops)
+ }
+}
+
+fn set(id: &str, key: &str, value: serde_json::Value) -> Op {
+ Op::Set {
+ id: id.to_string(),
+ props: Map::from_iter([(key.to_string(), value)]),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_brush::TILE;
+
+ fn row_rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
+ Rect::from_min_size(egui::pos2(x, y), vec2(w, h))
+ }
+
+ fn row(id: &str, path: Vec<usize>, kind: Kind, mask: bool) -> LayerRow {
+ LayerRow {
+ path,
+ id: id.into(),
+ name: id.into(),
+ kind,
+ depth: 0,
+ visible: true,
+ locked: false,
+ clip: false,
+ lock_alpha: false,
+ has_mask: false,
+ mask,
+ folded: false,
+ cel: None,
+ }
+ }
+
+ fn rows() -> Vec<(Rect, LayerRow)> {
+ [
+ row("top", vec![3], Kind::Paint, false),
+ row("fx", vec![2], Kind::Group, false),
+ row("inner", vec![2, 0], Kind::Paint, false),
+ row("m", vec![1, MASK], Kind::Paint, true),
+ row("base", vec![0], Kind::Paint, false),
+ ]
+ .into_iter()
+ .enumerate()
+ .map(|(i, r)| (row_rect(0.0, i as f32 * 30.0, 200.0, 30.0), r))
+ .collect()
+ }
+
+ #[test]
+ fn a_dragged_row_lands_above_below_or_inside_a_group_or_says_why_not() {
+ let rows = rows();
+ let base = rows[4].1.clone();
+ assert_eq!(drop_at(&rows, &base, 3.0), Some(Ok(Drop::Above("top".into()))));
+ assert_eq!(drop_at(&rows, &base, 27.0), Some(Ok(Drop::Below("top".into()))));
+ assert_eq!(drop_at(&rows, &base, 45.0), Some(Ok(Drop::Into("fx".into()))));
+ assert_eq!(drop_at(&rows, &base, 31.0), Some(Ok(Drop::Above("fx".into()))));
+ assert_eq!(drop_at(&rows, &base, 66.0), Some(Ok(Drop::Above("inner".into()))));
+ assert!(matches!(drop_at(&rows, &base, 95.0), Some(Err(_))));
+ assert_eq!(drop_at(&rows, &base, 125.0), None);
+ assert_eq!(drop_at(&rows, &base, 500.0), None);
+ let fx = rows[1].1.clone();
+ assert!(matches!(drop_at(&rows, &fx, 70.0), Some(Err(why)) if why.contains("inside itself")));
+ let mask = rows[3].1.clone();
+ assert!(matches!(drop_at(&rows, &mask, 10.0), Some(Err(why)) if why.contains("mask")));
+ }
+
+ #[test]
+ fn a_thumbnail_shows_where_the_layer_has_paint() {
+ let mut raster = Raster::new(200, 100);
+ (0..100).for_each(|y| {
+ (0..100).for_each(|x| {
+ let index = raster.index(x / TILE, y / TILE);
+ let tile = raster.ensure(index);
+ let i = ((y % TILE) * TILE + x % TILE) * 4;
+ [1.0, 0.0, 0.0, 1.0]
+ .iter()
+ .enumerate()
+ .for_each(|(k, v)| tile[i + k] = half::f16::from_f32(*v));
+ });
+ });
+ let image = thumbnail(&raster, (200, 100), (40, 20));
+ assert_eq!(image.size, [40, 20]);
+ let at = |x: usize, y: usize| image.pixels[y * 40 + x];
+ assert_eq!(at(5, 10), Color32::from_rgb(255, 0, 0));
+ assert_ne!(at(35, 10), Color32::from_rgb(255, 0, 0));
+ assert_eq!(at(35, 10).r(), at(35, 10).g());
+ let mut line = Raster::new(400, 200);
+ (0..200).for_each(|y| {
+ let index = line.index(200 / TILE, y / TILE);
+ let tile = line.ensure(index);
+ let i = ((y % TILE) * TILE + 200 % TILE) * 4;
+ [0.0, 0.0, 0.0, 1.0]
+ .iter()
+ .enumerate()
+ .for_each(|(k, v)| tile[i + k] = half::f16::from_f32(*v));
+ });
+ let thin = thumbnail(&line, (400, 200), (40, 20));
+ assert!(thin.pixels[10 * 40 + 20].r() < 160, "{:?}", thin.pixels[10 * 40 + 20]);
+ }
+}
diff --git a/crates/app/src/editor/look.rs b/crates/app/src/editor/look.rs
new file mode 100644
index 0000000..91469d7
--- /dev/null
+++ b/crates/app/src/editor/look.rs
@@ -0,0 +1,865 @@
+use super::Editor;
+use crate::color;
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use anyhow::Result;
+use egui::{Color32, RichText, Sense, Stroke, pos2, vec2};
+use klad_core::doc::{Blend, Layer, LayerContent, Paint, Stop};
+use klad_core::look::{self, ADJUSTMENTS, Adjustment, Curves, EFFECTS, Effect, Rays};
+use serde_json::Value;
+
+const NEAR: f32 = 14.0;
+const CHANNELS: [(&str, Color32); 4] = [
+ ("rgb", Color32::from_gray(220)),
+ ("red", Color32::from_rgb(235, 90, 90)),
+ ("green", Color32::from_rgb(110, 210, 120)),
+ ("blue", Color32::from_rgb(100, 150, 255)),
+];
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
+pub(super) enum Touch {
+ #[default]
+ Still,
+ Preview,
+ Commit,
+}
+
+impl Touch {
+ fn of(r: &egui::Response) -> Self {
+ match (r.drag_stopped(), r.changed(), r.dragged()) {
+ (true, _, _) => Touch::Commit,
+ (_, true, true) => Touch::Preview,
+ (_, true, false) => Touch::Commit,
+ _ => Touch::Still,
+ }
+ }
+
+ fn add(&mut self, other: Touch) {
+ *self = (*self).max(other);
+ }
+}
+
+pub(super) struct Draft {
+ pub id: String,
+ pub original: Layer,
+}
+
+#[derive(Default)]
+pub(super) struct LookState {
+ pub draft: Option<Draft>,
+ pub channel: usize,
+ pub dragging: Option<usize>,
+}
+
+fn slide(
+ ui: &mut egui::Ui,
+ touch: &mut Touch,
+ value: &mut f32,
+ range: std::ops::RangeInclusive<f32>,
+ text: &str,
+ hint: &str,
+) {
+ let r = ui.add(egui::Slider::new(value, range).text(text)).hint(hint);
+ touch.add(Touch::of(&r));
+}
+
+fn check(ui: &mut egui::Ui, touch: &mut Touch, value: &mut bool, text: &str, hint: &str) {
+ if ui.checkbox(value, text).hint(hint).changed() {
+ touch.add(Touch::Commit);
+ }
+}
+
+fn swatch(ui: &mut egui::Ui, touch: &mut Touch, hex: &mut String, current: [f32; 4], what: &str) {
+ let rgba = color::rgba_of(hex).unwrap_or([0.0, 0.0, 0.0, 1.0]);
+ if color::swatch(ui, rgba, false, theme::TARGET)
+ .hint(format!("{what}, {hex}; click to use the current colour"))
+ .clicked()
+ {
+ *hex = color::hex(current);
+ touch.add(Touch::Commit);
+ }
+}
+
+fn blend_pick(ui: &mut egui::Ui, touch: &mut Touch, value: &mut Blend, salt: &str, hint: &str) {
+ let before = *value;
+ egui::ComboBox::from_id_salt(salt)
+ .width(110.0)
+ .selected_text(value.name())
+ .show_ui(ui, |ui| {
+ Blend::ALL.iter().for_each(|b| {
+ ui.selectable_value(value, *b, b.name());
+ });
+ })
+ .response
+ .hint(hint);
+ if *value != before {
+ touch.add(Touch::Commit);
+ }
+}
+
+fn seed(ui: &mut egui::Ui, touch: &mut Touch, value: &mut u32) {
+ let r = ui
+ .add(egui::DragValue::new(value).range(0..=99_999).prefix("seed "))
+ .hint("another seed gives another pattern of the same kind");
+ touch.add(Touch::of(&r));
+}
+
+fn effect_controls(
+ ui: &mut egui::Ui,
+ effect: &mut Effect,
+ touch: &mut Touch,
+ current: [f32; 4],
+ layers: &[(String, String)],
+ height: f32,
+) {
+ match effect {
+ Effect::Haze(h) => {
+ slide(
+ ui,
+ touch,
+ &mut h.amount,
+ 0.0..=1.0,
+ "amount",
+ "how far the colours go towards the haze colour",
+ );
+ slide(
+ ui,
+ touch,
+ &mut h.desaturate,
+ 0.0..=1.0,
+ "greyer",
+ "how much colour the haze takes out",
+ );
+ ui.horizontal(|ui| {
+ swatch(ui, touch, &mut h.color, current, "the haze colour");
+ let mut graded = h.top.is_some();
+ check(
+ ui,
+ touch,
+ &mut graded,
+ "by height",
+ "a second colour at the top, blending down to the first",
+ );
+ if graded != h.top.is_some() {
+ h.top = graded.then(|| color::hex(current));
+ h.span = height;
+ }
+ if let Some(top) = h.top.as_mut() {
+ swatch(ui, touch, top, current, "the haze colour at the top");
+ }
+ });
+ }
+ Effect::Blur(b) => slide(ui, touch, &mut b.radius, 0.0..=64.0, "radius", "how soft, in px"),
+ Effect::Glow(g) => {
+ slide(
+ ui,
+ touch,
+ &mut g.radius,
+ 0.0..=128.0,
+ "radius",
+ "how far the glow spreads, in px",
+ );
+ slide(
+ ui,
+ touch,
+ &mut g.strength,
+ 0.0..=3.0,
+ "strength",
+ "how bright the glow is",
+ );
+ slide(
+ ui,
+ touch,
+ &mut g.threshold,
+ 0.0..=1.0,
+ "from brightness",
+ "0 glows from every pixel; higher glows only from the bright ones (bloom)",
+ );
+ ui.horizontal(|ui| {
+ let mut tinted = g.color.is_some();
+ check(ui, touch, &mut tinted, "tint", "glow in one colour instead of the layer's own");
+ if tinted != g.color.is_some() {
+ g.color = tinted.then(|| color::hex(current));
+ }
+ if let Some(hex) = g.color.as_mut() {
+ swatch(ui, touch, hex, current, "the glow's colour");
+ }
+ blend_pick(
+ ui,
+ touch,
+ &mut g.blend,
+ "glow.blend",
+ "how the glow mixes with what is under the layer: screen and add light it up, normal lays it like paint",
+ );
+ });
+ }
+ Effect::Outline(o) => {
+ slide(ui, touch, &mut o.width, 0.0..=32.0, "width", "the line's width, in px");
+ ui.horizontal(|ui| {
+ swatch(ui, touch, &mut o.color, current, "the outline's colour");
+ check(
+ ui,
+ touch,
+ &mut o.inside,
+ "inside",
+ "draw the line inside the edge instead of around it",
+ );
+ });
+ }
+ Effect::Shadow(s) => {
+ slide(
+ ui,
+ touch,
+ &mut s.x,
+ -64.0..=64.0,
+ "across",
+ "how far right the shadow falls, in px",
+ );
+ slide(
+ ui,
+ touch,
+ &mut s.y,
+ -64.0..=64.0,
+ "down",
+ "how far down the shadow falls, in px",
+ );
+ slide(
+ ui,
+ touch,
+ &mut s.radius,
+ 0.0..=64.0,
+ "softness",
+ "how soft the shadow is, in px",
+ );
+ swatch(
+ ui,
+ touch,
+ &mut s.color,
+ current,
+ "the shadow's colour (its alpha is its strength)",
+ );
+ }
+ Effect::Noise(n) => {
+ slide(ui, touch, &mut n.amount, 0.0..=1.0, "amount", "how strong the grain is");
+ slide(
+ ui,
+ touch,
+ &mut n.size,
+ 1.0..=16.0,
+ "grain size",
+ "the size of a grain, in px",
+ );
+ ui.horizontal(|ui| {
+ check(
+ ui,
+ touch,
+ &mut n.mono,
+ "grey",
+ "the same grain on every channel; off gives coloured grain",
+ );
+ seed(ui, touch, &mut n.seed);
+ });
+ }
+ Effect::Displace(d) => {
+ slide(
+ ui,
+ touch,
+ &mut d.amount,
+ 0.0..=64.0,
+ "amount",
+ "how far pixels are pushed, in px",
+ );
+ slide(
+ ui,
+ touch,
+ &mut d.size,
+ 4.0..=256.0,
+ "wave size",
+ "the size of the waves that push, in px",
+ );
+ ui.horizontal(|ui| {
+ let shown =
+ d.by.as_ref()
+ .and_then(|id| layers.iter().find(|(l, _)| l == id))
+ .map_or("waves".to_string(), |(_, name)| name.clone());
+ let before = d.by.clone();
+ egui::ComboBox::from_id_salt("displace.by")
+ .width(120.0)
+ .selected_text(shown)
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut d.by, None, "waves");
+ layers.iter().for_each(|(id, name)| {
+ ui.selectable_value(&mut d.by, Some(id.clone()), name);
+ });
+ })
+ .response
+ .hint(
+ "push by smooth waves, or by a layer: its red pushes across, its green down (grey stays put)",
+ );
+ if d.by != before {
+ touch.add(Touch::Commit);
+ }
+ seed(ui, touch, &mut d.seed);
+ });
+ }
+ }
+}
+
+fn curve_box(ui: &mut egui::Ui, points: &mut Vec<[f32; 2]>, state: &mut LookState, touch: &mut Touch, colour: Color32) {
+ if points.is_empty() {
+ *points = vec![[0.0, 0.0], [1.0, 1.0]];
+ }
+ let side = ui.available_width().clamp(120.0, 240.0);
+ let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag());
+ let response = response.hint(
+ "the curve: dark on the left, light on the right; drag a point to bend it, press empty space to add one, double-click a point to remove it",
+ );
+ let to_screen = |p: [f32; 2]| pos2(rect.left() + p[0] * side, rect.bottom() - p[1] * side);
+ let from_screen = |p: egui::Pos2| {
+ [
+ ((p.x - rect.left()) / side).clamp(0.0, 1.0),
+ ((rect.bottom() - p.y) / side).clamp(0.0, 1.0),
+ ]
+ };
+ let nearest = |at: egui::Pos2, points: &[[f32; 2]]| {
+ points
+ .iter()
+ .enumerate()
+ .map(|(i, p)| (i, to_screen(*p).distance(at)))
+ .filter(|(_, d)| *d <= NEAR)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(i, _)| i)
+ };
+ let insert = |points: &mut Vec<[f32; 2]>, p: [f32; 2]| {
+ let at = points.iter().position(|q| q[0] > p[0]).unwrap_or(points.len());
+ points.insert(at, p);
+ at
+ };
+ let pointer = response.interact_pointer_pos();
+ if response.double_clicked()
+ && let Some(i) = pointer.and_then(|at| nearest(at, points))
+ && i > 0
+ && i + 1 < points.len()
+ {
+ points.remove(i);
+ touch.add(Touch::Commit);
+ } else if response.drag_started()
+ && let Some(at) = pointer
+ {
+ state.dragging = Some(nearest(at, points).unwrap_or_else(|| insert(points, from_screen(at))));
+ touch.add(Touch::Preview);
+ } else if response.clicked()
+ && let Some(at) = pointer
+ && nearest(at, points).is_none()
+ {
+ insert(points, from_screen(at));
+ touch.add(Touch::Commit);
+ }
+ if response.dragged()
+ && let (Some(i), Some(at)) = (state.dragging, pointer)
+ && i < points.len()
+ {
+ let [x, y] = from_screen(at);
+ let low = if i == 0 { 0.0 } else { points[i - 1][0] + 0.01 };
+ let high = if i + 1 == points.len() {
+ 1.0
+ } else {
+ points[i + 1][0] - 0.01
+ };
+ points[i] = [x.clamp(low, high.max(low)), y];
+ touch.add(Touch::Preview);
+ }
+ if response.drag_stopped() {
+ state.dragging = None;
+ touch.add(Touch::Commit);
+ }
+ let painter = ui.painter_at(rect);
+ painter.rect_filled(rect, 2.0, Color32::from_gray(24));
+ (1..4).for_each(|k| {
+ let t = k as f32 / 4.0;
+ let faint = Stroke::new(1.0, Color32::from_gray(48));
+ painter.line_segment([to_screen([t, 0.0]), to_screen([t, 1.0])], faint);
+ painter.line_segment([to_screen([0.0, t]), to_screen([1.0, t])], faint);
+ });
+ painter.line_segment(
+ [to_screen([0.0, 0.0]), to_screen([1.0, 1.0])],
+ Stroke::new(1.0, Color32::from_gray(70)),
+ );
+ if let Ok(prepared) = Adjustment::Curves(Curves {
+ points: points.clone(),
+ ..Curves::default()
+ })
+ .prepare()
+ {
+ let line: Vec<egui::Pos2> = (0..=64)
+ .map(|i| i as f32 / 64.0)
+ .map(|v| to_screen([v, prepared.apply([v; 3])[0].clamp(0.0, 1.0)]))
+ .collect();
+ painter.add(egui::Shape::line(line, Stroke::new(2.0, colour)));
+ }
+ points.iter().enumerate().for_each(|(i, p)| {
+ let held = state.dragging == Some(i);
+ painter.circle(
+ to_screen(*p),
+ if held { 7.0 } else { 5.5 },
+ if held { colour } else { Color32::from_gray(30) },
+ Stroke::new(2.0, colour),
+ );
+ });
+}
+
+fn stops_controls(ui: &mut egui::Ui, stops: &mut Vec<Stop>, touch: &mut Touch, current: [f32; 4]) {
+ let mut gone = None;
+ let count = stops.len();
+ stops.iter_mut().enumerate().for_each(|(i, stop)| {
+ ui.push_id(("stop", i), |ui| {
+ ui.horizontal(|ui| {
+ swatch(ui, touch, &mut stop.1, current, "this stop's colour");
+ let r = ui
+ .add(egui::Slider::new(&mut stop.0, 0.0..=1.0).text("at"))
+ .hint("where on the dark to light scale this colour sits");
+ touch.add(Touch::of(&r));
+ if count > 1 && ui.button(theme::icon::TRASH).hint("remove this stop").clicked() {
+ gone = Some(i);
+ }
+ });
+ });
+ });
+ if let Some(i) = gone {
+ stops.remove(i);
+ touch.add(Touch::Commit);
+ }
+ if ui
+ .button(format!("{} add a stop", theme::icon::PLUS))
+ .hint("a stop in the current colour halfway along")
+ .clicked()
+ {
+ stops.push(Stop(0.5, color::hex(current)));
+ touch.add(Touch::Commit);
+ }
+}
+
+fn adjust_controls(
+ ui: &mut egui::Ui,
+ adjust: &mut Adjustment,
+ state: &mut LookState,
+ touch: &mut Touch,
+ current: [f32; 4],
+) {
+ match adjust {
+ Adjustment::Hsl(h) => {
+ slide(
+ ui,
+ touch,
+ &mut h.hue,
+ -180.0..=180.0,
+ "hue",
+ "turns every colour around the colour wheel, in degrees",
+ );
+ slide(
+ ui,
+ touch,
+ &mut h.saturation,
+ -1.0..=1.0,
+ "saturation",
+ "less colour to the left, more to the right",
+ );
+ slide(
+ ui,
+ touch,
+ &mut h.lightness,
+ -1.0..=1.0,
+ "lightness",
+ "towards black to the left, towards white to the right",
+ );
+ }
+ Adjustment::Levels(l) => {
+ slide(
+ ui,
+ touch,
+ &mut l.black,
+ 0.0..=1.0,
+ "black point",
+ "this and darker becomes the darkest output",
+ );
+ slide(
+ ui,
+ touch,
+ &mut l.white,
+ 0.0..=1.0,
+ "white point",
+ "this and lighter becomes the lightest output",
+ );
+ slide(
+ ui,
+ touch,
+ &mut l.gamma,
+ 0.1..=4.0,
+ "midtones",
+ "above 1 lifts the middle tones, below 1 sinks them",
+ );
+ slide(
+ ui,
+ touch,
+ &mut l.low,
+ 0.0..=1.0,
+ "darkest output",
+ "how dark the darkest pixels end up",
+ );
+ slide(
+ ui,
+ touch,
+ &mut l.high,
+ 0.0..=1.0,
+ "lightest output",
+ "how light the lightest pixels end up",
+ );
+ }
+ Adjustment::Curves(c) => {
+ ui.horizontal(|ui| {
+ CHANNELS.iter().enumerate().for_each(|(i, (name, colour))| {
+ if ui
+ .selectable_label(state.channel == i, RichText::new(*name).color(*colour))
+ .hint(match i {
+ 0 => "edit the curve for all channels at once",
+ _ => "edit one channel's curve; it applies before the rgb curve",
+ })
+ .clicked()
+ {
+ state.channel = i;
+ }
+ });
+ if ui
+ .button("reset")
+ .hint("set this channel's curve back to a straight line")
+ .clicked()
+ {
+ match state.channel {
+ 1 => c.red.clear(),
+ 2 => c.green.clear(),
+ 3 => c.blue.clear(),
+ _ => c.points = vec![[0.0, 0.0], [1.0, 1.0]],
+ }
+ touch.add(Touch::Commit);
+ }
+ });
+ let colour = CHANNELS[state.channel.min(3)].1;
+ let points = match state.channel {
+ 1 => &mut c.red,
+ 2 => &mut c.green,
+ 3 => &mut c.blue,
+ _ => &mut c.points,
+ };
+ curve_box(ui, points, state, touch, colour);
+ }
+ Adjustment::Balance(b) => {
+ [
+ ("shadows", &mut b.shadows),
+ ("midtones", &mut b.midtones),
+ ("highlights", &mut b.highlights),
+ ]
+ .into_iter()
+ .for_each(|(name, values)| {
+ ui.label(name);
+ ui.push_id(name, |ui| {
+ slide(
+ ui,
+ touch,
+ &mut values[0],
+ -1.0..=1.0,
+ "cyan to red",
+ "shift this range towards red or cyan",
+ );
+ slide(
+ ui,
+ touch,
+ &mut values[1],
+ -1.0..=1.0,
+ "magenta to green",
+ "shift this range towards green or magenta",
+ );
+ slide(
+ ui,
+ touch,
+ &mut values[2],
+ -1.0..=1.0,
+ "yellow to blue",
+ "shift this range towards blue or yellow",
+ );
+ });
+ });
+ check(
+ ui,
+ touch,
+ &mut b.keep_light,
+ "keep the light",
+ "shift the colours without making pixels lighter or darker",
+ );
+ }
+ Adjustment::GradientMap(g) => stops_controls(ui, &mut g.stops, touch, current),
+ Adjustment::Fill(f) => match &mut f.paint {
+ Paint::Solid(hex) => {
+ ui.horizontal(|ui| {
+ swatch(ui, touch, hex, current, "the fill's colour");
+ ui.label("blend and opacity are the layer's, above");
+ });
+ }
+ _ => {
+ ui.label("a gradient fill; change it with klad set");
+ }
+ },
+ }
+}
+
+impl Editor {
+ pub(super) fn rays_section(&mut self, ui: &mut egui::Ui, id: &str, rays: &Rays) -> Option<Value> {
+ let mut r = rays.clone();
+ let fields: [(&str, &mut f32, std::ops::RangeInclusive<f32>, f64, &str); 8] = [
+ ("x ", &mut r.x, -1e5..=1e5, 1.0, "where the light comes from, across"),
+ ("y ", &mut r.y, -1e5..=1e5, 1.0, "where the light comes from, down"),
+ (
+ "angle ",
+ &mut r.angle,
+ -360.0..=360.0,
+ 0.5,
+ "the direction they shine, in degrees: 90 is straight down",
+ ),
+ (
+ "spread ",
+ &mut r.spread,
+ 0.0..=360.0,
+ 0.5,
+ "how wide the fan of rays is, in degrees",
+ ),
+ ("length ", &mut r.length, 1.0..=1e5, 2.0, "how far they reach, in px"),
+ (
+ "gap ",
+ &mut r.start,
+ 0.0..=1e5,
+ 1.0,
+ "how wide the gap they shine through is, in px",
+ ),
+ (
+ "falloff ",
+ &mut r.falloff,
+ 0.05..=8.0,
+ 0.02,
+ "how quickly they fade along their length",
+ ),
+ (
+ "noise ",
+ &mut r.noise,
+ 0.0..=1.0,
+ 0.01,
+ "how much the rays differ in width, length and strength",
+ ),
+ ];
+ let mut changed = false;
+ ui.label(RichText::new(format!("{} rays", theme::icon::SUN)).strong());
+ fields
+ .into_iter()
+ .enumerate()
+ .for_each(|(i, (label, value, range, speed, hint))| {
+ if i % 2 == 0 {
+ ui.end_row();
+ }
+ if let Some(v) = self.number(ui, &format!("{id}.rays.{label}"), label, *value, range, speed, hint) {
+ *value = v;
+ changed = true;
+ }
+ });
+ let mut count = r.count as f32;
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.rays.count"),
+ "count ",
+ count,
+ 1.0..=256.0,
+ 0.1,
+ "how many rays",
+ ) {
+ count = v;
+ r.count = count.round() as u32;
+ changed = true;
+ }
+ let mut seed = r.seed as f32;
+ if let Some(v) = self.number(
+ ui,
+ &format!("{id}.rays.seed"),
+ "seed ",
+ seed,
+ 0.0..=99_999.0,
+ 0.2,
+ "another seed gives other rays of the same kind",
+ ) {
+ seed = v;
+ r.seed = seed.round() as u32;
+ changed = true;
+ }
+ changed.then(|| serde_json::to_value(&r).unwrap_or(Value::Null))
+ }
+
+ pub(super) fn preview_look(&mut self, layer: Layer) -> Result<()> {
+ if self.look.draft.as_ref().is_some_and(|d| d.id != layer.id) {
+ self.end_look_preview()?;
+ }
+ if self.look.draft.is_none() {
+ let Some(original) = self.scene.bundle.doc.find_layer(&layer.id).ok().cloned() else {
+ return Ok(());
+ };
+ self.look.draft = Some(Draft {
+ id: layer.id.clone(),
+ original,
+ });
+ }
+ self.scene.preview_layer(layer)?;
+ self.dirty.extend(self.scene.all_tiles());
+ Ok(())
+ }
+
+ pub(super) fn end_look_preview(&mut self) -> Result<()> {
+ if let Some(draft) = self.look.draft.take() {
+ self.scene.preview_layer(draft.original)?;
+ self.dirty.extend(self.scene.all_tiles());
+ }
+ Ok(())
+ }
+
+ fn settle_look(&mut self, layer: &Layer, touch: Touch, key: &str, value: Value) -> Result<()> {
+ match touch {
+ Touch::Still => Ok(()),
+ Touch::Preview => self.preview_look(layer.clone()),
+ Touch::Commit => {
+ self.end_look_preview()?;
+ self.set(&layer.id, vec![(key.to_string(), value)])
+ }
+ }
+ }
+
+ pub(super) fn effects_section(&mut self, ui: &mut egui::Ui, layer: &Layer) -> Result<()> {
+ if layer.reads_under() {
+ return Ok(());
+ }
+ ui.separator();
+ ui.label(RichText::new(format!("{} effects", theme::icon::SPARKLE)).strong())
+ .hint("effects apply in order, top first, each time the layer composes; they stay editable");
+ let mut list = layer.effects.clone();
+ let mut touch = Touch::Still;
+ let current = self.color;
+ let height = self.scene.bundle.doc.canvas.height as f32;
+ let layers: Vec<(String, String)> = self
+ .scene
+ .bundle
+ .doc
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.id != layer.id)
+ .map(|l| (l.id.clone(), l.name.clone()))
+ .collect();
+ let mut order: Option<(usize, usize)> = None;
+ let mut gone = None;
+ let count = list.len();
+ list.iter_mut().enumerate().for_each(|(i, effect)| {
+ ui.push_id(("effect", i), |ui| {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(effect.name()).color(theme::TEXT));
+ if i > 0 && ui.button(theme::icon::UP).hint("apply this effect earlier").clicked() {
+ order = Some((i, i - 1));
+ }
+ if i + 1 < count && ui.button(theme::icon::DOWN).hint("apply this effect later").clicked() {
+ order = Some((i, i + 1));
+ }
+ if ui.button(theme::icon::TRASH).hint("remove this effect").clicked() {
+ gone = Some(i);
+ }
+ });
+ effect_controls(ui, effect, &mut touch, current, &layers, height);
+ });
+ });
+ if let Some((a, b)) = order {
+ list.swap(a, b);
+ touch.add(Touch::Commit);
+ }
+ if let Some(i) = gone {
+ list.remove(i);
+ touch.add(Touch::Commit);
+ }
+ let mut added = None;
+ egui::ComboBox::from_id_salt(format!("{}.effect.add", layer.id))
+ .width(120.0)
+ .selected_text(format!("{} add an effect", theme::icon::PLUS))
+ .show_ui(ui, |ui| {
+ EFFECTS.iter().for_each(|name| {
+ if ui
+ .selectable_label(false, *name)
+ .hint(format!("add a {name} effect at the end"))
+ .clicked()
+ {
+ added = Effect::named(name);
+ }
+ });
+ })
+ .response
+ .hint("blur, glow, outline, shadow, grain or displacement, applied after the ones above");
+ if let Some(effect) = added {
+ list.push(effect);
+ touch.add(Touch::Commit);
+ }
+ if touch == Touch::Still {
+ return Ok(());
+ }
+ if let Some(e) = list.iter().find_map(|e| e.validate().err()) {
+ self.say(Tone::Refused, format!("{e:#}"));
+ return Ok(());
+ }
+ let value = serde_json::to_value(&list)?;
+ let changed = Layer {
+ effects: list,
+ ..layer.clone()
+ };
+ self.settle_look(&changed, touch, "effects", value)
+ }
+
+ pub(super) fn adjust_section(&mut self, ui: &mut egui::Ui, layer: &Layer) -> Result<()> {
+ let Some(mut adjust) = layer.adjustment().cloned() else {
+ return Ok(());
+ };
+ ui.separator();
+ let mut touch = Touch::Still;
+ let before = adjust.name();
+ let mut kind = before;
+ egui::ComboBox::from_id_salt(format!("{}.adjust.kind", layer.id))
+ .width(150.0)
+ .selected_text(adjust.label())
+ .show_ui(ui, |ui| {
+ ADJUSTMENTS.iter().for_each(|name| {
+ ui.selectable_value(&mut kind, name, look::label_of(name));
+ });
+ })
+ .response
+ .hint("what this adjustment layer does to the layers under it in its group (or the one it is clipped to)");
+ if kind != before
+ && let Some(fresh) = Adjustment::named(kind)
+ {
+ adjust = fresh;
+ touch.add(Touch::Commit);
+ }
+ let current = self.color;
+ let mut state = std::mem::take(&mut self.look);
+ adjust_controls(ui, &mut adjust, &mut state, &mut touch, current);
+ self.look = state;
+ if touch == Touch::Still {
+ return Ok(());
+ }
+ if let Err(e) = adjust.validate() {
+ self.say(Tone::Refused, format!("{e:#}"));
+ return Ok(());
+ }
+ let value = serde_json::to_value(&adjust)?;
+ let changed = Layer {
+ content: LayerContent::Adjust { adjust },
+ ..layer.clone()
+ };
+ self.settle_look(&changed, touch, "adjust", value)
+ }
+}
diff --git a/crates/app/src/editor/make.rs b/crates/app/src/editor/make.rs
new file mode 100644
index 0000000..cbb043e
--- /dev/null
+++ b/crates/app/src/editor/make.rs
@@ -0,0 +1,668 @@
+use super::Editor;
+use crate::color;
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use anyhow::Result;
+use egui::{Color32, Pos2, Rect, Stroke, Vec2, vec2};
+use klad_core::doc::{Item, Kind, Loc, Node, Shape};
+use klad_core::generators::Align;
+use klad_core::ops::{Op, Place};
+use klad_core::stroke::{POS_SCALE, Sample};
+use klad_render::overlay;
+use serde_json::{Value, json};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(super) enum ShapeKind {
+ #[default]
+ Rect,
+ Ellipse,
+}
+
+#[derive(Default)]
+pub(super) struct ShapeTool {
+ pub kind: ShapeKind,
+ pub radius: f32,
+ pub drag: Option<(Vec2, Vec2)>,
+}
+
+pub(super) fn mirrored(s: &Sample, axis: f32) -> Sample {
+ Sample {
+ x: (2.0 * axis * POS_SCALE).round() as i32 - s.x,
+ tilt_x: s.tilt_x.saturating_neg(),
+ ..*s
+ }
+}
+
+fn bounds(key: &str) -> (std::ops::RangeInclusive<f32>, f64) {
+ match key {
+ "count" => (1.0..=10_000.0, 0.1),
+ "columns" => (0.0..=1000.0, 0.1),
+ "seed" => (0.0..=99_999.0, 0.2),
+ "scale" => (0.01..=10.0, 0.01),
+ "size0" | "size1" => (0.01..=100.0, 0.01),
+ "turn" | "turn0" | "turn1" | "angle" => (-360.0..=360.0, 0.5),
+ "w" | "h" => (1.0..=100_000.0, 1.0),
+ "size" => (1.0..=4096.0, 0.5),
+ "leading" => (0.1..=10.0, 0.01),
+ "tracking" => (-200.0..=1000.0, 0.2),
+ _ => (-100_000.0..=100_000.0, 0.5),
+ }
+}
+
+pub(super) fn shape_box((a, b): (Vec2, Vec2), square: bool, centred: bool) -> [f32; 4] {
+ let d = b - a;
+ let d = match square {
+ true => {
+ let m = d.x.abs().max(d.y.abs());
+ vec2(m * d.x.signum(), m * d.y.signum())
+ }
+ false => d,
+ };
+ let (x0, y0, x1, y1) = match centred {
+ true => (a.x - d.x, a.y - d.y, a.x + d.x, a.y + d.y),
+ false => (a.x, a.y, a.x + d.x, a.y + d.y),
+ };
+ [x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()]
+}
+
+fn on_vector(editor: &Editor) -> Option<String> {
+ editor
+ .scene
+ .active_layer()
+ .filter(|l| l.kind() == Kind::Vector && !l.locked && !editor.scene.active_is_mask())
+ .map(|l| l.id.clone())
+}
+
+impl Editor {
+ pub(super) fn shape_now(&self) -> Option<[f32; 4]> {
+ self.shapes
+ .drag
+ .map(|d| shape_box(d, self.modifiers.shift, self.modifiers.alt))
+ }
+
+ pub(super) fn shape_down(&mut self, c: Vec2) {
+ if on_vector(self).is_none() {
+ self.say(
+ Tone::Refused,
+ "U draws rectangles and ellipses on a vector layer: add one with the layers panel's vector button",
+ );
+ return;
+ }
+ self.shapes.drag = Some((c, c));
+ }
+
+ pub(super) fn shape_move(&mut self, c: Vec2) {
+ if let Some((_, b)) = self.shapes.drag.as_mut() {
+ *b = c;
+ }
+ }
+
+ pub(super) fn shape_up(&mut self) -> Result<()> {
+ let made = self.shape_now();
+ self.shapes.drag = None;
+ let (Some([x, y, w, h]), Some(layer)) = (made, on_vector(self)) else {
+ return Ok(());
+ };
+ if w < 2.0 || h < 2.0 {
+ return Ok(());
+ }
+ let (colour, outline) = (color::hex(self.color), color::hex(self.second));
+ let (mut node, what) = match self.shapes.kind {
+ ShapeKind::Rect => (
+ json!({"type": "rect", "x": x, "y": y, "w": w, "h": h, "radius": self.shapes.radius.min(w / 2.0).min(h / 2.0)}),
+ "rectangle",
+ ),
+ ShapeKind::Ellipse => (
+ json!({"type": "ellipse", "cx": x + w / 2.0, "cy": y + h / 2.0, "rx": w / 2.0, "ry": h / 2.0}),
+ "ellipse",
+ ),
+ };
+ node["fill"] = match self.pen_fill {
+ true => json!(colour),
+ false => json!("none"),
+ };
+ if self.pen_stroke || !self.pen_fill {
+ node["stroke"] = json!({ "paint": outline, "width": self.pen_width });
+ }
+ let frame = self.scene.frame;
+ self.apply(vec![Op::AddNode {
+ node,
+ place: Place {
+ into: Some(layer),
+ frame: Some(frame),
+ ..Place::default()
+ },
+ }])?;
+ self.used_colour();
+ self.say(Tone::Done, format!("{what} added: V moves it, A edits its points"));
+ Ok(())
+ }
+
+ pub(super) fn decorate_shape(
+ &self,
+ painter: &egui::Painter,
+ to_screen: &dyn Fn(f32, f32) -> Pos2,
+ accent: Color32,
+ ) {
+ let Some([x, y, w, h]) = self.shape_now() else {
+ return;
+ };
+ let line = Stroke::new(1.5, accent);
+ match self.shapes.kind {
+ ShapeKind::Rect => {
+ let r = Rect::from_two_pos(to_screen(x, y), to_screen(x + w, y + h));
+ painter.rect_stroke(r, 0.0, line, egui::StrokeKind::Middle);
+ }
+ ShapeKind::Ellipse => {
+ let points: Vec<Pos2> = (0..=64)
+ .map(|i| i as f32 / 64.0 * std::f32::consts::TAU)
+ .map(|a| to_screen(x + w / 2.0 + a.cos() * w / 2.0, y + h / 2.0 + a.sin() * h / 2.0))
+ .collect();
+ painter.add(egui::Shape::line(points, line));
+ }
+ }
+ }
+
+ pub(super) fn wrap(&mut self, kind: &str) -> Result<()> {
+ let Some(id) = self.selection.clone() else {
+ self.say(Tone::Refused, "select a shape with V first");
+ return Ok(());
+ };
+ let doc = &self.scene.bundle.doc;
+ let (Some(Item::Node(_, cel, node)), Some(Loc::Node(_, _, path))) = (doc.item(&id), doc.locate(&id)) else {
+ self.say(Tone::Refused, "select a shape with V first");
+ return Ok(());
+ };
+ let Some([x, y, w, h]) = overlay::node_world_box(doc, &id)? else {
+ self.say(Tone::Refused, format!("{id} draws nothing to {kind}"));
+ return Ok(());
+ };
+ let parent = path[..path.len() - 1]
+ .iter()
+ .fold((cel.id.clone(), &cel.nodes[..]), |(_, list), i| {
+ (list[*i].id.clone(), list[*i].children())
+ })
+ .0;
+ let index = path.last().copied();
+ let mut child = serde_json::to_value(node)?;
+ let taken = doc.ids();
+ let made = (1..)
+ .map(|n| format!("{kind}{n}"))
+ .find(|i| !taken.contains(i))
+ .unwrap_or_default();
+ let generator = match kind {
+ "repeat" => json!({"id": made, "type": "repeat", "count": 4, "step": [w + 12.0, 0.0], "children": [child]}),
+ "mirror" => json!({"id": made, "type": "mirror", "x": x + w, "y": y, "angle": 90, "children": [child]}),
+ _ => {
+ let t = &node.transform;
+ child["transform"]["x"] = json!(t.x - (x + w / 2.0));
+ child["transform"]["y"] = json!(t.y - (y + h / 2.0));
+ json!({"id": made, "type": "scatter", "x": x - w * 2.0, "y": y - h, "w": w * 5.0, "h": h * 3.0, "count": 12, "children": [child]})
+ }
+ };
+ let frame = self.scene.frame;
+ self.apply(vec![
+ Op::Remove { ids: vec![id.clone()] },
+ Op::AddNode {
+ node: generator,
+ place: Place {
+ into: Some(parent),
+ index,
+ frame: Some(frame),
+ ..Place::default()
+ },
+ },
+ ])?;
+ self.selection = Some(made);
+ self.say(
+ Tone::Done,
+ format!("{id} is now inside a {kind}: the inspector sets how many copies and where they go"),
+ );
+ Ok(())
+ }
+
+ pub(super) fn unwrap(&mut self) -> Result<()> {
+ let Some(id) = self.selection.clone() else {
+ return Ok(());
+ };
+ let doc = &self.scene.bundle.doc;
+ let (Some(Item::Node(_, cel, node)), Some(Loc::Node(_, _, path))) = (doc.item(&id), doc.locate(&id)) else {
+ return Ok(());
+ };
+ if !node.shape.generates() {
+ return Ok(());
+ }
+ let parent = path[..path.len() - 1]
+ .iter()
+ .fold((cel.id.clone(), &cel.nodes[..]), |(_, list), i| {
+ (list[*i].id.clone(), list[*i].children())
+ })
+ .0;
+ let index = path.last().copied().unwrap_or(0);
+ let shift = match &node.shape {
+ Shape::Scatter(s) => Some((s.x + s.w / 2.0, s.y + s.h / 2.0)),
+ _ => None,
+ };
+ let children: Vec<Value> = node
+ .children()
+ .iter()
+ .map(|child| {
+ let mut value = serde_json::to_value(child)?;
+ if let Some((dx, dy)) = shift {
+ value["transform"]["x"] = json!(child.transform.x + dx);
+ value["transform"]["y"] = json!(child.transform.y + dy);
+ }
+ Ok(value)
+ })
+ .collect::<Result<_>>()?;
+ let first = node.children().first().map(|c| c.id.clone());
+ let kind = node.type_name();
+ let frame = self.scene.frame;
+ let ops = std::iter::once(Op::Remove { ids: vec![id.clone()] })
+ .chain(children.into_iter().enumerate().map(|(k, value)| Op::AddNode {
+ node: value,
+ place: Place {
+ into: Some(parent.clone()),
+ index: Some(index + k),
+ frame: Some(frame),
+ ..Place::default()
+ },
+ }))
+ .collect();
+ self.apply(ops)?;
+ self.selection = first;
+ self.say(Tone::Done, format!("the {kind} is gone; its shapes stay"));
+ Ok(())
+ }
+
+ fn fonts(&self) -> Vec<String> {
+ let dir = self.scene.bundle.root.join(klad_render::assets::FONTS);
+ let mut names: Vec<String> = std::fs::read_dir(dir)
+ .map(|entries| {
+ entries
+ .flatten()
+ .filter_map(|e| e.file_name().into_string().ok())
+ .collect()
+ })
+ .unwrap_or_default();
+ names.sort();
+ names
+ }
+
+ fn field(&mut self, ui: &mut egui::Ui, id: &str, key: &str, label: &str, value: f32, hint: &str) -> Option<f32> {
+ let (range, speed) = bounds(key);
+ self.number(ui, &format!("{id}.{key}.{label}"), label, value, range, speed, hint)
+ }
+
+ pub(super) fn shape_fields(&mut self, ui: &mut egui::Ui, id: &str, node: &Node) -> Vec<(String, Value)> {
+ let mut out: Vec<(String, Value)> = Vec::new();
+ let mut put = |key: &str, value: Value| out.push((key.to_string(), value));
+ match &node.shape {
+ Shape::Scatter(s) => {
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("scatter").strong().color(theme::TEXT));
+ self.command_button(ui, crate::commands::Cmd::Unwrap, Some("take the shapes out"));
+ });
+ ui.horizontal_wrapped(|ui| {
+ if let Some(v) = self.field(ui, id, "count", "copies ", s.count as f32, "how many copies") {
+ put("count", json!(v.round().max(0.0) as u32));
+ }
+ if let Some(v) = self.field(
+ ui,
+ id,
+ "seed",
+ "seed ",
+ s.seed as f32,
+ "another seed places them differently",
+ ) {
+ put("seed", json!(v.round().max(0.0) as u32));
+ }
+ [
+ ("x", "x ", s.x),
+ ("y", "y ", s.y),
+ ("w", "width ", s.w),
+ ("h", "height ", s.h),
+ ]
+ .iter()
+ .for_each(|(key, label, v)| {
+ if let Some(n) =
+ self.field(ui, id, key, label, *v, "the region the copies land in, in canvas px")
+ {
+ put(key, json!(n));
+ }
+ });
+ let size = (
+ self.field(ui, id, "size0", "smallest ", s.size[0], "the smallest copy, as a scale"),
+ self.field(ui, id, "size1", "largest ", s.size[1], "the largest copy, as a scale"),
+ );
+ if size.0.is_some() || size.1.is_some() {
+ put(
+ "size",
+ json!([size.0.unwrap_or(s.size[0]), size.1.unwrap_or(s.size[1])]),
+ );
+ }
+ let turn = (
+ self.field(ui, id, "turn0", "turn from ", s.turn[0], "the least turn, in degrees"),
+ self.field(ui, id, "turn1", "to ", s.turn[1], "the most turn, in degrees"),
+ );
+ if turn.0.is_some() || turn.1.is_some() {
+ put(
+ "turn",
+ json!([turn.0.unwrap_or(s.turn[0]), turn.1.unwrap_or(s.turn[1])]),
+ );
+ }
+ });
+ }
+ Shape::Repeat(r) => {
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("repeat").strong().color(theme::TEXT));
+ self.command_button(ui, crate::commands::Cmd::Unwrap, Some("take the shapes out"));
+ });
+ ui.horizontal_wrapped(|ui| {
+ if let Some(v) = self.field(
+ ui,
+ id,
+ "count",
+ "copies ",
+ r.count as f32,
+ "how many copies, the first included",
+ ) {
+ put("count", json!(v.round().max(0.0) as u32));
+ }
+ let step = (
+ self.field(ui, id, "step0", "step x ", r.step[0], "how far each copy moves across"),
+ self.field(ui, id, "step1", "step y ", r.step[1], "how far each copy moves down"),
+ );
+ if step.0.is_some() || step.1.is_some() {
+ put(
+ "step",
+ json!([step.0.unwrap_or(r.step[0]), step.1.unwrap_or(r.step[1])]),
+ );
+ }
+ if let Some(v) = self.field(
+ ui,
+ id,
+ "turn",
+ "turn ",
+ r.turn,
+ "each copy turns this much more, in degrees, about the pivot (an arc)",
+ ) {
+ put("turn", json!(v));
+ }
+ let pivot = (
+ self.field(ui, id, "pivot0", "pivot x ", r.pivot[0], "the point copies turn about"),
+ self.field(ui, id, "pivot1", "pivot y ", r.pivot[1], "the point copies turn about"),
+ );
+ if pivot.0.is_some() || pivot.1.is_some() {
+ put(
+ "pivot",
+ json!([pivot.0.unwrap_or(r.pivot[0]), pivot.1.unwrap_or(r.pivot[1])]),
+ );
+ }
+ if let Some(v) = self.field(
+ ui,
+ id,
+ "scale",
+ "scale ",
+ r.scale,
+ "each copy is this much bigger (1 keeps the size)",
+ ) {
+ put("scale", json!(v.max(0.01)));
+ }
+ if let Some(v) = self.field(
+ ui,
+ id,
+ "columns",
+ "columns ",
+ r.columns as f32,
+ "0 makes a line; more makes a grid this many wide",
+ ) {
+ put("columns", json!(v.round().max(0.0) as u32));
+ }
+ let row = (
+ self.field(ui, id, "row0", "row x ", r.row[0], "how far each grid row moves across"),
+ self.field(ui, id, "row1", "row y ", r.row[1], "how far each grid row moves down"),
+ );
+ if row.0.is_some() || row.1.is_some() {
+ put("row", json!([row.0.unwrap_or(r.row[0]), row.1.unwrap_or(r.row[1])]));
+ }
+ });
+ }
+ Shape::Mirror(m) => {
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("mirror").strong().color(theme::TEXT));
+ self.command_button(ui, crate::commands::Cmd::Unwrap, Some("take the shapes out"));
+ });
+ ui.horizontal_wrapped(|ui| {
+ [
+ ("x", "axis x ", m.x),
+ ("y", "axis y ", m.y),
+ ("angle", "angle ", m.angle),
+ ]
+ .iter()
+ .for_each(|(key, label, v)| {
+ if let Some(n) = self.field(
+ ui,
+ id,
+ key,
+ label,
+ *v,
+ "the mirror's axis: a point it passes through and its angle (90 is upright)",
+ ) {
+ put(key, json!(n));
+ }
+ });
+ });
+ }
+ Shape::Text(t) => {
+ ui.label(egui::RichText::new("text").strong().color(theme::TEXT));
+ let key = format!("{id}.text");
+ let mut text = self.typing.get(&key).cloned().unwrap_or_else(|| t.text.clone());
+ let edit = ui
+ .add(
+ egui::TextEdit::multiline(&mut text)
+ .desired_rows(2)
+ .desired_width(220.0),
+ )
+ .hint("the words; a new line starts a new line of text");
+ if edit.has_focus() {
+ self.typing.insert(key.clone(), text.clone());
+ } else if let Some(typed) = self.typing.remove(&key)
+ && typed != t.text
+ {
+ put("text", json!(typed));
+ }
+ let fonts = self.fonts();
+ let mut font = t.font.clone();
+ egui::ComboBox::from_id_salt(format!("{id}.font"))
+ .width(160.0)
+ .selected_text(&font)
+ .show_ui(ui, |ui| {
+ fonts.iter().for_each(|f| {
+ ui.selectable_value(&mut font, f.clone(), f);
+ });
+ })
+ .response
+ .hint("the font file, from the bundle's fonts folder (klad font adds one)");
+ if font != t.font {
+ put("font", json!(font));
+ }
+ ui.horizontal_wrapped(|ui| {
+ [("size", "size ", t.size), ("tracking", "tracking ", t.tracking), ("leading", "line height ", t.leading), ("x", "x ", t.x), ("y", "y ", t.y)]
+ .iter()
+ .for_each(|(key, label, v)| {
+ if let Some(n) = self.field(ui, id, key, label, *v, "size in px, tracking in px between letters, line height as a multiple of the size, x and y the anchor") {
+ put(key, json!(n));
+ }
+ });
+ [(Align::Left, "left"), (Align::Center, "centre"), (Align::Right, "right")]
+ .iter()
+ .for_each(|(align, label)| {
+ if ui
+ .selectable_label(t.align == *align, *label)
+ .hint("which end of each line sits at x")
+ .clicked()
+ && t.align != *align
+ {
+ put("align", json!(align));
+ }
+ });
+ });
+ }
+ Shape::Image(p) => {
+ ui.label(format!("picture {}", p.src));
+ ui.horizontal_wrapped(|ui| {
+ [
+ ("x", "x ", p.x),
+ ("y", "y ", p.y),
+ ("w", "width ", p.w),
+ ("h", "height ", p.h),
+ ]
+ .iter()
+ .for_each(|(key, label, v)| {
+ if let Some(n) = self.field(
+ ui,
+ id,
+ key,
+ label,
+ *v,
+ "where the picture sits and how big, in canvas px",
+ ) {
+ put(key, json!(n));
+ }
+ });
+ });
+ }
+ _ => {}
+ }
+ if !node.shape.generates() && !matches!(node.shape, Shape::Group { .. }) {
+ ui.horizontal_wrapped(|ui| {
+ self.command_button(ui, crate::commands::Cmd::MakeRepeat, Some("repeat it"));
+ self.command_button(ui, crate::commands::Cmd::MakeScatter, Some("scatter it"));
+ self.command_button(ui, crate::commands::Cmd::MakeMirror, Some("mirror it"));
+ });
+ }
+ out
+ }
+
+ pub(super) fn import_picture(&mut self, bytes: &[u8], name: &str) -> Result<()> {
+ let (src, w, h) = match klad_render::assets::import_image(&self.scene.bundle.root, bytes) {
+ Ok(made) => made,
+ Err(e) => {
+ self.say(Tone::Refused, format!("{name}: {e:#}"));
+ return Ok(());
+ }
+ };
+ let (cw, ch) = self.scene.size();
+ let fit = (cw as f32 / w as f32).min(ch as f32 / h as f32).min(1.0);
+ let (pw, ph) = (w as f32 * fit, h as f32 * fit);
+ let node = json!({"type": "image", "src": src, "x": (cw as f32 - pw) / 2.0, "y": (ch as f32 - ph) / 2.0, "w": pw, "h": ph});
+ let stem = std::path::Path::new(name)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("picture")
+ .to_string();
+ let frame = self.scene.frame;
+ self.add_layer_value(json!({"kind": "vector", "name": stem, "cels": [{"frame": frame, "nodes": [node]}]}))?;
+ self.say(
+ Tone::Done,
+ format!(
+ "{name} placed on a new layer: V moves and scales it, the inspector fades it or makes it a reference"
+ ),
+ );
+ Ok(())
+ }
+
+ pub(super) fn import_window(&mut self, ctx: &egui::Context) {
+ if !self.windows.import {
+ return;
+ }
+ let mut open = true;
+ egui::Window::new("import a picture")
+ .open(&mut open)
+ .resizable(false)
+ .show(ctx, |ui| {
+ let label = ui.label("PNG or JPEG file");
+ ui.add(egui::TextEdit::singleline(&mut self.import_path).desired_width(260.0))
+ .labelled_by(label.id)
+ .hint("the picture's path; dropping the file on the window works too");
+ if ui
+ .button("import")
+ .hint("copy the picture into the drawing and place it on a new layer")
+ .clicked()
+ {
+ let path = self.import_path.trim().to_string();
+ match std::fs::read(&path) {
+ Ok(bytes) => {
+ self.check(|e| e.import_picture(&bytes, &path));
+ self.windows.import = false;
+ }
+ Err(e) => self.say(Tone::Refused, format!("reading {path}: {e}")),
+ }
+ }
+ ui.small("or drop a PNG or JPEG on the canvas");
+ });
+ if !open {
+ self.windows.import = false;
+ }
+ }
+
+ pub(super) fn dropped_pictures(&mut self, ctx: &egui::Context) {
+ if self.windows.brush {
+ return;
+ }
+ let files: Vec<std::path::PathBuf> = ctx.input(|i| {
+ i.raw
+ .dropped_files
+ .iter()
+ .map(|f| f.path().to_path_buf())
+ .filter(|p| {
+ p.extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| ["png", "jpg", "jpeg"].contains(&e.to_ascii_lowercase().as_str()))
+ })
+ .collect()
+ });
+ files.into_iter().for_each(|path| match std::fs::read(&path) {
+ Ok(bytes) => self.check(|e| e.import_picture(&bytes, &path.display().to_string())),
+ Err(e) => self.say(Tone::Refused, format!("reading {}: {e}", path.display())),
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn counts_seeds_and_sizes_cannot_go_below_their_floor() {
+ [
+ ("count", 1.0),
+ ("columns", 0.0),
+ ("seed", 0.0),
+ ("scale", 0.01),
+ ("size0", 0.01),
+ ("w", 1.0),
+ ("size", 1.0),
+ ]
+ .iter()
+ .for_each(|(key, floor)| assert_eq!(*bounds(key).0.start(), *floor, "{key}"));
+ assert!(*bounds("x").0.start() < 0.0);
+ }
+
+ #[test]
+ fn shift_squares_and_alt_draws_from_the_centre() {
+ let drag = (vec2(10.0, 10.0), vec2(40.0, 20.0));
+ assert_eq!(shape_box(drag, false, false), [10.0, 10.0, 30.0, 10.0]);
+ assert_eq!(shape_box(drag, true, false), [10.0, 10.0, 30.0, 30.0]);
+ assert_eq!(shape_box(drag, false, true), [-20.0, 0.0, 60.0, 20.0]);
+ assert_eq!(
+ shape_box((vec2(10.0, 10.0), vec2(0.0, 5.0)), true, false),
+ [0.0, 0.0, 10.0, 10.0]
+ );
+ let s = Sample::quantize(30.0, 7.0, 0.5, (0.3, 0.1), 4.0);
+ let m = mirrored(&s, 100.0);
+ assert_eq!(m.pos(), (170.0, 7.0));
+ assert_eq!(mirrored(&m, 100.0), s);
+ }
+}
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
new file mode 100644
index 0000000..27d9396
--- /dev/null
+++ b/crates/app/src/editor/options.rs
@@ -0,0 +1,617 @@
+use super::{Editor, Tool};
+use crate::color;
+use crate::commands::Cmd;
+use crate::theme::{self, Hint, icon};
+use anyhow::{Result, anyhow};
+use egui::{Color32, ColorImage, RichText, Sense, TextureHandle, TextureOptions, vec2};
+use klad_brush::{BrushSet, Raster, TILE, replay};
+use klad_core::brushes::BrushDef;
+use klad_core::ops::{Op, PaletteEdit, parse_lines};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use klad_core::stroke::Mark;
+use std::collections::BTreeMap;
+
+pub const SAMPLE: (u32, u32) = (132, 30);
+pub const SIZES: [f32; 8] = [2.0, 4.0, 8.0, 12.0, 20.0, 32.0, 64.0, 128.0];
+
+pub fn size_from_drag(start: f32, dx: f32) -> f32 {
+ (start * 2f32.powf(dx / 120.0)).clamp(0.5, 800.0)
+}
+
+pub fn moved<T: Clone>(items: &[T], from: usize, to: usize) -> Vec<T> {
+ let mut out = items.to_vec();
+ if from >= out.len() {
+ return out;
+ }
+ let item = out.remove(from);
+ out.insert(to.min(out.len()), item);
+ out
+}
+
+pub fn sample(brushes: &BrushSet, id: &str) -> Result<Raster> {
+ sample_sized(brushes, id, SAMPLE, 14.0)
+}
+
+pub fn sample_sized(brushes: &BrushSet, id: &str, (w, h): (u32, u32), largest: f32) -> Result<Raster> {
+ let def = brushes.def(id).ok_or_else(|| anyhow!("no brush {id}"))?;
+ let size = (h as f32 * 0.42).min(largest);
+ let second = match def.color.is_some_and(|c| c.uses_second()) {
+ true => r##","second":"#6a8cff""##,
+ false => "",
+ };
+ let bands = match def.paint.is_some() {
+ true => format!(
+ r##"{{"op":"stroke","layer":"sample","brush":"ink","size":{s},"color":"#c0603c","path":"M{x0} 0 L{x0} {h}","seed":1}}
+{{"op":"stroke","layer":"sample","brush":"ink","size":{s},"color":"#3c68c0","path":"M{x1} 0 L{x1} {h}","seed":2}}
+"##,
+ s = w as f32 * 0.18,
+ x0 = w as f32 * 0.35,
+ x1 = w as f32 * 0.65,
+ ),
+ false => String::new(),
+ };
+ let line = format!(
+ r##"{bands}{{"op":"stroke","layer":"sample","brush":"{id}","size":{size},"color":"#e6e6e6","path":"M6 {a} C {b} {c} {d} {e} {f} {g}","pressure":[0.15,0.9,1,0.55,0.2],"taper":[{t0},{t1}],"seed":7{second}}}"##,
+ a = h as f32 * 0.7,
+ b = w as f32 * 0.3,
+ c = h as f32 * 0.05,
+ d = w as f32 * 0.6,
+ e = h as f32 * 1.05,
+ f = w as f32 - 6.0,
+ g = h as f32 * 0.3,
+ t0 = def.taper[0].min(30.0),
+ t1 = def.taper[1].min(40.0),
+ );
+ let marks: Vec<Mark> = parse_lines(&line)?
+ .into_iter()
+ .map(|op| match op {
+ Op::Stroke(spec) => spec.build(),
+ _ => Err(anyhow!("the sample stroke did not parse")),
+ })
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .flatten()
+ .enumerate()
+ .map(|(i, mut stroke)| {
+ stroke.id = i as u32 + 1;
+ Mark::Stroke(stroke)
+ })
+ .collect();
+ Ok(replay(w, h, &marks, brushes)?.raster)
+}
+
+pub fn image_of(raster: &Raster, (w, h): (u32, u32), background: Color32) -> ColorImage {
+ let bg = background.to_array().map(|c| c as f32 / 255.0);
+ let pixels = (0..h as usize)
+ .flat_map(|y| (0..w as usize).map(move |x| (x, y)))
+ .map(|(x, y)| {
+ let rgba = raster.get(x / TILE, y / TILE).map_or([0.0; 4], |t| {
+ let i = ((y % TILE) * TILE + x % TILE) * 4;
+ [t[i].to_f32(), t[i + 1].to_f32(), t[i + 2].to_f32(), t[i + 3].to_f32()]
+ });
+ let [r, g, b] =
+ [0, 1, 2].map(|k| ((rgba[k] + bg[k] * (1.0 - rgba[3])).clamp(0.0, 1.0) * 255.0).round() as u8);
+ Color32::from_rgb(r, g, b)
+ })
+ .collect();
+ ColorImage {
+ size: [w as usize, h as usize],
+ source_size: vec2(w as f32, h as f32),
+ pixels,
+ }
+}
+
+fn def_key(id: &str, def: &BrushDef) -> u64 {
+ fnv(
+ FNV_OFFSET,
+ format!("{id}{}", serde_json::to_string(def).unwrap_or_default()).as_bytes(),
+ )
+}
+
+#[derive(Default)]
+pub(super) struct Samples {
+ textures: BTreeMap<String, (u64, Option<TextureHandle>)>,
+}
+
+impl Samples {
+ fn texture(&mut self, ctx: &egui::Context, brushes: &BrushSet, id: &str, def: &BrushDef) -> Option<TextureHandle> {
+ let key = def_key(id, def);
+ if let Some((k, texture)) = self.textures.get(id).filter(|(k, _)| *k == key) {
+ let _ = k;
+ return texture.clone();
+ }
+ let texture = sample(brushes, id)
+ .ok()
+ .map(|raster| image_of(&raster, SAMPLE, theme::PANEL))
+ .map(|image| ctx.load_texture(format!("brush sample {id}"), image, TextureOptions::LINEAR));
+ self.textures.insert(id.to_string(), (key, texture.clone()));
+ texture
+ }
+}
+
+fn label_of(id: &str, def: &BrushDef) -> String {
+ match id.rsplit_once('-') {
+ Some((base, tail)) if tail.len() == 6 && tail.chars().all(|c| c.is_ascii_hexdigit()) => {
+ format!("{base} variant {tail}")
+ }
+ _ => def.name.clone(),
+ }
+}
+
+impl Editor {
+ pub(super) fn pick_new_colour(&mut self, rgba: [f32; 4]) {
+ if rgba != self.color {
+ self.second = self.color;
+ self.set_colour(rgba);
+ }
+ }
+
+ pub(super) fn swap_colours(&mut self) {
+ let (a, b) = (self.color, self.second);
+ self.second = a;
+ self.set_colour(b);
+ }
+
+ pub(super) fn colour_pair(&mut self, ui: &mut egui::Ui) {
+ let (rect, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover());
+ let back = egui::Rect::from_min_size(rect.min + vec2(12.0, 12.0), vec2(24.0, 24.0));
+ let front = egui::Rect::from_min_size(rect.min, vec2(24.0, 24.0));
+ let swap = ui
+ .interact(back, ui.scope_id().with("second colour"), Sense::click())
+ .hint(Cmd::SwapColours.spec().hint());
+ swap.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "the second colour"));
+ let current = ui
+ .interact(front, ui.scope_id().with("current colour"), Sense::click())
+ .hint("the current colour; the one behind it is the second, X swaps them");
+ current.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "the current colour"));
+ let painter = ui.painter();
+ [(back, self.second), (front, self.color)].iter().for_each(|(r, c)| {
+ painter.rect_filled(*r, 3.0, Color32::from_gray(200));
+ painter.rect_filled(*r, 3.0, color::color32(*c));
+ painter.rect_stroke(
+ *r,
+ 3.0,
+ egui::Stroke::new(1.5, Color32::from_gray(20)),
+ egui::StrokeKind::Outside,
+ );
+ });
+ if swap.clicked() || current.clicked() {
+ self.queued.push(Cmd::SwapColours);
+ }
+ }
+
+ fn brush_main(&mut self, ui: &mut egui::Ui) {
+ let current = self.brush.clone();
+ let choices: Vec<(String, String)> = self
+ .brushes
+ .defs()
+ .map(|(id, d)| (id.to_string(), label_of(id, d)))
+ .collect();
+ let shown = choices
+ .iter()
+ .find(|(id, _)| *id == current)
+ .map_or(current.clone(), |(_, l)| l.clone());
+ let mut picked = None;
+ egui::ComboBox::from_id_salt("options.brush")
+ .selected_text(shown)
+ .width(150.0)
+ .show_ui(ui, |ui| {
+ choices.iter().for_each(|(id, text)| {
+ if ui.selectable_label(*id == current, text).clicked() {
+ picked = Some(id.clone());
+ }
+ });
+ })
+ .response
+ .hint("the brush; the colour and brush panel shows them with a sample stroke");
+ if let Some(id) = picked {
+ self.pick(&id);
+ }
+ ui.add(
+ egui::Slider::new(&mut self.size, 0.5..=800.0)
+ .logarithmic(true)
+ .text("size"),
+ )
+ .hint("brush size in canvas px ([ and ], or hold cmd alt and drag sideways on the canvas)");
+ ui.add(egui::Slider::new(&mut self.opacity, 0.05..=1.0).text("opacity"))
+ .hint("a stroke never gets darker than this on its own");
+ ui.add(egui::Slider::new(&mut self.flow, 0.02..=1.0).text("flow"))
+ .hint("how much each dab lays down");
+ }
+
+ fn brush_more(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let current = self.brush.clone();
+ let t = &mut self.tuning;
+ if let Some(hardness) = t.hardness.as_mut() {
+ ui.add(egui::Slider::new(hardness, 0.0..=1.0).text("hardness"))
+ .hint("soft to hard edge; changing it draws as a variant of the brush");
+ }
+ ui.add(egui::Slider::new(&mut t.size_min, 0.0..=1.0).text("lightest size"))
+ .hint("the size at the lightest press, as a part of the full size");
+ ui.add(
+ egui::Slider::new(&mut t.size_gamma, 0.3..=3.0)
+ .logarithmic(true)
+ .text("pressure curve"),
+ )
+ .hint("below 1 light presses get wider sooner, above 1 later");
+ ui.add(egui::Slider::new(&mut t.taper[0], 0.0..=200.0).text("taper in px"))
+ .hint("how long the start of a stroke takes to reach full size");
+ ui.add(egui::Slider::new(&mut t.taper[1], 0.0..=200.0).text("taper out px"))
+ .hint("how long the end of a stroke takes to come to a point");
+ ui.add(egui::Slider::new(&mut t.stabilizer, 0.0..=200.0).text("stabiliser ms"))
+ .hint("the line follows the average of the pen's last this many ms; it catches up when you lift");
+ ui.add(egui::Slider::new(&mut t.smoothing, 0.0..=100.0).text("pressure smoothing ms"))
+ .hint("evens out pressure over this many ms");
+ if ui
+ .button("reset brush")
+ .hint("the brush's own settings again")
+ .clicked()
+ {
+ self.pick(&current);
+ }
+ let (id, _) = self.shaped()?;
+ if id != self.brush {
+ ui.small(format!("hardness or curve changed: draws as {id}, kept in the bundle"));
+ }
+ Ok(())
+ }
+
+ fn vector_colours(&mut self, ui: &mut egui::Ui, fill: &str, outline: &str) {
+ [(true, self.color, fill), (false, self.second, outline)]
+ .into_iter()
+ .for_each(|(first, rgba, hint)| {
+ let label = if first { "fill" } else { "outline" };
+ let on = if first {
+ &mut self.pen_fill
+ } else {
+ &mut self.pen_stroke
+ };
+ ui.checkbox(on, label).hint(hint);
+ if color::swatch(ui, rgba, false, theme::TARGET)
+ .hint(format!(
+ "the {label} colour, {}; click (or X) swaps the two colours",
+ color::hex(rgba)
+ ))
+ .clicked()
+ {
+ self.queued.push(Cmd::SwapColours);
+ }
+ });
+ }
+
+ pub(super) fn tool_options(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ ui.horizontal_wrapped(|ui| {
+ let (cmd, name) = match self.tool {
+ Tool::Brush if self.is_on(Cmd::Eraser) == Some(true) => (Cmd::Eraser, "eraser"),
+ Tool::Brush => (Cmd::Brush, "brush"),
+ Tool::Fill => (Cmd::Fill, "fill"),
+ Tool::Strokes => (Cmd::Strokes, "select strokes"),
+ Tool::Select => (Cmd::Shapes, "select and move"),
+ Tool::Direct => (Cmd::Points, "edit points"),
+ Tool::Pen => (Cmd::Pen, "pen"),
+ Tool::Shape => (Cmd::ShapeTool, "rectangles and ellipses"),
+ Tool::Note => (Cmd::Note, "note"),
+ };
+ ui.label(RichText::new(format!("{} {name}", cmd.spec().icon)).strong());
+ ui.separator();
+ match self.tool {
+ Tool::Brush => {
+ self.brush_main(ui);
+ ui.menu_button(format!("{} more", icon::MORE), |ui| {
+ self.check(|e| e.brush_more(ui));
+ })
+ .response
+ .hint("hardness, pressure curve, taper, stabiliser and smoothing");
+ self.command_button(ui, Cmd::BrushWindow, Some("edit"));
+ self.command_check(ui, Cmd::Symmetry, "mirror");
+ if let Some(axis) = self.mirror.as_mut() {
+ ui.add(egui::DragValue::new(axis).speed(1.0).prefix("axis x ").suffix(" px"))
+ .hint("where the mirror line stands, in canvas px");
+ }
+ if self.custom.is_some() {
+ ui.label(RichText::new("edited, not saved").color(theme::WEAK));
+ }
+ if self.scene.active_is_mask() {
+ ui.colored_label(Color32::from_rgb(255, 150, 150), self.mask_hint());
+ }
+ let vector = self
+ .scene
+ .active_layer()
+ .is_some_and(|l| l.kind() == klad_core::doc::Kind::Vector);
+ if vector {
+ ui.colored_label(
+ theme::REFUSED,
+ "this is a vector layer: P draws paths on it; brushes paint on paint layers",
+ );
+ } else if !self.scene.can_paint() {
+ ui.colored_label(theme::REFUSED, "pick a paint layer to draw on");
+ }
+ }
+ Tool::Fill => self.fill_panel(ui),
+ Tool::Strokes => {
+ self.command_check(ui, Cmd::CutLasso, "a lasso cuts strokes at its edge");
+ self.command_button(ui, Cmd::SelectAll, Some("select all"));
+ ui.label(RichText::new("click or lasso strokes; the bar under them edits them").color(theme::WEAK));
+ }
+ Tool::Select => {
+ ui.label(
+ RichText::new(
+ "click a stroke or a shape and drag it; alt drag drags a copy; drag on empty canvas to lasso strokes",
+ )
+ .color(theme::WEAK),
+ );
+ }
+ Tool::Direct => {
+ ui.label(RichText::new("click a stroke or a shape's outline, then drag its points").color(theme::WEAK));
+ self.command_button(ui, Cmd::Corner, Some("corner"));
+ self.command_button(ui, Cmd::Smooth, Some("smooth"));
+ ui.add(
+ egui::DragValue::new(&mut self.simplify_px)
+ .speed(0.05)
+ .range(0.1..=20.0)
+ .suffix(" px"),
+ )
+ .hint("how far simplified points may stray from the outline");
+ self.command_button(ui, Cmd::Simplify, Some("simplify"));
+ self.command_button(ui, Cmd::MakePath, Some("make it a path"));
+ }
+ Tool::Shape => {
+ [(super::make::ShapeKind::Rect, "rectangle"), (super::make::ShapeKind::Ellipse, "ellipse")]
+ .iter()
+ .for_each(|(kind, label)| {
+ if ui
+ .selectable_label(self.shapes.kind == *kind, *label)
+ .hint(format!("draw {label}s"))
+ .clicked()
+ {
+ self.shapes.kind = *kind;
+ }
+ });
+ if self.shapes.kind == super::make::ShapeKind::Rect {
+ ui.add(
+ egui::DragValue::new(&mut self.shapes.radius)
+ .speed(0.2)
+ .range(0.0..=500.0)
+ .prefix("corners ")
+ .suffix(" px"),
+ )
+ .hint("how round the rectangle's corners are");
+ }
+ self.vector_colours(ui, "fill the shape with the first colour", "outline the shape in the second colour");
+ ui.add(
+ egui::DragValue::new(&mut self.pen_width)
+ .speed(0.1)
+ .range(0.25..=100.0)
+ .suffix(" px"),
+ )
+ .hint("the outline's width");
+ ui.label(
+ RichText::new("drag on a vector layer; shift for a square or circle, alt from the centre")
+ .color(theme::WEAK),
+ );
+ }
+ Tool::Pen => {
+ self.vector_colours(
+ ui,
+ "closed paths are filled with the first colour",
+ "paths get an outline in the second colour; open paths always do",
+ );
+ ui.add(
+ egui::DragValue::new(&mut self.pen_width)
+ .speed(0.1)
+ .range(0.25..=100.0)
+ .suffix(" px"),
+ )
+ .hint("the outline's width");
+ match self
+ .scene
+ .active_layer()
+ .is_some_and(|l| l.kind() == klad_core::doc::Kind::Vector)
+ {
+ true => ui.label(
+ RichText::new(
+ "click for corners, drag for curves, click the first point to close, Return finishes, Esc drops it",
+ )
+ .color(theme::WEAK),
+ ),
+ false => ui.colored_label(theme::REFUSED, "pick a vector layer: the pen draws vector paths"),
+ };
+ }
+ Tool::Note => {
+ ui.label(
+ RichText::new(
+ "click the canvas to pin a note for the agent; right click a pin (any frame's) to go to it, Delete removes it",
+ )
+ .color(theme::WEAK),
+ );
+ }
+ }
+ });
+ Ok(())
+ }
+
+ pub(super) fn brush_tiles(&mut self, ui: &mut egui::Ui) {
+ ui.horizontal_wrapped(|ui| {
+ ui.label("size");
+ SIZES.iter().for_each(|s| {
+ if ui
+ .selectable_label((self.size - s).abs() < 0.01, format!("{s:.0}"))
+ .hint(format!("brush size {s:.0} px"))
+ .clicked()
+ {
+ self.size = *s;
+ }
+ });
+ });
+ let defs: Vec<(String, BrushDef)> = self.brushes.defs().map(|(id, d)| (id.to_string(), d.clone())).collect();
+ let (own, library): (Vec<_>, Vec<_>) = defs.into_iter().partition(|(id, _)| self.embedded.contains_key(id));
+ let ctx = ui.ctx().clone();
+ let mut picked = None;
+ [("in this document", own), ("library", library)]
+ .into_iter()
+ .filter(|(_, list)| !list.is_empty())
+ .for_each(|(title, list)| {
+ ui.label(RichText::new(title).color(theme::WEAK).small());
+ list.iter().for_each(|(id, def)| {
+ let label = label_of(id, def);
+ let selected = self.brush == *id;
+ let texture = match id.as_str() {
+ "eraser" => None,
+ _ => self.samples.texture(&ctx, &self.brushes, id, def),
+ };
+ let text = RichText::new(match id.as_str() {
+ "eraser" => format!("{} {label}", icon::ERASER),
+ _ => label.clone(),
+ });
+ let button = match &texture {
+ Some(t) => egui::Button::image_and_text(
+ egui::Image::new(t).fit_to_exact_size(vec2(SAMPLE.0 as f32, SAMPLE.1 as f32)),
+ text,
+ ),
+ None => egui::Button::new(text),
+ };
+ if ui
+ .add(
+ button
+ .selected(selected)
+ .min_size(vec2(ui.available_width(), theme::TARGET)),
+ )
+ .hint(format!("{id}: {}", def.name))
+ .clicked()
+ {
+ picked = Some(id.clone());
+ }
+ });
+ });
+ if let Some(id) = picked {
+ self.tool = Tool::Brush;
+ if id != "eraser" {
+ self.previous_brush = id.clone();
+ }
+ self.pick(&id);
+ }
+ }
+
+ pub(super) fn palette_row(&mut self, ui: &mut egui::Ui) -> Option<PaletteEdit> {
+ let palette = self.scene.bundle.doc.palette.clone();
+ let current = color::hex(self.color);
+ let mut edit = None;
+ let mut picked = None;
+ let mut rects = Vec::new();
+ ui.horizontal_wrapped(|ui| {
+ palette.iter().enumerate().for_each(|(i, swatch)| {
+ let rgba = color::rgba_of(&swatch.color).unwrap_or([0.0; 4]);
+ let name = match swatch.name.is_empty() {
+ true => swatch.color.clone(),
+ false => format!("{} {}", swatch.name, swatch.color),
+ };
+ let response = color::swatch_with(
+ ui,
+ rgba,
+ swatch.color.eq_ignore_ascii_case(&current),
+ 28.0,
+ Sense::click_and_drag(),
+ )
+ .hint(format!(
+ "{name}\nclick to use it, drag to move it, the x in its corner removes it"
+ ));
+ rects.push(response.rect);
+ let corner = egui::Rect::from_min_size(response.rect.right_top() - vec2(11.0, -1.0), vec2(10.0, 10.0));
+ if response.hovered() && self.swatch_drag.is_none() {
+ ui.painter()
+ .circle_filled(corner.center(), 5.0, Color32::from_black_alpha(200));
+ ui.painter().text(
+ corner.center(),
+ egui::Align2::CENTER_CENTER,
+ icon::CLOSE,
+ egui::FontId::proportional(9.0),
+ Color32::WHITE,
+ );
+ }
+ if response.clicked() {
+ let on_corner = response
+ .interact_pointer_pos()
+ .is_some_and(|p| corner.expand(2.0).contains(p));
+ match on_corner {
+ true => {
+ let mut rest = palette.clone();
+ rest.remove(i);
+ edit = Some(PaletteEdit::Set { swatches: rest });
+ }
+ false => picked = Some(rgba),
+ }
+ }
+ if response.secondary_clicked() {
+ let mut rest = palette.clone();
+ rest.remove(i);
+ edit = Some(PaletteEdit::Set { swatches: rest });
+ }
+ if response.drag_started() {
+ self.swatch_drag = Some(i);
+ }
+ });
+ });
+ if let (Some(from), true) = (self.swatch_drag, ui.input(|i| i.pointer.any_released())) {
+ let at = ui.input(|i| i.pointer.interact_pos());
+ let to = at.and_then(|p| rects.iter().position(|r| r.expand(3.0).contains(p)));
+ if let Some(to) = to.filter(|to| *to != from) {
+ edit = Some(PaletteEdit::Set {
+ swatches: moved(&palette, from, to),
+ });
+ }
+ self.swatch_drag = None;
+ }
+ if let Some(rgba) = picked {
+ self.pick_new_colour(rgba);
+ }
+ edit
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::bundle::Bundle;
+ use klad_core::doc::Document;
+
+ #[test]
+ fn dragging_sideways_doubles_the_size_every_120_pt() {
+ assert_eq!(size_from_drag(10.0, 0.0), 10.0);
+ assert!((size_from_drag(10.0, 120.0) - 20.0).abs() < 1e-4);
+ assert!((size_from_drag(10.0, -120.0) - 5.0).abs() < 1e-4);
+ assert_eq!(size_from_drag(10.0, 10_000.0), 800.0);
+ assert_eq!(size_from_drag(1.0, -10_000.0), 0.5);
+ }
+
+ #[test]
+ fn a_swatch_moves_to_where_it_is_dropped() {
+ assert_eq!(moved(&[0, 1, 2, 3], 0, 2), [1, 2, 0, 3]);
+ assert_eq!(moved(&[0, 1, 2, 3], 3, 0), [3, 0, 1, 2]);
+ assert_eq!(moved(&[0, 1, 2], 1, 9), [0, 2, 1]);
+ assert_eq!(moved(&[0, 1, 2], 7, 0), [0, 1, 2]);
+ }
+
+ #[test]
+ fn brush_samples_are_drawn_the_same_every_time_and_differ_between_brushes() {
+ let dir = std::env::temp_dir().join(format!("draw-samples-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = Bundle::create(&dir, Document::new(64, 64)).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let hashes: Vec<u64> = ["ink", "pencil", "marker", "airbrush"]
+ .iter()
+ .map(|id| sample(&brushes, id).unwrap().hash())
+ .collect();
+ assert_eq!(hashes[0], sample(&brushes, "ink").unwrap().hash());
+ let distinct: std::collections::BTreeSet<u64> = hashes.iter().copied().collect();
+ assert_eq!(distinct.len(), 4);
+ let image = image_of(&sample(&brushes, "ink").unwrap(), SAMPLE, Color32::BLACK);
+ assert_eq!(image.size, [SAMPLE.0 as usize, SAMPLE.1 as usize]);
+ assert!(image.pixels.iter().any(|p| p.r() > 120));
+ assert!(sample(&brushes, "no-such").is_err());
+ assert_eq!(
+ label_of("ink-3f0c9e", brushes.def("ink").unwrap()),
+ "ink variant 3f0c9e"
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
new file mode 100644
index 0000000..bd06cc8
--- /dev/null
+++ b/crates/app/src/editor/panels.rs
@@ -0,0 +1,963 @@
+use super::layers;
+use super::{Editor, Tool, ms};
+use crate::commands::{self, Cmd};
+use crate::jobs::{Outcome, Spec, Tag};
+use crate::layout::{self, Layout, Pane};
+use crate::messages::{Message, Tone};
+use crate::stats::lock;
+use crate::theme::{self, Hint, icon};
+use anyhow::Result;
+use egui::{Align, Color32, Id, Key, Layout as Flow, Margin, Modifiers, RichText, Sense, UiBuilder, vec2};
+use std::time::{Duration, Instant};
+
+fn colour_of(tone: Tone) -> Color32 {
+ match tone {
+ Tone::Info => theme::TEXT,
+ Tone::Done => theme::DONE,
+ Tone::Refused => theme::REFUSED,
+ Tone::Error => theme::ERROR,
+ }
+}
+
+fn icon_of(tone: Tone) -> &'static str {
+ match tone {
+ Tone::Info => icon::INFO,
+ Tone::Done => icon::CHECK,
+ Tone::Refused | Tone::Error => icon::WARNING,
+ }
+}
+
+fn ago(at: Instant, now: Instant) -> String {
+ let s = now.duration_since(at).as_secs();
+ match s {
+ 0..=59 => format!("{s} s ago"),
+ 60..=3599 => format!("{} min ago", s / 60),
+ _ => format!("{} h ago", s / 3600),
+ }
+}
+
+const STRIP_TOOLS: [Cmd; 9] = [
+ Cmd::Brush,
+ Cmd::Eraser,
+ Cmd::Fill,
+ Cmd::Strokes,
+ Cmd::Shapes,
+ Cmd::Points,
+ Cmd::Pen,
+ Cmd::ShapeTool,
+ Cmd::Note,
+];
+
+impl Editor {
+ pub(super) fn check(&mut self, f: impl FnOnce(&mut Self) -> Result<()>) {
+ if let Err(e) = f(self) {
+ self.error(e);
+ }
+ }
+
+ pub(crate) fn frame(&mut self, ui: &mut egui::Ui) {
+ let start = Instant::now();
+ let ctx = ui.ctx().clone();
+ if !self.themed {
+ theme::install(&ctx);
+ self.themed = true;
+ }
+ theme::clear_hints(&ctx);
+ if (ctx.zoom_factor() - self.settings.ui_scale).abs() > 1e-3 {
+ ctx.set_zoom_factor(self.settings.ui_scale);
+ }
+ let dt = ui.input(|i| i.unstable_dt);
+ if dt < 0.1 {
+ lock(&self.stats).frame_ms.push(dt * 1000.0);
+ }
+ self.pointer = ui.input(|i| i.pointer.latest_pos()).or(self.pointer);
+ self.check(|e| e.sync());
+ self.tend_jobs();
+ self.check(|e| e.tab_keys());
+ let window = ctx.content_rect().size();
+ self.settings.layout.clamp(window);
+ let pressing = ui.input(|i| i.pointer.any_down());
+ egui::Panel::bottom("status")
+ .exact_size(layout::STATUS)
+ .resizable(false)
+ .show(ui, |ui| self.status_line(ui));
+ if self.settings.layout.shows_timeline() {
+ let folded = self.settings.layout.timeline_folded;
+ let (lo, hi) = Layout::timeline_range(window);
+ let panel = match folded {
+ true => egui::Panel::bottom("timeline folded")
+ .exact_size(layout::TIMELINE_FOLDED)
+ .resizable(false),
+ false => egui::Panel::bottom("timeline")
+ .default_size(self.settings.layout.timeline_height)
+ .size_range(lo..=hi)
+ .resizable(true),
+ };
+ let shown = panel.show(ui, |ui| self.check(|e| e.timeline_panel(ui)));
+ let height = shown.response.rect.height();
+ if !folded && !pressing && (height - self.settings.layout.timeline_height).abs() > 0.5 {
+ self.settings.layout.timeline_height = height;
+ self.settings_dirty = true;
+ }
+ }
+ if self.settings.layout.shows_strip() {
+ egui::Panel::left("strip")
+ .exact_size(layout::STRIP)
+ .resizable(false)
+ .show(ui, |ui| self.strip(ui));
+ }
+ if self.settings.layout.shows_dock() {
+ let (lo, hi) = Layout::dock_range(window);
+ let shown = egui::Panel::right("dock")
+ .default_size(self.settings.layout.dock_width)
+ .size_range(lo..=hi)
+ .resizable(true)
+ .frame(egui::Frame::side_top_panel(&ctx.global_style()).inner_margin(Margin::ZERO))
+ .show(ui, |ui| self.dock(ui));
+ let width = shown.response.rect.width();
+ if !pressing && (width - self.settings.layout.dock_width).abs() > 0.5 {
+ self.settings.layout.dock_width = width;
+ self.settings_dirty = true;
+ }
+ }
+ if !self.settings.layout.hidden {
+ egui::Panel::top("options")
+ .resizable(false)
+ .show(ui, |ui| self.check(|e| e.tool_options(ui)));
+ }
+ let panels = ms(start);
+ egui::CentralPanel::no_frame().show(ui, |ui| self.check(|e| e.canvas(ui)));
+ let after = Instant::now();
+ self.windows(&ctx);
+ self.import_window(&ctx);
+ self.dropped_pictures(&ctx);
+ self.tend_thumbs(&ctx);
+ if let Some(path) = self.queued_activate.take() {
+ self.check(|e| e.activate(path));
+ }
+ self.check(|e| e.tend_pick());
+ self.check(|e| e.pin_popover(&ctx));
+ self.check(|e| e.run_queued());
+ lock(&self.stats).ui_ms.push((panels + ms(after)) as f32);
+ self.save_settings(pressing);
+ if let Some(wait) = self.messages.next_change(Instant::now()) {
+ ctx.request_repaint_after(wait.max(Duration::from_millis(16)));
+ }
+ if !self.jobs.is_empty() {
+ ctx.request_repaint_after(Duration::from_millis(100));
+ }
+ }
+
+ fn save_settings(&mut self, pressing: bool) {
+ if !self.settings_dirty || pressing {
+ return;
+ }
+ if let Some(path) = &self.settings_path
+ && let Err(e) = self.settings.save(path)
+ {
+ self.error(format!("saving your settings: {e:#}"));
+ }
+ self.settings_dirty = false;
+ }
+
+ pub(super) fn start_job(&mut self, mut spec: Spec) {
+ spec.exe = match std::env::current_exe() {
+ Ok(exe) => exe,
+ Err(e) => {
+ self.error(format!("cannot find the klad binary: {e}"));
+ return;
+ }
+ };
+ let name = spec.name.clone();
+ match self.jobs.start(spec) {
+ Ok(_) => self.say(Tone::Info, format!("{name}...")),
+ Err(e) => self.error(format!("cannot run {name}: {e}")),
+ }
+ }
+
+ fn say_job(&mut self, tone: Tone, text: String) {
+ self.messages.say(tone, text, None, Instant::now());
+ }
+
+ fn tend_jobs(&mut self) {
+ self.jobs.poll().into_iter().for_each(|e| {
+ let took = e.took.as_secs_f32();
+ match e.outcome {
+ Outcome::Rerun => self.say_job(
+ Tone::Info,
+ format!("{}: the document changed while it ran, so it runs again", e.name),
+ ),
+ Outcome::Done(text) => {
+ if e.tag == Tag::Inbetween {
+ self.check(|ed| ed.reload());
+ self.between.report = super::between::report(&e.output);
+ }
+ let detail = if text.is_empty() {
+ String::new()
+ } else {
+ format!(": {text}")
+ };
+ self.measure("last job", format!("{} in {took:.1} s{detail}", e.name));
+ self.say_job(Tone::Done, format!("{} done in {took:.1} s{detail}", e.name));
+ }
+ Outcome::Failed(text) => {
+ if e.tag == Tag::Inbetween {
+ self.between.report = super::between::report(&e.output);
+ }
+ self.say_job(Tone::Error, format!("{} failed: {text}", e.name))
+ }
+ Outcome::Cancelled => self.say_job(Tone::Info, format!("{} cancelled", e.name)),
+ }
+ });
+ }
+
+ fn strip(&mut self, ui: &mut egui::Ui) {
+ ui.spacing_mut().item_spacing.y = 4.0;
+ ui.vertical_centered(|ui| {
+ ui.add_space(6.0);
+ STRIP_TOOLS.iter().for_each(|cmd| {
+ let r = self.command_sized(ui, *cmd, None, 20.0, vec2(36.0, 36.0));
+ self.key_letter(ui, r.rect, *cmd);
+ });
+ ui.add_space(4.0);
+ self.colour_pair(ui);
+ ui.separator();
+ [Cmd::Undo, Cmd::Redo].iter().for_each(|cmd| {
+ self.command_sized(ui, *cmd, None, 18.0, vec2(36.0, 32.0));
+ });
+ });
+ ui.with_layout(Flow::bottom_up(Align::Center), |ui| {
+ ui.add_space(6.0);
+ [Cmd::Settings, Cmd::Numbers, Cmd::Palette].iter().for_each(|cmd| {
+ self.command_sized(ui, *cmd, None, 18.0, vec2(36.0, 32.0));
+ });
+ self.panels_menu(ui);
+ self.document_menu(ui);
+ });
+ }
+
+ fn document_menu(&mut self, ui: &mut egui::Ui) {
+ let button = egui::Button::new(RichText::new(icon::FILE).size(18.0)).min_size(vec2(36.0, 32.0));
+ let name = self
+ .scene
+ .bundle
+ .root
+ .file_stem()
+ .map_or_else(String::new, |s| s.to_string_lossy().to_string());
+ egui::containers::menu::MenuButton::from_button(button)
+ .ui(ui, |ui| {
+ ui.label(RichText::new(&name).strong());
+ ui.separator();
+ [
+ (Cmd::NewDocument, "new drawing"),
+ (Cmd::OpenDocument, "open"),
+ (Cmd::OpenRecent, "recent"),
+ (Cmd::CopyPath, "copy path"),
+ (Cmd::About, "about and licences"),
+ ]
+ .into_iter()
+ .for_each(|(cmd, label)| {
+ if self.command_button(ui, cmd, Some(label)).clicked() {
+ ui.close();
+ }
+ });
+ })
+ .0
+ .hint(format!("{name}: new, open, recent drawings, copy its path"));
+ }
+
+ fn about_panel(ui: &mut egui::Ui) {
+ static LINES: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
+ let lines = LINES.get_or_init(|| klad_core::notices::NOTICES.lines().collect());
+ ui.label(RichText::new(format!("klad {}", env!("CARGO_PKG_VERSION"))).strong());
+ ui.label("Source-available licence, copyright Indicode BV. Built on the open source work listed below; klad licences prints the same.");
+ ui.add_space(6.0);
+ ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
+ let row = ui.text_style_height(&egui::TextStyle::Small);
+ egui::ScrollArea::vertical()
+ .max_height(420.0)
+ .auto_shrink([false, false])
+ .show_rows(ui, row, lines.len(), |ui, rows| {
+ ui.set_width(600.0);
+ lines[rows].iter().for_each(|line| {
+ ui.label(RichText::new(*line).small());
+ });
+ });
+ }
+
+ fn panels_menu(&mut self, ui: &mut egui::Ui) {
+ let button = egui::Button::new(RichText::new(icon::SIDEBAR).size(18.0)).min_size(vec2(36.0, 32.0));
+ egui::containers::menu::MenuButton::from_button(button)
+ .ui(ui, |ui| {
+ [
+ (Cmd::ToolPane, Pane::Tool),
+ (Cmd::LayersPane, Pane::Layers),
+ (Cmd::InspectorPane, Pane::Inspector),
+ (Cmd::NotesPane, Pane::Notes),
+ (Cmd::HistoryPane, Pane::History),
+ ]
+ .into_iter()
+ .for_each(|(cmd, pane)| {
+ self.command_check(ui, cmd, pane.title());
+ });
+ ui.separator();
+ self.command_check(ui, Cmd::Timeline, "timeline");
+ })
+ .0
+ .hint("the panels: tick one to show it, untick to close it");
+ }
+
+ fn dock(&mut self, ui: &mut egui::Ui) {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ let bodies = self.settings.layout.bodies(ui.available_height());
+ let mut previous: Option<(Pane, bool)> = None;
+ bodies.into_iter().for_each(|(pane, body)| {
+ self.pane_title(ui, pane, body.is_none(), previous);
+ if let Some(height) = body {
+ egui::ScrollArea::vertical()
+ .id_salt(("pane", pane))
+ .max_height(height)
+ .min_scrolled_height(height)
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 5.0;
+ egui::Frame::new()
+ .inner_margin(Margin::symmetric(8, 6))
+ .show(ui, |ui| self.check(|e| e.pane_body(ui, pane)));
+ });
+ }
+ previous = Some((pane, body.is_some()));
+ });
+ }
+
+ fn pane_title(&mut self, ui: &mut egui::Ui, pane: Pane, collapsed: bool, previous: Option<(Pane, bool)>) {
+ let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), layout::TITLE), Sense::hover());
+ ui.painter().rect_filled(rect, 0.0, Color32::from_gray(42));
+ ui.painter().line_segment(
+ [rect.left_top(), rect.right_top()],
+ egui::Stroke::new(1.0, Color32::from_gray(24)),
+ );
+ if let Some((above, true)) = previous {
+ let grip = egui::Rect::from_min_size(rect.min, vec2(rect.width(), 5.0));
+ let r = ui.interact(grip, Id::unique(("pane grip", pane)), Sense::drag());
+ if r.hovered() || r.dragged() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
+ }
+ if r.dragged() {
+ let dy = r.drag_delta().y;
+ self.settings.layout.resize_pane(above, dy);
+ }
+ if r.drag_stopped() {
+ self.settings_dirty = true;
+ }
+ }
+ let mut child = ui.new_child(
+ UiBuilder::new()
+ .max_rect(rect.shrink2(vec2(4.0, 3.0)))
+ .layout(Flow::left_to_right(Align::Center)),
+ );
+ let caret = if collapsed { icon::FOLDED } else { icon::OPEN };
+ let toggle = child
+ .add(
+ egui::Button::new(RichText::new(caret).size(theme::ICON))
+ .frame(false)
+ .min_size(vec2(theme::TARGET, theme::TARGET)),
+ )
+ .hint(match collapsed {
+ true => format!("open {}", pane.title()),
+ false => format!("fold {} to its title", pane.title()),
+ });
+ child.label(RichText::new(pane.title()).strong());
+ let mut close = false;
+ child.with_layout(Flow::right_to_left(Align::Center), |ui| {
+ close = ui
+ .add(
+ egui::Button::new(RichText::new(icon::CLOSE).size(theme::ICON))
+ .frame(false)
+ .min_size(vec2(theme::TARGET, theme::TARGET)),
+ )
+ .hint(format!("close {}; cmd K brings it back", pane.title()))
+ .clicked();
+ if pane == Pane::Layers && !collapsed {
+ self.check(|e| e.layer_header(ui));
+ }
+ });
+ if toggle.clicked()
+ && let Some(p) = self.settings.layout.pane_mut(pane)
+ {
+ p.collapsed = !p.collapsed;
+ self.settings_dirty = true;
+ }
+ if close {
+ self.settings.layout.toggle(pane);
+ self.settings_dirty = true;
+ }
+ }
+
+ fn pane_body(&mut self, ui: &mut egui::Ui, pane: Pane) -> Result<()> {
+ match pane {
+ Pane::Tool => {
+ self.colour_panel(ui)?;
+ ui.separator();
+ self.brush_tiles(ui);
+ Ok(())
+ }
+ Pane::Layers => self.layers_pane(ui),
+ Pane::Inspector => match (self.tool, self.selection.clone()) {
+ _ if self.on_marks() => {
+ self.strokes_inspector(ui)?;
+ ui.separator();
+ self.layer_inspector(ui)
+ }
+ (Tool::Direct, _) => {
+ self.path_inspector(ui)?;
+ ui.separator();
+ self.layer_inspector(ui)
+ }
+ (_, Some(id)) => self.node_inspector(ui, &id),
+ (_, None) => self.layer_inspector(ui),
+ },
+ Pane::Notes => self.notes_pane(ui),
+ Pane::History => self.history_pane(ui),
+ }
+ }
+
+ fn status_line(&mut self, ui: &mut egui::Ui) {
+ let now = Instant::now();
+ let mut cancel = None;
+ let mut open_log = false;
+ ui.horizontal_centered(|ui| {
+ let frames = self.scene.bundle.doc.timeline.frames;
+ ui.label(RichText::new(format!("frame {} of {frames}", self.shown_frame())).strong());
+ if self.timeline.player.is_some() {
+ ui.label(
+ RichText::new(format!("{} playing {}", icon::PLAY, self.timeline.playing)).color(theme::ACCENT),
+ );
+ }
+ ui.separator();
+ ui.label(self.draws_into());
+ self.jobs.running(now).into_iter().for_each(|(id, name, took)| {
+ ui.separator();
+ ui.add(egui::Spinner::new().size(14.0));
+ ui.label(format!("{name} {:.1} s", took.as_secs_f32()));
+ if ui
+ .add(egui::Button::new(icon::CLOSE).min_size(vec2(theme::TARGET, theme::TARGET)))
+ .hint(format!("cancel {name}"))
+ .clicked()
+ {
+ cancel = Some(id);
+ }
+ });
+ self.internal_work(now).into_iter().for_each(|what| {
+ ui.separator();
+ ui.add(egui::Spinner::new().size(14.0));
+ ui.label(what);
+ });
+ ui.with_layout(Flow::right_to_left(Align::Center), |ui| {
+ if let Some(view) = self.view {
+ let degrees = view.angle.to_degrees().rem_euclid(360.0);
+ let flat = |text: String| egui::Button::new(RichText::new(text).color(theme::WEAK)).frame(false);
+ let zoom = ui
+ .add(flat(format!("{:.0}%", view.zoom * ui.ctx().pixels_per_point() * 100.0)))
+ .hint("zoom; click for 100%, double-click to fit the canvas");
+ if zoom.double_clicked() {
+ self.queued.push(Cmd::Fit);
+ } else if zoom.clicked() {
+ self.queued.push(Cmd::ActualSize);
+ }
+ if ui
+ .add(flat(format!("{degrees:.0}\u{b0}")))
+ .hint("the view's rotation; click to turn it upright")
+ .clicked()
+ {
+ self.queued.push(Cmd::ResetRotation);
+ }
+ if view.flip
+ && ui
+ .add(flat(format!("{} flipped", icon::FLIP_H)))
+ .hint("the view is mirrored (H); the document is not")
+ .clicked()
+ {
+ self.queued.push(Cmd::FlipView);
+ }
+ }
+ ui.separator();
+ if let Some(m) = self.messages.latest() {
+ let text = RichText::new(format!("{} {}", icon_of(m.tone), m.text)).color(colour_of(m.tone));
+ open_log = ui
+ .add(egui::Button::new(text).frame(false).truncate())
+ .hint("the last message; click for the message log")
+ .clicked();
+ }
+ });
+ });
+ if let Some(id) = cancel {
+ self.jobs.cancel(id);
+ }
+ if open_log {
+ self.windows.log = true;
+ }
+ }
+
+ fn internal_work(&self, now: Instant) -> Vec<String> {
+ let slow = Duration::from_millis(600);
+ let mut work = Vec::new();
+ if self.lift.as_ref().is_some_and(|l| l.job.is_some()) && now.duration_since(self.lift_since) > slow {
+ work.push("preparing the selection".to_string());
+ }
+ if self.path_commit.is_some() {
+ work.push("drawing the edited path".to_string());
+ }
+ let loading = self.frames.jobs() > 0 && self.timeline.on_screen != Some(self.scene.frame);
+ if self.timeline.player.is_none() && (loading || self.canvas_loading()) {
+ work.push(format!("loading frame {}", self.scene.frame));
+ }
+ work.extend(self.preparing_text());
+ work
+ }
+
+ fn window(
+ ctx: &egui::Context,
+ id: &str,
+ (title, at): (String, egui::Pos2),
+ open: &mut bool,
+ add: impl FnOnce(&mut egui::Ui),
+ ) {
+ egui::Window::new(&title)
+ .id(Id::unique(id))
+ .default_pos(at)
+ .title_bar(false)
+ .resizable(true)
+ .default_width(360.0)
+ .show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(&title).strong());
+ ui.with_layout(Flow::right_to_left(Align::Center), |ui| {
+ if ui
+ .add(
+ egui::Button::new(RichText::new(icon::CLOSE).size(theme::ICON))
+ .frame(false)
+ .min_size(vec2(theme::TARGET, theme::TARGET)),
+ )
+ .hint(format!("close {title}"))
+ .clicked()
+ {
+ *open = false;
+ }
+ });
+ });
+ ui.separator();
+ add(ui);
+ });
+ }
+
+ fn windows(&mut self, ctx: &egui::Context) {
+ if !self.settings.layout.hidden || self.selected().is_some() {
+ self.selection_bar(ctx);
+ }
+ let screen = ctx.content_rect();
+ let layout = &self.settings.layout;
+ let dock = if layout.shows_dock() { layout.dock_width } else { 0.0 };
+ let strip = if layout.shows_strip() { layout::STRIP } else { 0.0 };
+ let timeline = if layout.shows_timeline() {
+ layout.timeline_height
+ } else {
+ 0.0
+ };
+ let above = screen.bottom() - layout::STATUS - timeline;
+ let numbers_at = egui::pos2(screen.right() - dock - 380.0, screen.top() + 16.0);
+ let settings_at = egui::pos2(screen.center().x - 180.0, screen.top() + 60.0);
+ let log_at = egui::pos2(screen.left() + strip + 16.0, (above - 380.0).max(screen.top() + 16.0));
+ let near_timeline = egui::pos2(screen.left() + strip + 16.0, (above - 300.0).max(screen.top() + 16.0));
+ self.palette_window(ctx);
+ self.toasts(ctx);
+ if self.settings.layout.numbers {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "numbers",
+ (format!("{} Numbers", icon::NUMBERS), numbers_at),
+ &mut open,
+ |ui| self.numbers_panel(ui),
+ );
+ if !open {
+ self.settings.layout.numbers = false;
+ self.settings_dirty = true;
+ }
+ }
+ if self.windows.settings {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "settings",
+ (format!("{} Settings", icon::SETTINGS), settings_at),
+ &mut open,
+ |ui| self.settings_panel(ui),
+ );
+ self.windows.settings &= open;
+ }
+ if self.windows.brush {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "brush",
+ (format!("{} Brush", icon::BRUSH), settings_at),
+ &mut open,
+ |ui| self.check(|e| e.brush_window_ui(ui)),
+ );
+ self.windows.brush &= open;
+ }
+ if self.windows.about {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "about",
+ (format!("{} About klad", icon::INFO), settings_at),
+ &mut open,
+ Self::about_panel,
+ );
+ self.windows.about &= open;
+ }
+ if self.windows.log {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "log",
+ (format!("{} Messages", icon::LOG), log_at),
+ &mut open,
+ |ui| self.log_panel(ui),
+ );
+ self.windows.log &= open;
+ }
+ if self.windows.onion {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "onion",
+ (format!("{} Onion skin", icon::ONION), near_timeline),
+ &mut open,
+ |ui| self.check(|e| e.onion_settings(ui)),
+ );
+ self.windows.onion &= open;
+ }
+ if self.windows.link {
+ let mut open = true;
+ let mut chosen = None;
+ let drawings: Vec<(String, u32)> = self
+ .scene
+ .active_layer()
+ .map(|l| {
+ l.cels()
+ .iter()
+ .filter(|c| c.link.is_none())
+ .map(|c| (c.id.clone(), c.frame))
+ .collect()
+ })
+ .unwrap_or_default();
+ let frame = self.scene.frame;
+ let thumbs: Vec<_> = drawings.iter().map(|(id, _)| self.thumb(ctx, id)).collect();
+ Self::window(
+ ctx,
+ "link",
+ (format!("{} Show a drawing here", icon::LINK), near_timeline),
+ &mut open,
+ |ui| {
+ ui.label(format!("frame {frame} will show the drawing you pick, as a link"));
+ ui.horizontal_wrapped(|ui| {
+ drawings.iter().zip(&thumbs).for_each(|((id, f), thumb)| {
+ let text = format!("frame {f}");
+ let button = match thumb {
+ Some(t) => egui::Button::image_and_text(
+ egui::Image::new(t).fit_to_exact_size(egui::vec2(
+ layers::THUMB.0 as f32 * 2.0,
+ layers::THUMB.1 as f32 * 2.0,
+ )),
+ text,
+ ),
+ None => egui::Button::new(text),
+ };
+ if ui
+ .add(button)
+ .hint(format!("show {id} again here; drawing on it changes both"))
+ .clicked()
+ {
+ chosen = Some(id.clone());
+ }
+ });
+ });
+ },
+ );
+ if let Some(id) = chosen {
+ self.check(|e| e.link_here(id));
+ open = false;
+ }
+ self.windows.link &= open;
+ }
+ if self.windows.between {
+ let mut open = true;
+ Self::window(
+ ctx,
+ "between",
+ (format!("{} In-betweens", icon::INBETWEEN), near_timeline),
+ &mut open,
+ |ui| self.check(|e| e.between_window(ui)),
+ );
+ self.windows.between &= open;
+ }
+ if self.windows.clip {
+ let mut open = true;
+ let title = self
+ .current_clip()
+ .map_or("Clip".to_string(), |c| format!("Clip {}", c.name));
+ Self::window(
+ ctx,
+ "clip",
+ (format!("{} {title}", icon::CLIP_BAR), near_timeline),
+ &mut open,
+ |ui| self.check(|e| e.clip_window(ui)),
+ );
+ self.windows.clip &= open;
+ }
+ }
+
+ fn numbers_panel(&mut self, ui: &mut egui::Ui) {
+ let r = &self.readout;
+ ui.add(egui::ProgressBar::new(r.pressure).text(format!("pressure {:.3}", r.pressure)));
+ ui.label(format!(
+ "tilt {:.2}, {:.2} {}{} {} samples/s",
+ r.tilt.0,
+ r.tilt.1,
+ if r.tablet { "tablet" } else { "mouse" },
+ if r.eraser { ", eraser end" } else { "" },
+ r.samples.len()
+ ));
+ let lines = {
+ let s = lock(&self.stats);
+ [
+ format!(
+ "frame {} ({:.0} fps)",
+ s.frame_ms.summary(),
+ 1000.0 / s.frame_ms.avg().max(0.001)
+ ),
+ format!("pen to GPU {}", s.latency_ms.summary()),
+ format!("ui {}", s.ui_ms.spread()),
+ format!("compose {}", s.compose_ms.summary()),
+ format!("tiles {}", s.tiles.summary()),
+ format!("upload {}", s.upload_ms.summary()),
+ format!("frame step {}", s.step_ms.summary()),
+ format!("frame upload {}", s.frame_upload_ms.summary()),
+ ]
+ };
+ lines.iter().for_each(|l| {
+ ui.label(RichText::new(l).monospace());
+ });
+ ui.label(
+ RichText::new(format!(
+ "frame cache {} frames, {} MB, {} composing",
+ self.frames.len(),
+ self.frames.bytes() >> 20,
+ self.frames.jobs()
+ ))
+ .monospace(),
+ );
+ ui.label(RichText::new(format!("drawings {} MB in memory", self.scene.cache_bytes() >> 20)).monospace());
+ ui.separator();
+ let measured: Vec<(String, String)> = self.measured.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
+ measured.into_iter().for_each(|(k, v)| {
+ ui.label(RichText::new(format!("{k}: {v}")).small());
+ });
+ ui.horizontal_wrapped(|ui| {
+ self.command_check(ui, Cmd::Spin, "spin (fps test)");
+ self.command_button(ui, Cmd::ResetNumbers, Some("reset"));
+ });
+ }
+
+ fn settings_panel(&mut self, ui: &mut egui::Ui) {
+ ui.heading("Pen calibration");
+ self.pen_panel(ui);
+ ui.separator();
+ ui.heading("Defaults");
+ self.defaults_section(ui);
+ ui.separator();
+ ui.heading("Keys");
+ self.keys_section(ui);
+ ui.separator();
+ ui.heading("Layout");
+ self.scale_section(ui);
+ ui.horizontal_wrapped(|ui| {
+ self.command_check(ui, Cmd::Numbers, "numbers panel");
+ self.command_check(ui, Cmd::Timeline, "timeline");
+ if ui
+ .button("reset the layout")
+ .hint("every panel back where it starts, at its first size")
+ .clicked()
+ {
+ self.settings.layout = Layout::default();
+ self.settings_dirty = true;
+ }
+ });
+ ui.small("Tab hides the panels, shift Tab the dock, cmd K finds any command.");
+ }
+
+ fn log_panel(&mut self, ui: &mut egui::Ui) {
+ let now = Instant::now();
+ let log: Vec<Message> = self.messages.log().rev().cloned().collect();
+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
+ if log.is_empty() {
+ ui.label("no messages yet");
+ }
+ log.iter().for_each(|m| {
+ ui.horizontal_wrapped(|ui| {
+ ui.label(RichText::new(icon_of(m.tone)).color(colour_of(m.tone)));
+ ui.label(RichText::new(ago(m.at, now)).color(theme::WEAK).small());
+ let times = if m.times > 1 {
+ format!(" (x{})", m.times)
+ } else {
+ String::new()
+ };
+ ui.label(format!("{}{times}", m.text));
+ });
+ });
+ });
+ }
+
+ fn toasts(&mut self, ctx: &egui::Context) {
+ let now = Instant::now();
+ let screen = ctx.content_rect();
+ let shown: Vec<Message> = self.messages.toasts(now).into_iter().cloned().collect();
+ let mut dismiss = None;
+ let mut near = 0.0;
+ let mut corner = screen.bottom() - layout::STATUS - 10.0;
+ shown.iter().rev().for_each(|m| {
+ let (pos, pivot) = match m.anchor {
+ Some(p) => {
+ let at = p + vec2(18.0, 16.0 + near);
+ near += 38.0;
+ (at, egui::Align2::LEFT_TOP)
+ }
+ None => {
+ let at = egui::pos2(screen.right() - 12.0, corner);
+ corner -= 40.0;
+ (at, egui::Align2::RIGHT_BOTTOM)
+ }
+ };
+ let sticky = m.tone == Tone::Error;
+ egui::Area::new(Id::unique(("toast", m.id)))
+ .order(egui::Order::Tooltip)
+ .pivot(pivot)
+ .fixed_pos(pos)
+ .interactable(sticky)
+ .constrain(true)
+ .show(ctx, |ui| {
+ egui::Frame::popup(ui.style())
+ .fill(Color32::from_gray(30))
+ .stroke(egui::Stroke::new(1.0, colour_of(m.tone)))
+ .show(ui, |ui| {
+ ui.set_max_width(380.0);
+ ui.horizontal(|ui| {
+ ui.label(
+ RichText::new(icon_of(m.tone))
+ .color(colour_of(m.tone))
+ .size(theme::ICON),
+ );
+ ui.label(&m.text);
+ if sticky
+ && ui
+ .add(
+ egui::Button::new(icon::CLOSE).min_size(vec2(theme::TARGET, theme::TARGET)),
+ )
+ .hint("dismiss; the message log keeps it")
+ .clicked()
+ {
+ dismiss = Some(m.id);
+ }
+ });
+ });
+ });
+ });
+ if let Some(id) = dismiss {
+ self.messages.dismiss(id);
+ }
+ }
+
+ fn palette_window(&mut self, ctx: &egui::Context) {
+ let Some(mut state) = self.palette.take() else {
+ return;
+ };
+ let recent = self.recent_commands();
+ let found = commands::rank(&state.query, &recent);
+ let mut run = None;
+ let modal = egui::Modal::new(Id::unique("palette")).show(ctx, |ui| {
+ ui.set_width(560.0);
+ let (down, up, enter) = ui.input_mut(|i| {
+ (
+ i.consume_key(Modifiers::NONE, Key::ArrowDown),
+ i.consume_key(Modifiers::NONE, Key::ArrowUp),
+ i.consume_key(Modifiers::NONE, Key::Enter),
+ )
+ });
+ let last = found.len().saturating_sub(1);
+ state.selected = match (down, up) {
+ (true, _) => (state.selected + 1).min(last),
+ (_, true) => state.selected.saturating_sub(1),
+ _ => state.selected.min(last),
+ };
+ let label = ui.label(RichText::new(format!("{} Find a command", icon::SEARCH)).strong());
+ let edit = ui
+ .add(
+ egui::TextEdit::singleline(&mut state.query)
+ .hint_text("type what you want to do, or a key")
+ .desired_width(f32::INFINITY),
+ )
+ .labelled_by(label.id)
+ .hint("type a few letters; arrows pick, Return runs, Esc closes");
+ if !state.opened {
+ edit.request_focus();
+ state.opened = true;
+ }
+ if edit.changed() {
+ state.selected = 0;
+ }
+ if enter {
+ run = found.get(state.selected).copied();
+ }
+ ui.add_space(4.0);
+ egui::ScrollArea::vertical().max_height(440.0).show(ui, |ui| {
+ if found.is_empty() {
+ ui.label("nothing matches");
+ }
+ found.iter().enumerate().for_each(|(i, cmd)| {
+ let spec = cmd.spec();
+ let reason = self.can_run(*cmd);
+ let colour = if reason.is_some() { theme::WEAK } else { theme::TEXT };
+ let row = ui
+ .add(
+ egui::Button::new(RichText::new(format!("{} {}", spec.icon, spec.name)).color(colour))
+ .right_text(RichText::new(self.bindings.label(*cmd)).color(theme::WEAK))
+ .selected(i == state.selected)
+ .min_size(vec2(ui.available_width(), theme::TARGET)),
+ )
+ .hint(self.command_hint(*cmd));
+ if i == state.selected && (down || up) {
+ row.scroll_to_me(None);
+ }
+ if let Some(reason) = reason.filter(|_| !spec.is_hold()) {
+ ui.label(
+ RichText::new(format!(" {}: {reason}", spec.group.name()))
+ .small()
+ .color(theme::WEAK),
+ );
+ }
+ if row.clicked() {
+ run = Some(*cmd);
+ }
+ });
+ });
+ });
+ match run {
+ Some(cmd) => self.queued.push(cmd),
+ None if !modal.should_close() => self.palette = Some(state),
+ None => {}
+ }
+ }
+}
diff --git a/crates/app/src/editor/pins.rs b/crates/app/src/editor/pins.rs
new file mode 100644
index 0000000..567f499
--- /dev/null
+++ b/crates/app/src/editor/pins.rs
@@ -0,0 +1,352 @@
+use super::Editor;
+use crate::messages::Tone;
+use crate::theme::{self, Hint, icon};
+use anyhow::Result;
+use egui::{Color32, Pos2, Rect, RichText, Vec2, vec2};
+use klad_core::notes::{self, Note};
+
+pub(super) const PIN: f32 = 11.0;
+
+pub(super) fn hit_pin(pins: &[Note], frame: u32, at: Vec2, zoom: f32) -> Option<u32> {
+ let reach = (PIN + 4.0) / zoom.max(1e-3);
+ pins.iter()
+ .filter(|n| n.frame == frame)
+ .map(|n| (n.id, (n.x - at.x).hypot(n.y - at.y)))
+ .filter(|(_, d)| *d <= reach)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(id, _)| id)
+}
+
+pub(super) fn hit_any_pin(pins: &[Note], frame: u32, at: Vec2, zoom: f32) -> Option<(u32, u32)> {
+ let reach = (PIN + 4.0) / zoom.max(1e-3);
+ pins.iter()
+ .filter(|n| !n.done || n.frame == frame)
+ .map(|n| (n, (n.x - at.x).hypot(n.y - at.y)))
+ .filter(|(_, d)| *d <= reach)
+ .min_by(|a, b| {
+ (a.0.frame != frame, a.1)
+ .partial_cmp(&(b.0.frame != frame, b.1))
+ .unwrap_or(std::cmp::Ordering::Equal)
+ })
+ .map(|(n, _)| (n.id, n.frame))
+}
+
+impl Editor {
+ pub(super) fn draw_pins(&self, painter: &egui::Painter, place: impl Fn(Vec2) -> Pos2) {
+ let frame = self.scene.frame;
+ let mut pins: Vec<&Note> = self.pins.iter().filter(|n| !n.done || n.frame == frame).collect();
+ pins.sort_by_key(|n| n.frame == frame);
+ pins.into_iter().for_each(|n| {
+ let p = place(vec2(n.x, n.y));
+ let here = n.frame == frame;
+ let open = self.note_open == Some(n.id);
+ let fill = match (n.done, here) {
+ (true, _) => Color32::from_rgba_unmultiplied(120, 200, 120, 200),
+ (false, true) => Color32::from_rgb(255, 196, 60),
+ (false, false) => Color32::from_rgba_unmultiplied(255, 196, 60, 90),
+ };
+ if open {
+ painter.circle_stroke(p, PIN + 4.0, egui::Stroke::new(2.5, theme::ACCENT));
+ }
+ painter.circle_filled(p, PIN, fill);
+ painter.circle_stroke(
+ p,
+ PIN,
+ egui::Stroke::new(
+ if open { 2.5 } else { 1.5 },
+ Color32::from_black_alpha(if here { 180 } else { 90 }),
+ ),
+ );
+ let label = if n.done {
+ icon::CHECK.to_string()
+ } else {
+ n.id.to_string()
+ };
+ painter.text(
+ p,
+ egui::Align2::CENTER_CENTER,
+ label,
+ egui::FontId::proportional(12.0),
+ Color32::from_black_alpha(if here { 255 } else { 140 }),
+ );
+ if !here {
+ painter.text(
+ p + vec2(PIN + 3.0, 0.0),
+ egui::Align2::LEFT_CENTER,
+ format!("frame {}", n.frame),
+ egui::FontId::proportional(11.0),
+ Color32::from_black_alpha(150),
+ );
+ }
+ });
+ if let Some(at) = self.note_at {
+ painter.circle_stroke(place(at), PIN, egui::Stroke::new(2.0, Color32::from_rgb(255, 196, 60)));
+ }
+ }
+
+ pub(super) fn press_note(&mut self, at: Vec2) {
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ match hit_pin(&self.pins, self.scene.frame, at, zoom) {
+ Some(id) => self.open_pin(id),
+ None => {
+ self.note_open = None;
+ self.note_at = Some(at);
+ self.note_text.clear();
+ }
+ }
+ }
+
+ pub(super) fn select_pin(&mut self, at: Vec2) -> Result<()> {
+ let zoom = self.view.map_or(1.0, |v| v.zoom);
+ match hit_any_pin(&self.pins, self.scene.frame, at, zoom) {
+ Some((id, frame)) => {
+ self.go_to(frame)?;
+ self.open_pin(id);
+ self.say(Tone::Info, format!("note {id} on frame {frame}: Delete removes it"));
+ }
+ None => {
+ self.note_open = None;
+ self.note_at = None;
+ }
+ }
+ Ok(())
+ }
+
+ pub(super) fn remove_open_pin(&mut self) -> Result<()> {
+ if let Some(id) = self.note_open.take() {
+ notes::remove(&self.scene.bundle, id)?;
+ self.reread_pins();
+ self.say(Tone::Done, format!("note {id} removed"));
+ }
+ Ok(())
+ }
+
+ pub(super) fn open_pin(&mut self, id: u32) {
+ self.note_at = None;
+ self.note_open = Some(id);
+ self.note_edit = self
+ .pins
+ .iter()
+ .find(|n| n.id == id)
+ .map(|n| n.text.clone())
+ .unwrap_or_default();
+ }
+
+ fn reread_pins(&mut self) {
+ self.pins = notes::read(&self.scene.bundle);
+ }
+
+ pub(super) fn pin_popover(&mut self, ctx: &egui::Context) -> Result<()> {
+ let (Some(view), rect) = (self.view, self.canvas_rect) else {
+ return Ok(());
+ };
+ let at = match (self.note_at, self.note_open) {
+ (Some(at), _) => at,
+ (None, Some(id)) => match self.pins.iter().find(|n| n.id == id) {
+ Some(n) => vec2(n.x, n.y),
+ None => {
+ self.note_open = None;
+ return Ok(());
+ }
+ },
+ _ => return Ok(()),
+ };
+ let p = self.screen(view, rect, at);
+ let spot = Rect::from_min_size(p + vec2(PIN + 6.0, PIN + 6.0), vec2(0.0, 0.0)).min;
+ let mut result = Ok(());
+ egui::Area::new(egui::Id::unique("pin popover"))
+ .fixed_pos(spot)
+ .order(egui::Order::Foreground)
+ .show(ctx, |ui| {
+ egui::Frame::popup(ui.style()).show(ui, |ui| {
+ ui.set_max_width(300.0);
+ result = match self.note_open {
+ Some(id) => self.open_pin_ui(ui, id),
+ None => self.new_pin_ui(ui, at),
+ };
+ });
+ });
+ result
+ }
+
+ fn new_pin_ui(&mut self, ui: &mut egui::Ui, at: Vec2) -> Result<()> {
+ let label = ui.label(format!(
+ "a note for the agent at {:.0}, {:.0}, frame {}",
+ at.x, at.y, self.scene.frame
+ ));
+ let response = ui
+ .add(egui::TextEdit::multiline(&mut self.note_text).desired_rows(3))
+ .labelled_by(label.id)
+ .hint("what the agent should know or do here");
+ if self.note_text.is_empty() && !response.has_focus() {
+ response.request_focus();
+ }
+ let mut pin = false;
+ let mut cancel = false;
+ ui.horizontal(|ui| {
+ pin = ui
+ .add_enabled(!self.note_text.trim().is_empty(), egui::Button::new("pin it"))
+ .hint("save the note where you clicked; the agent reads it with klad notes")
+ .clicked();
+ cancel = ui.button("cancel").hint("drop this note").clicked();
+ });
+ if pin {
+ notes::add(
+ &self.scene.bundle,
+ (at.x, at.y),
+ self.scene.frame,
+ &self.note_text,
+ "user",
+ )?;
+ self.note_at = None;
+ self.note_text.clear();
+ self.reread_pins();
+ self.say(Tone::Done, "note pinned: the agent reads it with klad notes");
+ }
+ if cancel {
+ self.note_at = None;
+ }
+ Ok(())
+ }
+
+ fn open_pin_ui(&mut self, ui: &mut egui::Ui, id: u32) -> Result<()> {
+ let Some(note) = self.pins.iter().find(|n| n.id == id).cloned() else {
+ self.note_open = None;
+ return Ok(());
+ };
+ let label = ui.label(format!(
+ "note {} on frame {}, by {}{}",
+ note.id,
+ note.frame,
+ note.author,
+ if note.done { ", done" } else { "" }
+ ));
+ ui.add(egui::TextEdit::multiline(&mut self.note_edit).desired_rows(3))
+ .labelled_by(label.id)
+ .hint("edit the note; save keeps it");
+ let mut done = note.done;
+ let (mut save, mut remove, mut close) = (false, false, false);
+ ui.horizontal(|ui| {
+ save = ui
+ .add_enabled(
+ self.note_edit.trim() != note.text && !self.note_edit.trim().is_empty(),
+ egui::Button::new("save"),
+ )
+ .hint("keep the edited text")
+ .clicked();
+ ui.checkbox(&mut done, "done")
+ .hint("done: the agent has acted on it (it marks this itself with klad notes --done)");
+ remove = ui.button("remove").hint("delete this note").clicked();
+ close = ui.button("close").hint("close this note").clicked();
+ });
+ if save {
+ notes::set_text(&self.scene.bundle, id, &self.note_edit)?;
+ }
+ if done != note.done {
+ notes::set_done(&self.scene.bundle, id, done)?;
+ }
+ if remove {
+ self.remove_open_pin()?;
+ return Ok(());
+ }
+ if close {
+ self.note_open = None;
+ }
+ if save || remove || done != note.done {
+ self.reread_pins();
+ }
+ Ok(())
+ }
+
+ pub(super) fn notes_pane(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let open: Vec<Note> = self.pins.iter().filter(|n| !n.done).cloned().collect();
+ let done: Vec<Note> = self.pins.iter().filter(|n| n.done).cloned().collect();
+ if open.is_empty() {
+ ui.label(RichText::new("no open notes: N, then click the canvas to pin one").color(theme::WEAK));
+ }
+ let mut go: Option<(u32, u32)> = None;
+ let mut reopen = None;
+ open.iter().for_each(|n| {
+ if ui
+ .add(egui::Button::new(format!("{}. frame {}: {}", n.id, n.frame, n.text)).truncate())
+ .hint("go to its frame and open it")
+ .clicked()
+ {
+ go = Some((n.frame, n.id));
+ }
+ });
+ if !done.is_empty() {
+ ui.collapsing(format!("done ({})", done.len()), |ui| {
+ done.iter().for_each(|n| {
+ ui.horizontal(|ui| {
+ if ui
+ .add(
+ egui::Button::new(
+ RichText::new(format!("{} {}. frame {}: {}", icon::CHECK, n.id, n.frame, n.text))
+ .color(theme::WEAK),
+ )
+ .truncate(),
+ )
+ .hint("go to its frame and open it")
+ .clicked()
+ {
+ go = Some((n.frame, n.id));
+ }
+ if ui
+ .button("open again")
+ .hint("the agent should look at it again")
+ .clicked()
+ {
+ reopen = Some(n.id);
+ }
+ });
+ });
+ });
+ }
+ if let Some(id) = reopen {
+ notes::set_done(&self.scene.bundle, id, false)?;
+ self.reread_pins();
+ }
+ if let Some((frame, id)) = go {
+ self.go_to(frame)?;
+ self.open_pin(id);
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn note(id: u32, x: f32, y: f32, frame: u32) -> Note {
+ Note {
+ id,
+ x,
+ y,
+ frame,
+ text: format!("note {id}"),
+ author: "user".into(),
+ at_ms: 0,
+ done: false,
+ }
+ }
+
+ #[test]
+ fn a_press_opens_the_nearest_pin_of_its_frame_within_reach() {
+ let pins = vec![
+ note(1, 100.0, 100.0, 0),
+ note(2, 108.0, 100.0, 0),
+ note(3, 100.0, 100.0, 4),
+ ];
+ assert_eq!(hit_pin(&pins, 0, vec2(106.0, 101.0), 1.0), Some(2));
+ assert_eq!(hit_pin(&pins, 0, vec2(98.0, 100.0), 1.0), Some(1));
+ assert_eq!(hit_pin(&pins, 0, vec2(130.0, 100.0), 1.0), None);
+ assert_eq!(hit_pin(&pins, 0, vec2(130.0, 100.0), 0.5), Some(2));
+ assert_eq!(hit_pin(&pins, 4, vec2(101.0, 100.0), 1.0), Some(3));
+ assert_eq!(hit_pin(&pins, 2, vec2(101.0, 100.0), 1.0), None);
+ assert_eq!(hit_any_pin(&pins, 2, vec2(101.0, 100.0), 1.0), Some((1, 0)));
+ assert_eq!(hit_any_pin(&pins, 4, vec2(101.0, 100.0), 1.0), Some((3, 4)));
+ assert_eq!(hit_any_pin(&pins, 0, vec2(130.0, 100.0), 1.0), None);
+ }
+}
diff --git a/crates/app/src/editor/prefs.rs b/crates/app/src/editor/prefs.rs
new file mode 100644
index 0000000..0888d24
--- /dev/null
+++ b/crates/app/src/editor/prefs.rs
@@ -0,0 +1,213 @@
+use super::Editor;
+use crate::commands::Cmd;
+use crate::messages::Tone;
+use crate::theme::{self, Hint};
+use egui::{RichText, vec2};
+
+impl Editor {
+ pub(super) fn defaults_section(&mut self, ui: &mut egui::Ui) {
+ let mut changed = false;
+ let d = &mut self.settings.defaults;
+ ui.horizontal_wrapped(|ui| {
+ let now = match (&d.brush, d.size) {
+ (Some(b), Some(s)) => format!("new windows start with {b} at {s:.1} px"),
+ _ => "new windows start with the ink brush at 12 px".to_string(),
+ };
+ ui.label(now);
+ });
+ let (brush, size) = (self.brush.clone(), self.size);
+ ui.horizontal_wrapped(|ui| {
+ if ui
+ .button("use the current brush and size")
+ .hint("the brush and size you have now become the ones every window starts with")
+ .clicked()
+ {
+ d.brush = Some(brush.clone());
+ d.size = Some(size);
+ changed = true;
+ }
+ if ui
+ .add_enabled(d.brush.is_some(), egui::Button::new("forget them"))
+ .hint("start with the ink brush at 12 px again")
+ .clicked()
+ {
+ d.brush = None;
+ d.size = None;
+ changed = true;
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("shift K exposes on");
+ [1, 2, 3].into_iter().for_each(|n| {
+ if ui
+ .selectable_value(&mut d.exposure, n, format!("{n}s"))
+ .hint("how many frames each new drawing holds when shift K makes it")
+ .clicked()
+ {
+ changed = true;
+ }
+ });
+ });
+ ui.horizontal(|ui| {
+ ui.label("onion before");
+ changed |= ui
+ .add(egui::DragValue::new(&mut d.onion_before).range(0..=8))
+ .hint("drawings shown before, in red, when onion skin is on")
+ .changed();
+ ui.label("after");
+ changed |= ui
+ .add(egui::DragValue::new(&mut d.onion_after).range(0..=8))
+ .hint("drawings shown after, in green")
+ .changed();
+ ui.label("opacity");
+ changed |= ui
+ .add(egui::DragValue::new(&mut d.onion_opacity).range(0.05..=1.0).speed(0.01))
+ .hint("how strong the nearest ghost is")
+ .changed();
+ });
+ ui.horizontal(|ui| {
+ ui.label("around the canvas");
+ changed |= ui
+ .color_edit_button_srgb(&mut d.surround)
+ .hint("the grey around the canvas; neutral keeps colours true")
+ .changed();
+ if ui.button("neutral grey").hint("back to the neutral grey").clicked() {
+ d.surround = theme::SURROUND;
+ changed = true;
+ }
+ });
+ if changed {
+ self.settings_dirty = true;
+ self.use_defaults();
+ }
+ }
+
+ pub(super) fn scale_section(&mut self, ui: &mut egui::Ui) {
+ ui.horizontal(|ui| {
+ let label = ui.label("UI scale");
+ let mut scale = self.settings.ui_scale;
+ let r = ui
+ .add(egui::Slider::new(&mut scale, 0.75..=2.0).step_by(0.05))
+ .labelled_by(label.id)
+ .hint("bigger targets for a pen on a big tablet; everything but the canvas grows");
+ if r.drag_stopped() || (r.changed() && !r.dragged()) {
+ self.settings.ui_scale = scale;
+ self.settings_dirty = true;
+ }
+ });
+ }
+
+ pub(super) fn keys_section(&mut self, ui: &mut egui::Ui) {
+ ui.horizontal(|ui| {
+ let label = ui.label("find");
+ ui.add(egui::TextEdit::singleline(&mut self.key_filter).desired_width(180.0))
+ .labelled_by(label.id)
+ .hint("type part of a command's name or key");
+ if ui
+ .button("reset every key")
+ .hint("every command back to its first key")
+ .clicked()
+ {
+ self.bindings.reset_all();
+ self.settings.keys = self.bindings.to_settings();
+ self.settings_dirty = true;
+ self.say(Tone::Done, "every key is back to its first one");
+ }
+ });
+ if let Some(cmd) = self.capturing {
+ ui.label(
+ RichText::new(format!(
+ "press the new key for {} (Esc keeps the old one)",
+ cmd.spec().name
+ ))
+ .color(theme::ACCENT),
+ );
+ }
+ let filter = self.key_filter.trim().to_lowercase();
+ let shown: Vec<Cmd> = Cmd::ALL
+ .into_iter()
+ .filter(|c| {
+ filter.is_empty()
+ || c.spec().name.contains(filter.as_str())
+ || self.bindings.label(*c).to_lowercase().contains(filter.as_str())
+ })
+ .collect();
+ let mut action: Option<(Cmd, &str)> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("keys list")
+ .max_height(320.0)
+ .show(ui, |ui| {
+ shown.iter().for_each(|cmd| {
+ let spec = cmd.spec();
+ ui.horizontal(|ui| {
+ let key = self.bindings.label(*cmd);
+ let key = if key.is_empty() { "no key".to_string() } else { key };
+ [(spec.name.to_string(), 220.0, theme::TEXT), (key, 110.0, theme::WEAK)]
+ .into_iter()
+ .for_each(|(text, width, colour)| {
+ ui.allocate_ui_with_layout(
+ vec2(width, theme::TARGET),
+ egui::Layout::left_to_right(egui::Align::Center),
+ |ui| {
+ ui.set_min_width(width);
+ ui.add(egui::Label::new(RichText::new(text).color(colour)).truncate());
+ },
+ );
+ });
+ if spec.is_hold() {
+ return;
+ }
+ if ui
+ .button("change")
+ .hint(format!("press a new key for {}", spec.name))
+ .clicked()
+ {
+ action = Some((*cmd, "change"));
+ }
+ if ui
+ .add_enabled(!self.bindings.keys(*cmd).is_empty(), egui::Button::new("no key"))
+ .hint("take its key away; it stays in the palette and on its button")
+ .clicked()
+ {
+ action = Some((*cmd, "clear"));
+ }
+ if ui
+ .add_enabled(!self.bindings.is_default(*cmd), egui::Button::new("reset"))
+ .hint("its first key again")
+ .clicked()
+ {
+ action = Some((*cmd, "reset"));
+ }
+ });
+ });
+ });
+ match action {
+ Some((cmd, "change")) => self.capturing = Some(cmd),
+ Some((cmd, "clear")) => {
+ self.bindings.clear(cmd);
+ self.settings.keys = self.bindings.to_settings();
+ self.settings_dirty = true;
+ }
+ Some((cmd, _)) => {
+ let before = self.bindings.clone();
+ self.bindings.reset(cmd);
+ let first = self.bindings.keys(cmd);
+ let clash = first.iter().find_map(|k| self.bindings.taken_by(*k, cmd));
+ match clash {
+ Some(other) => {
+ self.bindings = before;
+ self.say(
+ Tone::Refused,
+ format!("its first key now runs {}; change that one first", other.spec().name),
+ );
+ }
+ None => {
+ self.settings.keys = self.bindings.to_settings();
+ self.settings_dirty = true;
+ }
+ }
+ }
+ None => {}
+ }
+ }
+}
diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rs
new file mode 100644
index 0000000..bc8a292
--- /dev/null
+++ b/crates/app/src/editor/selection.rs
@@ -0,0 +1,365 @@
+use super::{Editor, Tool};
+use crate::commands::Cmd;
+use crate::messages::Tone;
+use crate::pen::PenEvent;
+use crate::theme;
+use anyhow::Result;
+use egui::{Id, RichText, vec2};
+use klad_core::doc::Item;
+use klad_core::markedit::{LassoAction, MarkTransform};
+use klad_core::ops::{Op, Place};
+use klad_core::pathedit::PathEdit;
+use serde_json::{Map, Value, json};
+
+#[derive(Default)]
+pub(super) struct Held {
+ events: Vec<PenEvent>,
+}
+
+impl Held {
+ pub fn admit(&mut self, busy: bool, events: Vec<PenEvent>) -> Vec<PenEvent> {
+ match busy {
+ true => {
+ self.events.extend(events);
+ Vec::new()
+ }
+ false => {
+ let mut all = std::mem::take(&mut self.events);
+ all.extend(events);
+ all
+ }
+ }
+ }
+
+ #[cfg(test)]
+ pub fn len(&self) -> usize {
+ self.events.len()
+ }
+}
+
+pub(super) enum Selected {
+ Strokes,
+ Shape(String),
+ Points,
+}
+
+fn strip_ids(value: &mut Value) {
+ if let Value::Object(map) = value {
+ map.remove("id");
+ map.values_mut().for_each(strip_ids);
+ }
+ if let Value::Array(items) = value {
+ items.iter_mut().for_each(strip_ids);
+ }
+}
+
+impl Editor {
+ pub(super) fn selected(&self) -> Option<Selected> {
+ match self.tool {
+ Tool::Strokes => self.picked.as_ref().map(|_| Selected::Strokes),
+ Tool::Direct => self
+ .direct
+ .as_ref()
+ .filter(|d| !d.points.is_empty())
+ .map(|_| Selected::Points),
+ Tool::Select => self
+ .selection
+ .clone()
+ .map(Selected::Shape)
+ .or_else(|| self.picked.as_ref().map(|_| Selected::Strokes)),
+ _ => None,
+ }
+ }
+
+ pub(super) fn writing(&self) -> bool {
+ self.lift.as_ref().is_some_and(|l| l.commit.is_some()) || self.path_commit.is_some()
+ }
+
+ fn middle_of_picked(&self) -> Option<[f32; 2]> {
+ self.picked_corners()
+ .map(|(_, c)| [(c[0].x + c[2].x) / 2.0, (c[0].y + c[2].y) / 2.0])
+ }
+
+ fn set_node(&mut self, id: &str, props: Vec<(&str, Value)>) -> Result<()> {
+ self.apply(vec![Op::Set {
+ id: id.to_string(),
+ props: props
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v))
+ .collect::<Map<String, Value>>(),
+ }])
+ }
+
+ pub(super) fn node_transform(&self, id: &str) -> Option<klad_core::doc::Transform> {
+ match self.scene.bundle.doc.item(id) {
+ Some(Item::Node(_, _, node)) => Some(node.transform),
+ _ => None,
+ }
+ }
+
+ pub(super) fn nudge(&mut self, dx: f32, dy: f32) -> Result<()> {
+ let step = if self.key_shift { 10.0 } else { 1.0 };
+ let (dx, dy) = (dx * step, dy * step);
+ match self.selected() {
+ Some(Selected::Strokes) => self.edit_picked(LassoAction::Transform(MarkTransform {
+ x: dx,
+ y: dy,
+ ..Default::default()
+ })),
+ Some(Selected::Shape(id)) => {
+ let Some(t) = self.node_transform(&id) else {
+ return Ok(());
+ };
+ self.set_node(
+ &id,
+ vec![("transform.x", json!(t.x + dx)), ("transform.y", json!(t.y + dy))],
+ )
+ }
+ Some(Selected::Points) => {
+ let points: Vec<usize> = self
+ .direct
+ .as_ref()
+ .map_or(Vec::new(), |d| d.points.iter().copied().collect());
+ self.commit_path(PathEdit::Move { points, by: [dx, dy] })
+ }
+ None => Ok(()),
+ }
+ }
+
+ pub(super) fn turn(&mut self, degrees: f32) -> Result<()> {
+ match self.selected() {
+ Some(Selected::Strokes) => {
+ let pivot = self.middle_of_picked();
+ self.edit_picked(LassoAction::Transform(MarkTransform {
+ rotate: degrees,
+ pivot,
+ ..Default::default()
+ }))
+ }
+ Some(Selected::Shape(id)) => {
+ let Some(t) = self.node_transform(&id) else {
+ return Ok(());
+ };
+ self.set_node(&id, vec![("transform.rotate", json!(t.rotate + degrees))])
+ }
+ _ => Ok(()),
+ }
+ }
+
+ pub(super) fn flip(&mut self, horizontal: bool) -> Result<()> {
+ match self.selected() {
+ Some(Selected::Strokes) => match horizontal {
+ true => self.flip_picked(-1.0, 1.0),
+ false => self.flip_picked(1.0, -1.0),
+ },
+ Some(Selected::Shape(id)) => {
+ let Some(t) = self.node_transform(&id) else {
+ return Ok(());
+ };
+ let scale = match horizontal {
+ true => ("transform.sx", json!(-t.sx)),
+ false => ("transform.sy", json!(-t.sy)),
+ };
+ self.set_node(&id, vec![scale, ("transform.rotate", json!(-t.rotate))])
+ }
+ _ => Ok(()),
+ }
+ }
+
+ pub(super) fn duplicate_in_place(&mut self) -> Result<()> {
+ match self.selected() {
+ Some(Selected::Strokes) => match self.copied() {
+ Some(copied) => self.paste_copied(copied, "duplicated"),
+ None => Ok(()),
+ },
+ Some(Selected::Shape(id)) => {
+ let Some(Item::Node(_, _, node)) = self.scene.bundle.doc.item(&id) else {
+ return Ok(());
+ };
+ let mut value = serde_json::to_value(node)?;
+ strip_ids(&mut value);
+ let op = Op::AddNode {
+ node: value,
+ place: Place {
+ above: Some(id.clone()),
+ frame: Some(self.scene.frame),
+ ..Place::default()
+ },
+ };
+ let applied = self.scene.apply_with(&[op], &self.brushes);
+ match applied {
+ Ok((dirty, applied)) => {
+ self.dirty.extend(dirty);
+ self.selection = applied.added.first().cloned();
+ self.say(Tone::Done, format!("duplicated {id} in place"));
+ Ok(())
+ }
+ Err(e) => {
+ self.say(Tone::Refused, format!("duplicate: {e:#}"));
+ Ok(())
+ }
+ }
+ }
+ _ => Ok(()),
+ }
+ }
+
+ pub(super) fn selection_bar(&mut self, ctx: &egui::Context) {
+ let Some(selected) = self.selected() else {
+ return;
+ };
+ let Some(view) = self.view else {
+ return;
+ };
+ let rect = self.canvas_rect;
+ let corners = match selected {
+ Selected::Points => None,
+ _ => self.handles().map(|(_, c)| c),
+ };
+ let at = match corners {
+ Some(corners) => {
+ let screen: Vec<egui::Pos2> = corners.iter().map(|c| self.screen(view, rect, *c)).collect();
+ let (lo, hi) = screen
+ .iter()
+ .fold((screen[0], screen[0]), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ match hi.y + 30.0 + 40.0 < rect.bottom() {
+ true => egui::pos2((lo.x + hi.x) / 2.0, hi.y + 30.0),
+ false => egui::pos2((lo.x + hi.x) / 2.0, lo.y - 72.0),
+ }
+ }
+ None => egui::pos2(rect.center().x, rect.bottom() - 60.0),
+ };
+ let at = egui::pos2(
+ at.x.clamp(rect.left() + 8.0, rect.right() - 8.0),
+ at.y.max(rect.top() + 8.0),
+ );
+ let commands: Vec<Cmd> = match selected {
+ Selected::Strokes => vec![
+ Cmd::FlipH,
+ Cmd::FlipV,
+ Cmd::TurnLeft90,
+ Cmd::TurnRight90,
+ Cmd::Recolour,
+ Cmd::Thinner,
+ Cmd::Thicker,
+ Cmd::Copy,
+ Cmd::Paste,
+ Cmd::DuplicateInPlace,
+ Cmd::Delete,
+ Cmd::Deselect,
+ ],
+ Selected::Shape(_) => vec![
+ Cmd::FlipH,
+ Cmd::FlipV,
+ Cmd::TurnLeft90,
+ Cmd::TurnRight90,
+ Cmd::DuplicateInPlace,
+ Cmd::Delete,
+ Cmd::Deselect,
+ ],
+ Selected::Points => vec![
+ Cmd::Corner,
+ Cmd::Smooth,
+ Cmd::NudgeLeft,
+ Cmd::NudgeRight,
+ Cmd::NudgeUp,
+ Cmd::NudgeDown,
+ Cmd::Delete,
+ Cmd::Deselect,
+ ],
+ };
+ let writing = self.writing();
+ egui::Area::new(Id::unique("selection bar"))
+ .order(egui::Order::Foreground)
+ .pivot(egui::Align2::CENTER_TOP)
+ .fixed_pos(at)
+ .constrain(true)
+ .show(ctx, |ui| {
+ egui::Frame::popup(ui.style()).show(ui, |ui| {
+ ui.horizontal(|ui| {
+ commands.iter().for_each(|cmd| {
+ if *cmd == Cmd::Recolour {
+ let swatch = crate::color::color32(self.color);
+ let r = self.command_button(ui, *cmd, None);
+ ui.painter().rect_filled(
+ egui::Rect::from_min_size(r.rect.right_bottom() - vec2(9.0, 9.0), vec2(7.0, 7.0)),
+ 1.0,
+ swatch,
+ );
+ } else {
+ self.command_button(ui, *cmd, None);
+ }
+ });
+ if let Some((_, chosen)) = self.chosen_marks().filter(|_| self.on_marks()) {
+ let opacity = chosen.first().map_or(1.0, |(_, m)| match m {
+ klad_core::stroke::Mark::Stroke(s) => s.opacity,
+ klad_core::stroke::Mark::Fill(f) => f.opacity,
+ });
+ if let Some(v) = self.number(
+ ui,
+ "bar.opacity",
+ "",
+ opacity,
+ 0.0..=1.0,
+ 0.01,
+ "the opacity of every selected stroke and fill",
+ ) {
+ let sets = chosen
+ .iter()
+ .map(|(cel, m)| (cel.clone(), m.id(), "opacity", json!(v)))
+ .collect();
+ self.check(|e| e.set_picked(sets));
+ }
+ }
+ if writing {
+ ui.label(RichText::new("writing...").color(theme::WEAK));
+ }
+ });
+ });
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::pen::Phase;
+ use std::time::Instant;
+
+ fn event(phase: Phase, x: f32) -> PenEvent {
+ PenEvent {
+ phase,
+ pos: egui::pos2(x, 10.0),
+ pressure: 1.0,
+ tilt: (0.0, 0.0),
+ eraser: false,
+ tablet: false,
+ device: 0,
+ at: Instant::now(),
+ }
+ }
+
+ #[test]
+ fn a_press_while_an_edit_is_written_waits_for_it_in_order() {
+ let mut held = Held::default();
+ let first = vec![event(Phase::Down, 1.0), event(Phase::Move, 2.0)];
+ assert!(held.admit(true, first).is_empty());
+ assert!(held.admit(true, vec![event(Phase::Up, 3.0)]).is_empty());
+ assert_eq!(held.len(), 3);
+ let out = held.admit(false, vec![event(Phase::Down, 4.0)]);
+ let xs: Vec<f32> = out.iter().map(|e| e.pos.x).collect();
+ assert_eq!(xs, [1.0, 2.0, 3.0, 4.0]);
+ assert_eq!(held.len(), 0);
+ assert_eq!(held.admit(false, vec![event(Phase::Move, 5.0)]).len(), 1);
+ }
+
+ #[test]
+ fn duplicated_shapes_lose_their_ids_everywhere() {
+ let mut v = json!({"id": "n5", "type": "group", "children": [{"id": "n6", "type": "rect"}], "fill": {"linear": {"stops": []}}});
+ strip_ids(&mut v);
+ assert_eq!(
+ v,
+ json!({"type": "group", "children": [{"type": "rect"}], "fill": {"linear": {"stops": []}}})
+ );
+ }
+}
diff --git a/crates/app/src/editor/timeline.rs b/crates/app/src/editor/timeline.rs
new file mode 100644
index 0000000..5a767bf
--- /dev/null
+++ b/crates/app/src/editor/timeline.rs
@@ -0,0 +1,1753 @@
+use super::clips::{self, Hit, Strip};
+use super::layers::{self, LayerRow};
+use super::tweens::{self, Span};
+use super::{Editor, ms};
+use crate::commands::Cmd;
+use crate::composite::CanvasDone;
+use crate::frames::Player;
+use crate::messages::Tone;
+use crate::theme::{self, Hint, icon};
+use anyhow::Result;
+use egui::{Align2, Color32, FontId, Key, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2};
+use klad_core::doc::{Cel, Kind, Layer, Loc, MASK};
+use klad_core::ops::{Op, Place};
+use klad_core::timing::{CelAction, CelSpec, FrameSpec, OPEN, ends};
+use klad_render::onion::By;
+use serde_json::{Map, json};
+use std::collections::BTreeSet;
+use std::sync::mpsc::{Receiver, RecvTimeoutError, TryRecvError, channel};
+use std::time::{Duration, Instant};
+
+const ROW: f32 = crate::theme::ROW;
+const RULER: f32 = 18.0;
+const NAMES: f32 = 236.0;
+const EDGE: f32 = 8.0;
+const PAST: f32 = 14.0;
+const GRIP: f32 = 7.0;
+const SETTLE: Duration = Duration::from_millis(150);
+const FLIP_PX: f32 = 22.0;
+const AHEAD: u32 = 4;
+const PEN_WAIT: Duration = Duration::from_millis(60);
+pub(super) const OPEN_WAIT: Duration = Duration::from_millis(400);
+pub(super) const FILL: usize = 64;
+
+pub(super) struct CanvasWait {
+ asked: u64,
+ frame: u32,
+ active: Vec<usize>,
+ rev: u64,
+ rx: Receiver<Result<CanvasDone>>,
+ since: Instant,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+enum Drag {
+ Scrub,
+ Range {
+ from: u32,
+ to: u32,
+ },
+ Hold {
+ layer: String,
+ cel: String,
+ start: u32,
+ end: u32,
+ open: bool,
+ to: u32,
+ },
+ Move {
+ cel: String,
+ from: u32,
+ to: u32,
+ },
+ NewClip {
+ from: u32,
+ to: u32,
+ },
+ Select {
+ from: u32,
+ to: u32,
+ first: usize,
+ last: usize,
+ },
+ ClipEnd {
+ index: usize,
+ name: String,
+ first: bool,
+ from: u32,
+ to: u32,
+ },
+}
+
+pub(super) struct Flip {
+ origin: u32,
+ x: f32,
+}
+
+pub(super) struct Timeline {
+ cell: f32,
+ drag: Option<Drag>,
+ pub folded: BTreeSet<String>,
+ pub masks: BTreeSet<String>,
+ fps: u32,
+ length: u32,
+ pub range: Option<(u32, u32)>,
+ pub on: u32,
+ pub player: Option<Player>,
+ pub playing: String,
+ moved_at: Instant,
+ step_start: Option<Instant>,
+ pub canvas_frame: Option<u32>,
+ pub on_screen: Option<u32>,
+ shown_key: Option<u64>,
+ flip: Option<Flip>,
+ pub roll: Option<u32>,
+ direction: i32,
+ cache_rev: u64,
+ pub clip: Option<String>,
+ pub clip_name: (String, String),
+ pub clip_fps: u32,
+ pub godot: (String, String),
+ pub span: Option<Span>,
+ pub ask: tweens::Ask,
+ pub cells: Option<Vec<super::cells::CellCopy>>,
+ pub geom: Option<Geom>,
+}
+
+impl Default for Timeline {
+ fn default() -> Self {
+ Self {
+ cell: 18.0,
+ drag: None,
+ folded: BTreeSet::new(),
+ masks: BTreeSet::new(),
+ fps: 0,
+ length: 0,
+ range: None,
+ on: 2,
+ player: None,
+ playing: String::new(),
+ moved_at: Instant::now(),
+ step_start: None,
+ canvas_frame: None,
+ on_screen: None,
+ shown_key: None,
+ flip: None,
+ roll: None,
+ direction: 0,
+ cache_rev: u64::MAX,
+ clip: None,
+ clip_name: (String::new(), String::new()),
+ clip_fps: 0,
+ godot: (String::new(), String::new()),
+ span: None,
+ ask: tweens::Ask::default(),
+ cells: None,
+ geom: None,
+ }
+ }
+}
+
+fn span_of(
+ rows: &[LayerRow],
+ (from, to): (u32, u32),
+ (first, last): (usize, usize),
+ anchor: (u32, usize),
+) -> Option<Span> {
+ let (a, b) = (first.min(last), first.max(last));
+ let ids: Vec<String> = rows[a..=b.min(rows.len().saturating_sub(1))]
+ .iter()
+ .filter(|r| matches!(r.kind, Kind::Paint | Kind::Vector))
+ .map(|r| r.id.clone())
+ .collect();
+ (!ids.is_empty()).then(|| Span {
+ from: from.min(to),
+ to: from.max(to),
+ rows: ids,
+ anchor,
+ })
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct Block {
+ cel: String,
+ link: Option<String>,
+ start: u32,
+ end: u32,
+ open: bool,
+ tween: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(super) struct Geom {
+ left: f32,
+ top: f32,
+ cell: f32,
+ frames: u32,
+ rows: usize,
+}
+
+impl Geom {
+ fn x_of(&self, f: u32) -> f32 {
+ self.left + f as f32 * self.cell
+ }
+
+ pub(super) fn cell_centre(&self, f: u32, row: usize) -> Pos2 {
+ pos2(
+ self.x_of(f) + self.cell / 2.0,
+ self.top + RULER + ROW * (row as f32 + 0.5),
+ )
+ }
+
+ fn frame_at(&self, x: f32) -> u32 {
+ (((x - self.left) / self.cell).floor().max(0.0) as u32).min(self.frames.saturating_sub(1))
+ }
+
+ fn row_at(&self, y: f32) -> Option<usize> {
+ (y >= self.top + RULER)
+ .then(|| ((y - self.top - RULER) / ROW).floor() as usize)
+ .filter(|r| *r < self.rows)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+enum Press {
+ Ruler(u32),
+ End(usize, Block),
+ Start(usize, Block),
+ Cell(usize, u32),
+}
+
+fn press_at(g: &Geom, blocks: &[Vec<Block>], p: Pos2) -> Option<Press> {
+ if p.y < g.top {
+ return None;
+ }
+ let f = g.frame_at(p.x);
+ let Some(r) = g.row_at(p.y) else {
+ return Some(Press::Ruler(f));
+ };
+ let list = blocks.get(r)?;
+ if let Some(b) = list
+ .iter()
+ .find(|b| (p.x - g.x_of(b.end)).abs() <= EDGE && p.x > g.x_of(b.start) + g.cell / 2.0)
+ {
+ return Some(Press::End(r, b.clone()));
+ }
+ match list.iter().find(|b| b.start <= f && f < b.end) {
+ Some(b) if b.start == f && g.cell_centre(f, r).distance(p) <= GRIP => Some(Press::Start(r, b.clone())),
+ _ => Some(Press::Cell(r, f)),
+ }
+}
+
+fn drag_of(press: &Press, shift: bool, layer: impl Fn(usize) -> String) -> Drag {
+ match press {
+ Press::Ruler(f) if shift => Drag::Range { from: *f, to: *f },
+ Press::Ruler(_) => Drag::Scrub,
+ Press::End(r, b) => Drag::Hold {
+ layer: layer(*r),
+ cel: b.cel.clone(),
+ start: b.start,
+ end: b.end,
+ open: b.open,
+ to: b.end,
+ },
+ Press::Start(_, b) => Drag::Move {
+ cel: b.cel.clone(),
+ from: b.start,
+ to: b.start,
+ },
+ Press::Cell(r, f) => Drag::Select {
+ from: *f,
+ to: *f,
+ first: *r,
+ last: *r,
+ },
+ }
+}
+
+fn blocks(layer: &Layer, frames: u32) -> Vec<Block> {
+ let cels = layer.cels();
+ cels.iter()
+ .zip(ends(cels))
+ .filter(|(c, _)| c.frame < frames)
+ .map(|(c, end)| Block {
+ cel: c.id.clone(),
+ link: c.link.clone(),
+ start: c.frame,
+ end: end.min(frames),
+ open: end == OPEN,
+ tween: c.tween.is_some(),
+ })
+ .collect()
+}
+
+fn exposed(layer: &Layer, frame: u32) -> Option<(Cel, u32)> {
+ let cels = layer.cels();
+ cels.iter()
+ .zip(ends(cels))
+ .find(|(c, e)| c.frame <= frame && frame < *e)
+ .map(|(c, e)| (c.clone(), e))
+}
+
+impl Editor {
+ pub(super) fn busy(&self) -> bool {
+ self.live.is_some()
+ || self.drag.is_some()
+ || self.point_drag.is_some()
+ || self.path_commit.is_some()
+ || self.lift.as_ref().is_some_and(|l| l.commit.is_some())
+ }
+
+ pub(crate) fn canvas_current(&self) -> bool {
+ self.timeline.canvas_frame == Some(self.scene.frame) && !self.scene.stale
+ }
+
+ pub(super) fn cacheable(&self) -> bool {
+ !(self.scene.active_is_mask() && self.scene.tint_mask)
+ }
+
+ pub(super) fn go_to(&mut self, frame: u32) -> Result<()> {
+ if self.timeline.player.is_some() {
+ self.stop_playback();
+ }
+ let last = self.scene.bundle.doc.timeline.frames - 1;
+ let frame = frame.min(last);
+ if self.busy() || frame == self.scene.frame {
+ return Ok(());
+ }
+ self.timeline.direction = if frame > self.scene.frame { 1 } else { -1 };
+ self.scene.move_to(frame);
+ let now = Instant::now();
+ self.timeline.moved_at = now;
+ self.timeline.step_start = Some(now);
+ self.selection = None;
+ self.picked = None;
+ self.direct = None;
+ self.cut_view = None;
+ self.lasso = None;
+ self.drop_lift();
+ Ok(())
+ }
+
+ pub(super) fn invalidate_canvas(&mut self) {
+ self.canvas_gen += 1;
+ self.scene.stale = true;
+ }
+
+ pub(super) fn canvas_loading(&self) -> bool {
+ self.canvas_wait.as_ref().is_some_and(|w| w.frame == self.scene.frame) && !self.canvas_current()
+ }
+
+ fn canvas_wanted(&self, wait: &CanvasWait) -> bool {
+ wait.asked == self.canvas_gen
+ && wait.frame == self.scene.frame
+ && wait.active == self.scene.active
+ && wait.rev == self.scene.bundle.doc.rev
+ }
+
+ pub(super) fn request_canvas(&mut self) {
+ if self.canvas_wait.is_some() {
+ return;
+ }
+ let mut request = self.scene.canvas_request(&self.brushes);
+ if self.cacheable() {
+ let (frame, onion) = (self.scene.frame, self.scene.onion_on);
+ let key = self.frames.key(&mut self.scene, frame, onion, &self.brushes);
+ request = request.with_picture(
+ key,
+ self.frames.level,
+ self.scene.pictures(),
+ self.buffering.writes.clone(),
+ );
+ }
+ let (tx, rx) = channel();
+ let ctx = self.ctx.clone();
+ std::thread::spawn(move || {
+ let _ = tx.send(crate::background().install(|| request.run()));
+ ctx.request_repaint();
+ });
+ self.canvas_wait = Some(CanvasWait {
+ asked: self.canvas_gen,
+ frame: self.scene.frame,
+ active: self.scene.active.clone(),
+ rev: self.scene.bundle.doc.rev,
+ rx,
+ since: Instant::now(),
+ });
+ }
+
+ pub(super) fn tend_canvas(&mut self, wait: Duration) -> Result<()> {
+ let Some(pending) = self.canvas_wait.as_ref() else {
+ return Ok(());
+ };
+ let received = match wait.is_zero() {
+ true => pending.rx.try_recv().map_err(|e| e == TryRecvError::Disconnected),
+ false => pending
+ .rx
+ .recv_timeout(wait)
+ .map_err(|e| e == RecvTimeoutError::Disconnected),
+ };
+ let result = match received {
+ Ok(result) => result,
+ Err(gone) => {
+ if gone {
+ self.canvas_wait = None;
+ }
+ return Ok(());
+ }
+ };
+ let Some(pending) = self.canvas_wait.take() else {
+ return Ok(());
+ };
+ let mut done = match result {
+ Ok(done) => done,
+ Err(e) => {
+ self.error(format!("loading frame {}: {e:#}", pending.frame));
+ return Ok(());
+ }
+ };
+ let wanted = self.canvas_wanted(&pending);
+ let (frame, loaded) = (done.frame, done.loaded);
+ self.frames.heavy |= done.bytes > crate::frames::HEAVY;
+ self.scene.lean = self.frames.heavy;
+ let thumbs = std::mem::take(&mut done.thumbs);
+ if self.scene.adopt(done, wanted) {
+ self.keep_thumbs(thumbs);
+ self.dirty.extend(self.scene.all_tiles());
+ self.timeline.canvas_frame = Some(self.scene.frame);
+ self.measure(
+ "canvas",
+ format!(
+ "frame {frame} ready to draw on {:.0} ms after it was asked for ({loaded} drawings loaded for it, {} strokes and fills in memory)",
+ ms(pending.since),
+ self.scene.total_marks()
+ ),
+ );
+ }
+ Ok(())
+ }
+
+ fn catch_up(&mut self, wait: Duration) -> Result<bool> {
+ if self.canvas_current() {
+ return Ok(true);
+ }
+ if !self.scene.stale && self.scene.has_frame(self.scene.frame) {
+ self.dirty.extend(self.scene.all_tiles());
+ self.timeline.canvas_frame = Some(self.scene.frame);
+ return Ok(true);
+ }
+ self.request_canvas();
+ self.tend_canvas(wait)?;
+ if !self.canvas_current() && self.canvas_wait.is_none() {
+ self.request_canvas();
+ self.tend_canvas(wait)?;
+ }
+ Ok(self.canvas_current())
+ }
+
+ pub(super) fn hold_still(&mut self) {
+ if self.timeline.player.is_some() {
+ self.stop_playback();
+ }
+ self.timeline.roll = None;
+ }
+
+ pub(super) fn ensure_canvas(&mut self) -> Result<bool> {
+ self.hold_still();
+ if !self.canvas_current() {
+ if !self.catch_up(PEN_WAIT)? {
+ return Ok(false);
+ }
+ self.timeline.on_screen = Some(self.scene.frame);
+ }
+ Ok(true)
+ }
+
+ fn shown(&mut self, frame: u32, cached: bool) {
+ self.timeline.on_screen = Some(frame);
+ if frame != self.scene.frame {
+ return;
+ }
+ if let Some(start) = self.timeline.step_start.take() {
+ let took = ms(start);
+ crate::stats::lock(&self.stats).step_ms.push(took as f32);
+ let text = format!(
+ "frame {frame} shown in {took:.1} ms {}, {} MB of drawings and {} MB of frames ({}) in memory",
+ if cached { "from the frame cache" } else { "composed" },
+ self.scene.cache_bytes() >> 20,
+ self.frames.bytes() >> 20,
+ self.frames.len()
+ );
+ self.measure("frame step", text);
+ }
+ }
+
+ fn forget_old_frames(&mut self) {
+ if self.frames.is_empty() {
+ return;
+ }
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let onion = self.scene.onion_on;
+ let live: BTreeSet<u64> = (0..frames)
+ .flat_map(|f| [false, onion].into_iter().map(move |o| (f, o)))
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .map(|(f, o)| self.frames.key(&mut self.scene, f, o, &self.brushes))
+ .collect();
+ self.frames.forget_unused(&live);
+ }
+
+ pub(super) fn frames_changed(&mut self) {
+ self.frames.changed();
+ self.forget_old_frames();
+ }
+
+ pub(super) fn tend_frames(&mut self) -> Result<Option<u64>> {
+ self.tend_canvas(Duration::ZERO)?;
+ let now = Instant::now();
+ let rev = self.scene.bundle.doc.rev;
+ if rev != self.timeline.cache_rev {
+ self.timeline.cache_rev = rev;
+ self.frames_changed();
+ }
+ if self.timeline.player.as_ref().is_some_and(|p| p.finished(now)) {
+ self.stop_playback();
+ }
+ self.frames.collect(&mut self.scene);
+ self.scene.lean = self.frames.heavy;
+ if let Some(e) = self.frames.error.take() {
+ self.error(e);
+ }
+ let show = match self.timeline.player.is_some() {
+ true => self.tend_playback(now),
+ false => self.tend_still(now)?,
+ };
+ let keep: BTreeSet<u64> = show.into_iter().collect();
+ self.frames.prune(&keep);
+ Ok(show)
+ }
+
+ fn tend_still(&mut self, now: Instant) -> Result<Option<u64>> {
+ let onion = self.scene.onion_on;
+ let target = self.timeline.roll.unwrap_or(self.scene.frame);
+ let cacheable = self.cacheable();
+ let key = cacheable.then(|| self.frames.key(&mut self.scene, target, onion, &self.brushes));
+ let cached = key.filter(|k| self.frames.has(*k));
+ let rolling = self.timeline.roll.is_some();
+ if !rolling && !self.canvas_current() {
+ let settled = now.duration_since(self.timeline.moved_at) >= SETTLE && self.timeline.flip.is_none();
+ let loaded = self.scene.has_frame(self.scene.frame);
+ let heavy = self.frames.heavy;
+ if (loaded && (cached.is_none() || settled)) || !cacheable || (heavy && settled) {
+ self.catch_up(Duration::ZERO)?;
+ }
+ if cached.is_some() && !self.canvas_current() {
+ self.ctx.request_repaint_after(SETTLE);
+ }
+ }
+ if !rolling && self.canvas_current() {
+ let filling = self.dirty.len() > FILL && self.live.is_none();
+ if let Some(key) = self.timeline.shown_key.filter(|k| filling && self.frames.has(*k)) {
+ self.frames.touch(key);
+ self.ctx.request_repaint();
+ return Ok(Some(key));
+ }
+ self.timeline.shown_key = None;
+ self.shown(self.scene.frame, false);
+ self.prefetch(onion);
+ return Ok(None);
+ }
+ if let Some(key) = cached {
+ self.frames.touch(key);
+ self.timeline.shown_key = Some(key);
+ self.shown(target, true);
+ self.prefetch(onion);
+ return Ok(Some(key));
+ }
+ let seen = key.is_some_and(|k| self.frames.on_disk(k));
+ let loading_here = !seen && (self.frames.heavy || self.canvas_wait.as_ref().is_some_and(|w| w.frame == target));
+ if !loading_here {
+ self.frames.request(&mut self.scene, target, onion, &self.brushes, true);
+ }
+ Ok(self.timeline.shown_key.filter(|k| self.frames.has(*k)))
+ }
+
+ fn prefetch(&mut self, onion: bool) {
+ let direction = self.timeline.direction;
+ if direction == 0 || self.busy() || !self.cacheable() {
+ return;
+ }
+ let last = self.scene.bundle.doc.timeline.frames as i64 - 1;
+ let from = self.scene.frame as i64;
+ (1..=AHEAD as i64)
+ .map(|k| from + k * direction as i64)
+ .filter(|f| (0..=last).contains(f))
+ .filter(|f| {
+ !self.frames.heavy || {
+ let key = self.frames.key(&mut self.scene, *f as u32, onion, &self.brushes);
+ self.frames.on_disk(key)
+ }
+ })
+ .collect::<Vec<_>>()
+ .into_iter()
+ .try_for_each(|f| {
+ match self
+ .frames
+ .request(&mut self.scene, f as u32, onion, &self.brushes, false)
+ {
+ true => Some(()),
+ false => None,
+ }
+ });
+ }
+
+ fn tend_playback(&mut self, now: Instant) -> Option<u64> {
+ let player = self.timeline.player.as_mut()?;
+ let (frames, scene, brushes) = (&mut self.frames, &mut self.scene, &self.brushes);
+ player.tick(now, |f| {
+ let key = frames.key(scene, f, false, brushes);
+ frames.has(key)
+ });
+ let length = (player.to - player.from + 1) as usize;
+ player
+ .ahead(now, length)
+ .into_iter()
+ .try_for_each(|f| match frames.request(scene, f, false, brushes, false) {
+ true => Some(()),
+ false => None,
+ });
+ let wait = player.next_in(now);
+ let shown = player.shown();
+ self.ctx.request_repaint_after(wait);
+ let key = shown.map(|f| frames.key(scene, f, false, brushes));
+ if let Some(f) = shown {
+ self.timeline.on_screen = Some(f);
+ }
+ key.filter(|k| self.frames.has(*k))
+ }
+
+ pub(super) fn play(&mut self) -> Result<()> {
+ if self.timeline.player.is_some() {
+ self.stop_playback();
+ return Ok(());
+ }
+ if self.busy() {
+ return Ok(());
+ }
+ let t = &self.scene.bundle.doc.timeline;
+ let span = clips::play_span(t, self.scene.frame, self.timeline.range, self.timeline.clip.as_deref());
+ self.timeline.roll = None;
+ self.timeline.flip = None;
+ self.timeline.player = Some(Player::new(
+ Instant::now(),
+ self.scene.frame,
+ (span.from, span.to),
+ span.fps,
+ span.once,
+ ));
+ self.timeline.playing = format!(
+ "{} at {} fps{}",
+ span.what,
+ span.fps,
+ if span.once { ", once" } else { "" }
+ );
+ Ok(())
+ }
+
+ pub(super) fn stop_playback(&mut self) {
+ let Some(player) = self.timeline.player.take() else {
+ return;
+ };
+ let played = format!("played {}: {}", self.timeline.playing, player.summary());
+ self.measure("last play", played.clone());
+ self.say(Tone::Done, played);
+ if let Some(frame) = player.shown() {
+ if frame != self.scene.frame {
+ self.scene.move_to(frame);
+ self.timeline.direction = 0;
+ }
+ self.timeline.shown_key = Some(self.frames.key(&mut self.scene, frame, false, &self.brushes));
+ }
+ self.timeline.moved_at = Instant::now();
+ }
+
+ pub(super) fn shown_frame(&self) -> u32 {
+ match (&self.timeline.player, self.timeline.roll) {
+ (Some(p), _) => p.shown().unwrap_or(self.scene.frame),
+ (None, Some(roll)) => roll,
+ _ => self.scene.frame,
+ }
+ }
+
+ pub(super) fn waiting(&self) -> bool {
+ self.timeline.on_screen != Some(self.scene.frame)
+ }
+
+ pub(super) fn toggle_onion(&mut self) -> Result<()> {
+ self.scene.onion_on = !self.scene.onion_on;
+ self.onion_changed()
+ }
+
+ pub(super) fn onion_changed(&mut self) -> Result<()> {
+ self.scene.onion.wrap = self.timeline.range;
+ self.invalidate_canvas();
+ self.frames_changed();
+ Ok(())
+ }
+
+ pub(super) fn previous_drawing(&self) -> Option<u32> {
+ let layer = self.scene.active_layer()?;
+ let frame = self.scene.frame;
+ let start = layer.cel_at(frame).map_or(frame, |c| c.frame);
+ let starts: Vec<u32> = layer.cels().iter().map(|c| c.frame).collect();
+ let earlier = starts.iter().rev().find(|f| **f < start).copied();
+ match self.timeline.range {
+ Some((a, b)) if (a..=b).contains(&frame) && earlier.is_none_or(|f| f < a) => starts
+ .iter()
+ .rev()
+ .find(|f| **f > start && **f <= b)
+ .copied()
+ .or(earlier),
+ _ => earlier,
+ }
+ }
+
+ pub(super) fn flip_and_roll(&mut self, ui: &egui::Ui) -> Result<()> {
+ let (q, w) = ui.input(|i| (i.key_down(Key::Q), i.key_down(Key::W)));
+ let x = ui.input(|i| i.pointer.latest_pos()).map(|p| p.x);
+ match (q, self.timeline.flip.as_ref(), x) {
+ (true, None, Some(x)) if !self.busy() => {
+ if self.timeline.player.is_some() {
+ self.stop_playback();
+ }
+ self.timeline.flip = Some(Flip {
+ origin: self.scene.frame,
+ x,
+ });
+ }
+ (true, Some(flip), Some(x)) => {
+ let last = self.scene.bundle.doc.timeline.frames as i64 - 1;
+ let offset = ((x - flip.x) / FLIP_PX).round() as i64;
+ let frame = (flip.origin as i64 + offset).clamp(0, last) as u32;
+ if frame != self.scene.frame {
+ self.go_to(frame)?;
+ }
+ }
+ (false, Some(_), _) => {
+ self.timeline.flip = None;
+ self.timeline.moved_at = Instant::now();
+ }
+ _ => {}
+ }
+ self.timeline.roll = match w && self.timeline.player.is_none() && !self.busy() {
+ true => self.timeline.roll.or_else(|| self.previous_drawing()),
+ false => None,
+ };
+ Ok(())
+ }
+
+ pub(super) fn holding_frame_keys(&self) -> bool {
+ self.timeline.flip.is_some() || self.timeline.roll.is_some()
+ }
+
+ fn active_layer_id(&self) -> Option<String> {
+ self.scene.active_id()
+ }
+
+ pub(super) fn here(&self) -> Option<(String, Option<(Cel, u32)>)> {
+ let layer = self.scene.active_layer()?;
+ if !matches!(layer.kind(), Kind::Paint | Kind::Vector) {
+ return None;
+ }
+ Some((layer.id.clone(), exposed(layer, self.scene.frame)))
+ }
+
+ pub(super) fn drawing_starts(&self) -> Vec<u32> {
+ self.scene
+ .active_layer()
+ .map(|l| l.cels().iter().map(|c| c.frame).collect())
+ .unwrap_or_default()
+ }
+
+ pub(super) fn next_drawing(&mut self) -> Result<()> {
+ let Some(layer) = self
+ .scene
+ .active_layer()
+ .filter(|l| matches!(l.kind(), Kind::Paint | Kind::Vector))
+ .cloned()
+ else {
+ return Ok(());
+ };
+ let on = self.timeline.on.max(1);
+ let frame = self.scene.frame;
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let mut ops = Vec::new();
+ let at = match exposed(&layer, frame) {
+ None => frame,
+ Some((cel, end)) if end == OPEN => {
+ let at = cel.frame + on * (frame + 1 - cel.frame).div_ceil(on);
+ ops.push(Op::Set {
+ id: cel.id.clone(),
+ props: Map::from_iter([("hold".to_string(), json!(at - cel.frame))]),
+ });
+ at
+ }
+ Some((_, end)) => end,
+ };
+ let taken = layer.cels().iter().any(|c| c.frame == at);
+ ops.push(Op::Cel(CelSpec {
+ action: CelAction::New {
+ layer: layer.id.clone(),
+ },
+ id: None,
+ frame: Some(at),
+ hold: Some(on),
+ insert: taken,
+ }));
+ if at + on > frames.max(at + 1) && !taken {
+ ops.push(Op::Timeline {
+ fps: None,
+ frames: Some(at + on),
+ origin: None,
+ });
+ }
+ if self.timeline_apply(ops)?.is_some() {
+ self.go_to(at)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn timeline_apply(&mut self, ops: Vec<Op>) -> Result<Option<klad_core::ops::Applied>> {
+ if ops.is_empty() {
+ return Ok(None);
+ }
+ let start = Instant::now();
+ match self.scene.apply_with(&ops, &self.brushes) {
+ Ok((dirty, applied)) => {
+ self.dirty.extend(dirty);
+ self.forget_missing_selection();
+ let text = format!("{} in {:.0} ms", klad_core::bundle::summarize(&ops), ms(start));
+ self.measure("timeline edit", text.clone());
+ self.say(Tone::Info, text);
+ Ok(Some(applied))
+ }
+ Err(e) => {
+ self.say(Tone::Refused, format!("{e:#}"));
+ Ok(None)
+ }
+ }
+ }
+
+ fn cel_op(&mut self, action: CelAction, frame: Option<u32>, insert: bool) -> Result<Option<String>> {
+ let spec = CelSpec {
+ action,
+ id: None,
+ frame,
+ hold: None,
+ insert,
+ };
+ Ok(self
+ .timeline_apply(vec![Op::Cel(spec)])?
+ .and_then(|a| a.added.first().cloned()))
+ }
+
+ pub(super) fn new_drawing(&mut self) -> Result<()> {
+ let Some((layer, _)) = self.here() else {
+ return Ok(());
+ };
+ self.cel_op(CelAction::New { layer }, Some(self.scene.frame), false)?;
+ Ok(())
+ }
+
+ pub(super) fn duplicate_next(&mut self) -> Result<()> {
+ let Some((_, Some((cel, end)))) = self.here() else {
+ self.say(Tone::Refused, "nothing to duplicate on this frame");
+ return Ok(());
+ };
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let at = if end == OPEN { frames.max(cel.frame + 1) } else { end };
+ if self
+ .cel_op(CelAction::Dup { cel: cel.id }, None, end != OPEN)?
+ .is_some()
+ {
+ self.go_to(at)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn link_here(&mut self, source: String) -> Result<()> {
+ self.cel_op(CelAction::Link { cel: source }, Some(self.scene.frame), false)?;
+ Ok(())
+ }
+
+ pub(super) fn unlink_here(&mut self) -> Result<()> {
+ if let Some((_, Some((cel, _)))) = self
+ .here()
+ .filter(|(_, c)| c.as_ref().is_some_and(|(c, _)| c.link.is_some()))
+ {
+ self.cel_op(CelAction::Unlink { cel: cel.id }, None, false)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn delete_here(&mut self) -> Result<()> {
+ if let Some((_, Some((cel, _)))) = self.here() {
+ self.timeline_apply(vec![Op::Remove { ids: vec![cel.id] }])?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn frames_at(&mut self, insert: bool, every_layer: bool) -> Result<()> {
+ let Some(layer) = self.active_layer_id() else {
+ return Ok(());
+ };
+ if !insert && self.scene.bundle.doc.timeline.frames == 1 {
+ return Ok(());
+ }
+ let spec = FrameSpec {
+ insert,
+ at: self.scene.frame,
+ count: 1,
+ layers: (!every_layer).then(|| vec![layer]),
+ };
+ self.timeline_apply(vec![Op::Frames(spec)])?;
+ Ok(())
+ }
+
+ pub(super) fn resize(
+ &mut self,
+ layer: &str,
+ cel: &str,
+ (start, end, open): (u32, u32, bool),
+ to: u32,
+ ) -> Result<()> {
+ let to = to.max(start + 1);
+ let op = match to.cmp(&end) {
+ std::cmp::Ordering::Equal => return Ok(()),
+ std::cmp::Ordering::Greater => Op::Frames(FrameSpec {
+ insert: true,
+ at: end - 1,
+ count: to - end,
+ layers: Some(vec![layer.to_string()]),
+ }),
+ std::cmp::Ordering::Less if open => Op::Set {
+ id: cel.to_string(),
+ props: Map::from_iter([("hold".to_string(), json!(to - start))]),
+ },
+ std::cmp::Ordering::Less => Op::Frames(FrameSpec {
+ insert: false,
+ at: to,
+ count: end - to,
+ layers: Some(vec![layer.to_string()]),
+ }),
+ };
+ self.timeline_apply(vec![op])?;
+ Ok(())
+ }
+
+ pub(super) fn hold(&mut self, delta: i32) -> Result<()> {
+ let Some((layer, Some((cel, end)))) = self.here() else {
+ return Ok(());
+ };
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let (open, end) = (end == OPEN, end.min(frames));
+ if delta < 0 && end - cel.frame <= 1 {
+ self.say(
+ Tone::Refused,
+ format!("{} already shows for one frame; delete it instead", cel.id),
+ );
+ return Ok(());
+ }
+ let to = (end as i64 + delta as i64).max(cel.frame as i64 + 1) as u32;
+ self.resize(&layer, &cel.id, (cel.frame, end, open), to)
+ }
+
+ pub(super) fn add_layer(&mut self, kind: &str) -> Result<()> {
+ let frame = self.scene.frame;
+ self.add_layer_value(json!({"kind": kind, "cels": [{"frame": frame}]}))
+ }
+
+ pub(super) fn add_layer_value(&mut self, layer: serde_json::Value) -> Result<()> {
+ let above = self.scene.active.clone();
+ let owner = match above.last() {
+ Some(&MASK) => above[..above.len() - 1].to_vec(),
+ _ => above,
+ };
+ let place = match self.scene.bundle.doc.locate_path(&owner) {
+ Some(layer) => Place {
+ above: Some(layer.id.clone()),
+ ..Place::default()
+ },
+ None => Place::default(),
+ };
+ let Some(applied) = self.timeline_apply(vec![Op::AddLayer { layer, place }])? else {
+ return Ok(());
+ };
+ if let Some(Loc::Layer(path)) = applied.added.first().and_then(|id| self.scene.bundle.doc.locate(id)) {
+ self.activate(path)?;
+ }
+ Ok(())
+ }
+
+ fn timeline_rows(&self) -> Vec<LayerRow> {
+ self.layer_rows(layers::Where::Timeline)
+ }
+
+ fn timeline_header(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let t = self.scene.bundle.doc.timeline.clone();
+ if !ui.memory(|m| m.focused().is_some()) {
+ self.timeline.fps = t.fps;
+ self.timeline.length = t.frames;
+ }
+ let mut ops = Vec::new();
+ let mut range = self.timeline.range;
+ let mut go = None;
+ let folded = self.settings.layout.timeline_folded;
+ ui.horizontal_wrapped(|ui| {
+ let caret = if folded { icon::FOLDED } else { icon::OPEN };
+ if ui
+ .add(
+ egui::Button::new(RichText::new(caret).size(theme::ICON))
+ .min_size(vec2(theme::TARGET, theme::TARGET)),
+ )
+ .hint("fold the timeline to this row, or open it again")
+ .clicked()
+ {
+ self.settings.layout.timeline_folded = !folded;
+ self.settings_dirty = true;
+ }
+ let shown = self.shown_frame();
+ let mut typed = shown;
+ let label = ui.label(RichText::new("frame").strong());
+ let field = ui
+ .add(egui::DragValue::new(&mut typed).range(0..=t.frames - 1))
+ .labelled_by(label.id)
+ .hint("the frame on screen; drag, or double-click and type a frame to go there");
+ if typed != shown && (field.lost_focus() || field.dragged() || field.changed()) {
+ go = Some(typed);
+ }
+ ui.label(RichText::new(format!("of {}", t.frames)).color(theme::WEAK));
+ if self.timeline.player.is_none() && ((self.frames.jobs() > 0 && self.waiting()) || self.canvas_loading()) {
+ ui.label(RichText::new("loading").color(theme::WEAK));
+ }
+ [
+ Cmd::FirstFrame,
+ Cmd::PrevDrawing,
+ Cmd::PrevFrame,
+ Cmd::Play,
+ Cmd::NextFrame,
+ Cmd::NextDrawing,
+ Cmd::LastFrame,
+ ]
+ .into_iter()
+ .for_each(|cmd| {
+ self.command_button(ui, cmd, None);
+ });
+ ui.separator();
+ self.command_button(ui, Cmd::LoopRange, None);
+ if let Some((a, b)) = range.as_mut() {
+ ui.add(egui::DragValue::new(a).range(0..=t.frames - 1))
+ .hint("the loop range's first frame");
+ ui.label("to");
+ ui.add(egui::DragValue::new(b).range(0..=t.frames - 1))
+ .hint("the loop range's last frame");
+ *b = (*b).max(*a);
+ }
+ self.command_button(ui, Cmd::Prepare, None);
+ if let Some(text) = self.preparing_text() {
+ ui.label(RichText::new(text).color(theme::WEAK));
+ }
+ ui.separator();
+ self.command_button(ui, Cmd::Onion, None);
+ self.command_button(ui, Cmd::OnionSettings, None);
+ ui.separator();
+ ui.label("shift K on");
+ [
+ (Cmd::ExposeOnes, "1s"),
+ (Cmd::ExposeTwos, "2s"),
+ (Cmd::ExposeThrees, "3s"),
+ ]
+ .into_iter()
+ .for_each(|(cmd, label)| {
+ self.command_button(ui, cmd, Some(label));
+ });
+ ui.separator();
+ ui.label("fps");
+ let fps = ui
+ .add(egui::DragValue::new(&mut self.timeline.fps).range(1..=240))
+ .hint("frames per second of the document; drag, or double-click and type");
+ ui.label("length");
+ let length = ui
+ .add(egui::DragValue::new(&mut self.timeline.length).range(1..=100_000))
+ .hint("the timeline's length in frames");
+ let done = |r: &egui::Response| r.drag_stopped() || r.lost_focus();
+ if (done(&fps) || done(&length)) && (self.timeline.fps != t.fps || self.timeline.length != t.frames) {
+ ops.push(Op::Timeline {
+ fps: (self.timeline.fps != t.fps).then_some(self.timeline.fps),
+ frames: (self.timeline.length != t.frames).then_some(self.timeline.length),
+ origin: None,
+ });
+ }
+ ui.label("zoom");
+ ui.add(egui::Slider::new(&mut self.timeline.cell, 8.0..=40.0).show_value(false))
+ .hint("the width of a frame in the timeline");
+ });
+ self.timeline_apply(ops)?;
+ if let Some(frame) = go {
+ self.go_to(frame)?;
+ }
+ if range != self.timeline.range {
+ self.timeline.range = range;
+ self.onion_changed()?;
+ }
+ if folded {
+ return Ok(());
+ }
+ self.selection_toolbar(ui)?;
+ Ok(())
+ }
+
+ pub(super) fn onion_settings(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let mut onion = self.scene.onion.clone();
+ let mut on = self.scene.onion_on;
+ ui.checkbox(&mut on, "onion skin (O)")
+ .hint("see the drawings before (red) and after (green) under the active layer");
+ ui.horizontal(|ui| {
+ ui.label("before");
+ ui.add(egui::DragValue::new(&mut onion.before).range(0..=12))
+ .hint("how many drawings or frames before this one");
+ ui.label("after");
+ ui.add(egui::DragValue::new(&mut onion.after).range(0..=12))
+ .hint("how many drawings or frames after this one");
+ });
+ ui.horizontal(|ui| {
+ ui.label("count");
+ ui.selectable_value(&mut onion.by, By::Drawings, "drawings")
+ .hint("count drawings: each one once, at its nearest distance");
+ ui.selectable_value(&mut onion.by, By::Frames, "frames")
+ .hint("count frames: on twos the nearest drawing is two frames off and fainter");
+ });
+ ui.add(egui::Slider::new(&mut onion.opacity, 0.05..=1.0).text("opacity"))
+ .hint("the nearest ghost's opacity");
+ ui.add(egui::Slider::new(&mut onion.falloff, 0.1..=1.0).text("falloff"))
+ .hint("each step further keeps this much of the opacity");
+ ui.checkbox(&mut onion.tint, "tint: red before, green after")
+ .hint("off: the ghosts keep their own colours");
+ ui.small("The dot at the right of a layer's name in the timeline shows that layer's onion too.");
+ if onion != self.scene.onion || on != self.scene.onion_on {
+ self.scene.onion = onion;
+ self.scene.onion_on = on;
+ self.onion_changed()?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn draws_into(&self) -> String {
+ let frame = self.scene.frame;
+ let frames = self.scene.bundle.doc.timeline.frames;
+ let Some(layer) = self.scene.active_layer() else {
+ return "no active layer".into();
+ };
+ let name = &layer.name;
+ if layer.kind() == Kind::Group {
+ return format!("{name} is a group: pick a paint layer to draw");
+ }
+ if layer.kind() == Kind::Adjust {
+ return format!("{name} is an adjustment layer: it changes what is under it; pick a paint layer to draw");
+ }
+ let span = |start: u32, end: u32| match end.min(frames) - start {
+ 1 => format!("frame {start}"),
+ _ => format!("frames {start} to {}", end.min(frames) - 1),
+ };
+ match exposed(layer, frame) {
+ None => format!("{name}: frame {frame} is empty, a stroke starts a drawing"),
+ Some((cel, _)) if cel.link.is_some() => {
+ let source = cel.link.clone().unwrap_or_default();
+ format!(
+ "draws into {source} on {name} through the link {} (it changes wherever {source} shows)",
+ cel.id
+ )
+ }
+ Some((cel, end)) => format!("draws into {} on {name}, {}", cel.id, span(cel.frame, end)),
+ }
+ }
+
+ fn names(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ let band = clips::band_height(&self.scene.bundle.doc.timeline.clips);
+ let (strip, _) = ui.allocate_exact_size(vec2(NAMES, band), Sense::hover());
+ ui.painter().text(
+ pos2(strip.left() + 4.0, strip.top() + clips::LANE / 2.0),
+ Align2::LEFT_CENTER,
+ "clips",
+ FontId::proportional(11.0),
+ Color32::GRAY,
+ );
+ let (rect, _) = ui.allocate_exact_size(vec2(NAMES, RULER), Sense::hover());
+ ui.painter().text(
+ rect.left_center() + vec2(4.0, 0.0),
+ Align2::LEFT_CENTER,
+ "layers",
+ FontId::proportional(11.0),
+ Color32::GRAY,
+ );
+ let rows = self.layer_rows(layers::Where::Timeline);
+ let mut placed = Vec::new();
+ let mut responses = Vec::new();
+ rows.into_iter().for_each(|row| {
+ let (rect, _) = ui.allocate_exact_size(vec2(NAMES, ROW), Sense::hover());
+ responses.push(self.layer_row(ui, &row, layers::Where::Timeline, rect));
+ placed.push((rect, row));
+ });
+ self.layer_drags(ui, layers::Where::Timeline, &placed, &responses);
+ Ok(())
+ }
+
+ fn grid(&mut self, ui: &mut egui::Ui, rows: &[LayerRow]) -> Result<()> {
+ let doc = &self.scene.bundle.doc;
+ let frames = doc.timeline.frames;
+ let cw = self.timeline.cell;
+ let clip_list = doc.timeline.clips.clone();
+ let band = clips::band_height(&clip_list);
+ let size = vec2(frames as f32 * cw + PAST, band + RULER + rows.len() as f32 * ROW);
+ let (rect, response) = ui.allocate_exact_size(size, Sense::CLICK | Sense::DRAG);
+ let painter = ui.painter_at(rect);
+ let top = rect.top() + band;
+ painter.rect_filled(rect, 0.0, Color32::from_gray(26));
+ painter.rect_filled(
+ Rect::from_min_max(pos2(rect.left() + frames as f32 * cw, top), rect.max),
+ 0.0,
+ Color32::from_gray(18),
+ );
+ let strip = Strip {
+ rect: Rect::from_min_max(rect.min, pos2(rect.right(), top)),
+ cell: cw,
+ lanes: clips::lanes(&clip_list),
+ };
+ let dragged_span: Vec<(usize, u32, u32)> = match &self.timeline.drag {
+ Some(Drag::ClipEnd { index, from, to, .. }) => vec![(*index, *from, *to)],
+ _ => Vec::new(),
+ };
+ strip.paint(
+ &painter,
+ &clip_list,
+ doc.timeline.fps,
+ self.timeline.clip.as_deref(),
+ &dragged_span,
+ );
+ if let Some(Drag::NewClip { from, to }) = &self.timeline.drag {
+ strip.outline(&painter, *from, *to);
+ }
+ let x_of = |f: u32| rect.left() + f as f32 * cw;
+ let row_rect =
+ |i: usize| Rect::from_min_size(pos2(rect.left(), top + RULER + i as f32 * ROW), vec2(rect.width(), ROW));
+ let shown = self.shown_frame();
+ let step = if cw >= 14.0 { 1 } else { 5 };
+ (0..frames).for_each(|f| {
+ let x = x_of(f);
+ let strong = f % 5 == 0;
+ painter.line_segment(
+ [pos2(x, top + RULER), pos2(x, rect.bottom())],
+ Stroke::new(1.0, Color32::from_gray(if strong { 52 } else { 38 })),
+ );
+ if f % step == 0 {
+ painter.text(
+ pos2(x + cw / 2.0, top + RULER / 2.0),
+ Align2::CENTER_CENTER,
+ f.to_string(),
+ FontId::monospace(if cw >= 18.0 { 10.0 } else { 9.0 }),
+ if strong { Color32::LIGHT_GRAY } else { Color32::GRAY },
+ );
+ }
+ });
+ let ready = &self.buffering.shown;
+ (0..frames).for_each(|f| {
+ let at = |y: f32, h: f32| Rect::from_min_size(pos2(x_of(f), top + y), vec2(cw, h));
+ if ready.watch.contains(&f) {
+ painter.rect_filled(at(1.0, 3.0), 0.0, Color32::from_rgb(90, 200, 110));
+ }
+ if ready.draw.contains(&f) {
+ painter.rect_filled(at(4.0, 2.0), 0.0, Color32::from_rgb(90, 160, 230));
+ }
+ });
+ if response.hover_pos().is_some_and(|p| p.y >= top && p.y < top + 7.0) {
+ response.clone().on_hover_text_at_pointer(
+ "green: the frame's picture is buffered, it shows at once; blue: its drawings are cached, so drawing there starts within seconds. The lightning (prepare frames) fills both",
+ );
+ }
+ let band = match &self.timeline.drag {
+ Some(Drag::Range { from, to }) => Some(((*from).min(*to), (*from).max(*to))),
+ _ => self.timeline.range,
+ };
+ if let Some((a, b)) = band {
+ painter.rect_filled(
+ Rect::from_min_max(pos2(x_of(a), top), pos2(x_of(b + 1), top + RULER)),
+ 0.0,
+ Color32::from_rgba_unmultiplied(255, 170, 60, 70),
+ );
+ painter.line_segment(
+ [pos2(x_of(a), top + RULER - 1.0), pos2(x_of(b + 1), top + RULER - 1.0)],
+ Stroke::new(2.0, Color32::from_rgb(255, 170, 60)),
+ );
+ }
+ rows.iter().enumerate().for_each(|(i, row)| {
+ let r = row_rect(i);
+ if self.scene.active == row.path {
+ painter.rect_filled(r, 0.0, Color32::from_gray(36));
+ }
+ painter.line_segment(
+ [r.left_bottom(), r.right_bottom()],
+ Stroke::new(1.0, Color32::from_gray(40)),
+ );
+ let Some(layer) = doc.locate_path(&row.path) else {
+ return;
+ };
+ blocks(layer, frames).iter().for_each(|b| {
+ let end = match &self.timeline.drag {
+ Some(Drag::Hold { cel, to, .. }) if *cel == b.cel => *to,
+ _ => b.end,
+ };
+ let fill = match (&b.link, layer.kind()) {
+ (Some(_), _) => Color32::from_rgb(112, 92, 146),
+ (None, Kind::Vector) => Color32::from_rgb(78, 124, 96),
+ _ if b.tween => Color32::from_rgb(100, 136, 166),
+ _ => Color32::from_rgb(76, 104, 140),
+ };
+ let label = match &b.link {
+ Some(source) => format!("->{source}"),
+ None if b.tween => format!("{}*", b.cel),
+ None => b.cel.clone(),
+ };
+ let moved_to = match &self.timeline.drag {
+ Some(Drag::Move { cel, from, to }) if *cel == b.cel && from != to => Some(*to),
+ _ => None,
+ };
+ let at = |start: u32, end: u32| {
+ Rect::from_min_max(
+ pos2(x_of(start) + 1.0, r.top() + 3.0),
+ pos2(x_of(end) - 1.0, r.bottom() - 3.0),
+ )
+ };
+ let faded = moved_to.is_some();
+ paint_block(&painter, at(b.start, end), cw, fill, &label, faded);
+ if let Some(to) = moved_to {
+ let ghost = at(to, to + (b.end - b.start));
+ paint_block(&painter, ghost, cw, fill, &label, false);
+ painter.rect_stroke(ghost, 3.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Outside);
+ }
+ });
+ });
+ let selected = match &self.timeline.drag {
+ Some(Drag::Select { from, to, first, last }) => {
+ span_of(rows, (*from, *to), (*first, *last), (*from, *first))
+ }
+ _ => self.timeline.span.clone(),
+ };
+ if let Some(span) = &selected {
+ let found: Vec<usize> = rows
+ .iter()
+ .enumerate()
+ .filter(|(_, r)| span.rows.contains(&r.id))
+ .map(|(i, _)| i)
+ .collect();
+ if let (Some(&a), Some(&b)) = (found.first(), found.last()) {
+ let area = Rect::from_min_max(
+ pos2(x_of(span.from), row_rect(a).top()),
+ pos2(x_of(span.to + 1), row_rect(b).bottom()),
+ );
+ painter.rect_filled(area, 2.0, Color32::from_rgba_unmultiplied(255, 255, 255, 34));
+ painter.rect_stroke(
+ area,
+ 2.0,
+ Stroke::new(1.5, Color32::from_gray(235)),
+ egui::StrokeKind::Inside,
+ );
+ }
+ }
+ painter.rect_filled(
+ Rect::from_min_size(pos2(x_of(shown), rect.top()), vec2(cw, rect.height())),
+ 0.0,
+ Color32::from_rgba_unmultiplied(64, 196, 255, 46),
+ );
+ painter.line_segment(
+ [pos2(x_of(shown), rect.top()), pos2(x_of(shown), rect.bottom())],
+ Stroke::new(1.5, Color32::from_rgb(64, 196, 255)),
+ );
+ let geom = Geom {
+ left: rect.left(),
+ top,
+ cell: cw,
+ frames,
+ rows: rows.len(),
+ };
+ self.timeline.geom = Some(geom);
+ let row_blocks: Vec<Vec<Block>> = rows
+ .iter()
+ .map(|r| doc.locate_path(&r.path).map_or(Vec::new(), |l| blocks(l, frames)))
+ .collect();
+ let at = |p: Pos2| -> (u32, Option<usize>) { (geom.frame_at(p.x), geom.row_at(p.y)) };
+ let pointer = response.interact_pointer_pos().or(response.hover_pos());
+ let press = ui.input(|i| i.pointer.press_origin());
+ let on_edge = |p: Pos2| matches!(press_at(&geom, &row_blocks, p), Some(Press::End(..)));
+ let in_strip = |p: Pos2| p.y < top;
+ let on_clip_end =
+ |p: Pos2| in_strip(p) && matches!(strip.hit(&clip_list, p), Some((_, Hit::First | Hit::Last)));
+ let resizing = matches!(self.timeline.drag, Some(Drag::Hold { .. } | Drag::ClipEnd { .. }));
+ let hover_end = response.hover_pos().is_some_and(|p| on_edge(p) || on_clip_end(p));
+ let hover_dot = response
+ .hover_pos()
+ .is_some_and(|p| matches!(press_at(&geom, &row_blocks, p), Some(Press::Start(..))));
+ if resizing || (self.timeline.drag.is_none() && hover_end) {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
+ } else if matches!(self.timeline.drag, Some(Drag::Move { .. })) {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
+ } else if self.timeline.drag.is_none() && hover_dot {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
+ }
+ let mut pick: Option<(u32, Option<usize>)> = None;
+ let shift = ui.input(|i| i.modifiers.shift);
+ if response.drag_started()
+ && let Some(p) = press.or(pointer)
+ {
+ let (f, row) = at(p);
+ let clip_hit = in_strip(p).then(|| strip.hit(&clip_list, p)).flatten();
+ if let Some((i, _)) = clip_hit {
+ self.timeline.clip = Some(clip_list[i].name.clone());
+ }
+ self.timeline.drag = match press_at(&geom, &row_blocks, p) {
+ _ if in_strip(p) => match clip_hit {
+ Some((i, hit @ (Hit::First | Hit::Last))) => Some(Drag::ClipEnd {
+ index: i,
+ name: clip_list[i].name.clone(),
+ first: hit == Hit::First,
+ from: clip_list[i].from,
+ to: clip_list[i].to,
+ }),
+ Some(_) => Some(Drag::Scrub),
+ None => Some(Drag::NewClip { from: f, to: f }),
+ },
+ Some(press) => Some(drag_of(&press, shift, |r| rows[r].id.clone())),
+ None => None,
+ };
+ if matches!(
+ self.timeline.drag,
+ Some(Drag::Scrub | Drag::Hold { .. } | Drag::Move { .. } | Drag::Select { .. })
+ ) {
+ pick = Some((f, row));
+ }
+ }
+ if response.dragged()
+ && let Some(p) = pointer
+ {
+ let edge = ((p.x - rect.left()) / cw).round().max(0.0) as u32;
+ let (f, under) = at(p);
+ match &mut self.timeline.drag {
+ Some(Drag::Scrub) => self.go_to(f)?,
+ Some(Drag::Select { to, last, .. }) => {
+ *to = f;
+ if let Some(r) = under {
+ *last = r;
+ }
+ }
+ Some(Drag::Range { to, .. }) => *to = f,
+ Some(Drag::Hold { start, to, .. }) => *to = edge.max(*start + 1),
+ Some(Drag::Move { to, .. }) => *to = f,
+ Some(Drag::NewClip { to, .. }) => *to = f,
+ Some(Drag::ClipEnd {
+ first: true, from, to, ..
+ }) => *from = edge.min(*to),
+ Some(Drag::ClipEnd { from, to, .. }) => *to = edge.saturating_sub(1).max(*from).min(frames - 1),
+ None => {}
+ }
+ }
+ if response.drag_stopped() {
+ match self.timeline.drag.take() {
+ Some(Drag::Range { from, to }) => {
+ self.timeline.range = Some((from.min(to), from.max(to)));
+ self.onion_changed()?;
+ }
+ Some(Drag::Hold {
+ layer,
+ cel,
+ start,
+ end,
+ open,
+ to,
+ }) => self.resize(&layer, &cel, (start, end, open), to)?,
+ Some(Drag::Move { cel, from, to }) if from != to => {
+ let op = Op::Cel(CelSpec {
+ action: CelAction::Move { cel },
+ id: None,
+ frame: Some(to),
+ hold: None,
+ insert: false,
+ });
+ if self.timeline_apply(vec![op])?.is_some() {
+ self.go_to(to)?;
+ }
+ }
+ Some(Drag::NewClip { from, to }) => self.add_clip(from, to)?,
+ Some(Drag::Select { from, to, first, last }) => {
+ self.timeline.span = span_of(rows, (from, to), (first, last), (from, first));
+ }
+ Some(Drag::ClipEnd { name, from, to, .. }) => self.reach_clip(&name, from, to)?,
+ _ => {}
+ }
+ }
+ let mut extended = false;
+ if response.clicked()
+ && shift
+ && let Some(p) = pointer
+ && let (f, Some(r)) = at(p)
+ {
+ let anchor = self.timeline.span.as_ref().map_or_else(
+ || {
+ (
+ self.scene.frame,
+ rows.iter().position(|row| row.path == self.scene.active).unwrap_or(r),
+ )
+ },
+ |s| s.anchor,
+ );
+ self.timeline.span = span_of(rows, (anchor.0, f), (anchor.1, r), anchor);
+ extended = true;
+ }
+ if (response.clicked() || response.secondary_clicked())
+ && !extended
+ && let Some(p) = pointer
+ {
+ if in_strip(p) && response.clicked() {
+ self.timeline.clip = strip.hit(&clip_list, p).map(|(i, _)| clip_list[i].name.clone());
+ self.windows.clip = self.timeline.clip.is_some();
+ }
+ if response.clicked() {
+ self.timeline.span = None;
+ }
+ pick = Some(at(p));
+ }
+ if let Some((f, row)) = pick {
+ if let Some(path) = row.map(|r| rows[r].path.clone()).filter(|p| *p != self.scene.active) {
+ let leaf = self
+ .scene
+ .bundle
+ .doc
+ .locate_path(&path)
+ .is_some_and(|l| matches!(l.kind(), Kind::Paint | Kind::Vector));
+ if leaf {
+ self.activate(path)?;
+ }
+ }
+ self.go_to(f)?;
+ }
+ let mut chosen: Option<String> = None;
+ let mut actions: Vec<Cmd> = Vec::new();
+ let drawings: Vec<(String, u32)> = self
+ .scene
+ .active_layer()
+ .map(|l| {
+ l.cels()
+ .iter()
+ .filter(|c| c.link.is_none())
+ .map(|c| (c.id.clone(), c.frame))
+ .collect()
+ })
+ .unwrap_or_default();
+ let span = self.timeline.span.clone();
+ let span_keys = span.as_ref().and_then(|s| tweens::keys(&self.scene.bundle.doc, s));
+ let mut span_choice = None;
+ let ask = &mut self.timeline.ask;
+ response.context_menu(|ui| {
+ [
+ Cmd::NewDrawing,
+ Cmd::Duplicate,
+ Cmd::Unlink,
+ Cmd::DeleteDrawing,
+ Cmd::HoldLonger,
+ Cmd::HoldShorter,
+ Cmd::InsertFrame,
+ Cmd::InsertFrameAll,
+ Cmd::RemoveFrame,
+ Cmd::RemoveFrameAll,
+ Cmd::NewClip,
+ ]
+ .into_iter()
+ .for_each(|cmd| {
+ let spec = cmd.spec();
+ let key = self.bindings.label(cmd);
+ let label = match key.is_empty() {
+ true => format!("{} {}", spec.icon, spec.name),
+ false => format!("{} {} ({key})", spec.icon, spec.name),
+ };
+ if ui.button(label).clicked() {
+ actions.push(cmd);
+ ui.close();
+ }
+ });
+ ui.menu_button("show a drawing here (link)", |ui| {
+ drawings.iter().for_each(|(id, frame)| {
+ if ui.button(format!("{id} (frame {frame})")).clicked() {
+ chosen = Some(id.clone());
+ ui.close();
+ }
+ });
+ });
+ match &span {
+ Some(span) => span_choice = tweens::span_menu(ui, span, span_keys, ask),
+ None => {
+ ui.separator();
+ ui.small(
+ "shift click a cell (or shift drag over cells) to select frames for retiming and in-betweens",
+ );
+ }
+ }
+ });
+ if let Some(choice) = span_choice {
+ self.span_action(choice)?;
+ }
+ self.queued.extend(actions);
+ if let Some(source) = chosen {
+ self.link_here(source)?;
+ }
+ Ok(())
+ }
+
+ pub(super) fn timeline_panel(&mut self, ui: &mut egui::Ui) -> Result<()> {
+ self.tend_buffer();
+ self.timeline_header(ui)?;
+ if self.settings.layout.timeline_folded {
+ return Ok(());
+ }
+ let rows = self.timeline_rows();
+ let mut result = Ok(());
+ egui::ScrollArea::vertical()
+ .id_salt("timeline rows")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
+ ui.vertical(|ui| {
+ if let Err(e) = self.names(ui) {
+ result = Err(e);
+ }
+ });
+ egui::ScrollArea::horizontal()
+ .id_salt("timeline frames")
+ .auto_shrink([false, true])
+ .show(ui, |ui| {
+ if let Err(e) = self.grid(ui, &rows) {
+ result = Err(e);
+ }
+ });
+ });
+ });
+ result
+ }
+}
+
+fn paint_block(painter: &egui::Painter, block: Rect, cw: f32, fill: Color32, label: &str, faded: bool) {
+ let fill = if faded { fill.gamma_multiply(0.35) } else { fill };
+ painter.rect_filled(block, 3.0, fill);
+ let grips = block.width() > 12.0;
+ if grips {
+ [3.0, 6.0].iter().for_each(|dx| {
+ let x = block.right() - dx;
+ painter.line_segment(
+ [pos2(x, block.top() + 3.0), pos2(x, block.bottom() - 3.0)],
+ Stroke::new(1.0, Color32::from_gray(210)),
+ );
+ });
+ }
+ let dot = pos2(block.left() - 1.0 + cw / 2.0, block.center().y);
+ painter.circle_filled(dot, 3.5, if faded { Color32::from_gray(150) } else { Color32::WHITE });
+ if block.width() > cw * 1.5 {
+ let room = Rect::from_min_max(
+ pos2(block.left() - 1.0 + cw, block.top()),
+ pos2(block.right() - if grips { 9.0 } else { 2.0 }, block.bottom()),
+ );
+ painter.with_clip_rect(room.intersect(painter.clip_rect())).text(
+ room.left_center(),
+ Align2::LEFT_CENTER,
+ label,
+ FontId::monospace(10.0),
+ Color32::from_gray(if faded { 140 } else { 230 }),
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn block(cel: &str, start: u32, end: u32) -> Block {
+ Block {
+ cel: cel.into(),
+ link: None,
+ start,
+ end,
+ open: false,
+ tween: false,
+ }
+ }
+
+ #[test]
+ fn a_press_on_the_timeline_starts_the_drag_its_place_asks_for() {
+ let g = Geom {
+ left: 100.0,
+ top: 40.0,
+ cell: 20.0,
+ frames: 24,
+ rows: 2,
+ };
+ let rows = vec![vec![block("c1", 0, 4), block("c2", 4, 6)], vec![block("c9", 2, 3)]];
+ let row0 = 40.0 + RULER + ROW / 2.0;
+ let row1 = row0 + ROW;
+ assert_eq!(press_at(&g, &rows, pos2(130.0, 30.0)), None);
+ assert_eq!(press_at(&g, &rows, pos2(130.0, 45.0)), Some(Press::Ruler(1)));
+ assert_eq!(
+ press_at(&g, &rows, pos2(105.0, row0)),
+ Some(Press::Start(0, rows[0][0].clone()))
+ );
+ assert_eq!(press_at(&g, &rows, pos2(150.0, row0)), Some(Press::Cell(0, 2)));
+ assert_eq!(
+ press_at(&g, &rows, pos2(102.0, row0 - ROW / 2.0 + 2.0)),
+ Some(Press::Cell(0, 0))
+ );
+ assert_eq!(press_at(&g, &rows, pos2(118.0, row0)), Some(Press::Cell(0, 0)));
+ assert_eq!(
+ press_at(&g, &rows, pos2(180.0 - 7.0, row0)),
+ Some(Press::End(0, rows[0][0].clone()))
+ );
+ assert_eq!(
+ press_at(&g, &rows, pos2(180.0 + 7.0, row0)),
+ Some(Press::End(0, rows[0][0].clone()))
+ );
+ assert_eq!(
+ press_at(&g, &rows, pos2(195.0, row0)),
+ Some(Press::Start(0, rows[0][1].clone()))
+ );
+ assert_eq!(press_at(&g, &rows, pos2(400.0, row0)), Some(Press::Cell(0, 15)));
+ assert_eq!(
+ press_at(&g, &rows, pos2(165.0, row1)),
+ Some(Press::End(1, rows[1][0].clone()))
+ );
+ assert_eq!(press_at(&g, &rows, pos2(130.0, row1 + ROW)), Some(Press::Ruler(1)));
+ let origin = pos2(180.0 - 4.0, row0);
+ let moved = origin + vec2(6.0, 0.0);
+ assert!(matches!(press_at(&g, &rows, origin), Some(Press::End(..))));
+ assert!(matches!(press_at(&g, &rows, moved), Some(Press::End(..))));
+ let name = |r: usize| format!("l{r}");
+ assert_eq!(drag_of(&Press::Ruler(3), false, name), Drag::Scrub);
+ assert_eq!(drag_of(&Press::Ruler(3), true, name), Drag::Range { from: 3, to: 3 });
+ assert!(matches!(
+ drag_of(&Press::Cell(1, 5), false, name),
+ Drag::Select { from: 5, first: 1, .. }
+ ));
+ assert!(matches!(drag_of(&Press::Cell(1, 5), true, name), Drag::Select { .. }));
+ assert!(matches!(
+ drag_of(&Press::Start(0, rows[0][1].clone()), false, name),
+ Drag::Move { from: 4, .. }
+ ));
+ assert!(
+ matches!(drag_of(&Press::End(0, rows[0][0].clone()), false, name), Drag::Hold { end: 4, ref layer, .. } if layer == "l0")
+ );
+ }
+}
diff --git a/crates/app/src/editor/tweens.rs b/crates/app/src/editor/tweens.rs
new file mode 100644
index 0000000..e0c33a1
--- /dev/null
+++ b/crates/app/src/editor/tweens.rs
@@ -0,0 +1,194 @@
+use super::Editor;
+use crate::messages::Tone;
+use anyhow::Result;
+use klad_core::doc::{Document, Kind};
+use klad_core::ops::Op;
+use klad_core::retime::{Retime, RetimeSpec};
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Span {
+ pub from: u32,
+ pub to: u32,
+ pub rows: Vec<String>,
+ pub anchor: (u32, usize),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Ask {
+ pub every_frame: bool,
+ pub count: u32,
+ pub spacing: String,
+ pub matching: String,
+ pub every_layer: bool,
+ pub fit: u32,
+ pub unpaired: String,
+}
+
+impl Default for Ask {
+ fn default() -> Self {
+ Self {
+ every_frame: true,
+ count: 1,
+ spacing: "even".into(),
+ matching: "id".into(),
+ every_layer: false,
+ fit: 8,
+ unpaired: "leave".into(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) enum SpanAction {
+ Retime(Retime),
+ Inbetween,
+ Redo,
+ Clear,
+}
+
+pub(super) fn keys(doc: &Document, span: &Span) -> Option<(u32, u32)> {
+ let layer = doc.layer(span.rows.first()?)?;
+ if layer.kind() != Kind::Paint {
+ return None;
+ }
+ layer.content_at(span.from)?;
+ let to = layer
+ .cels()
+ .iter()
+ .filter(|c| c.frame > span.from && c.frame <= span.to)
+ .map(|c| c.frame)
+ .max()?;
+ (to > span.from + 1).then_some((span.from, to))
+}
+
+pub(super) fn span_menu(ui: &mut egui::Ui, span: &Span, keys: Option<(u32, u32)>, ask: &mut Ask) -> Option<SpanAction> {
+ let mut chosen = None;
+ ui.separator();
+ ui.label(format!(
+ "selected: frames {} to {} on {}",
+ span.from,
+ span.to,
+ span.rows.join(", ")
+ ));
+ ui.menu_button("retime the selected frames", |ui| {
+ ui.checkbox(&mut ask.every_layer, "on every layer (later frames and clips move too)");
+ [(1, "on ones"), (2, "on twos"), (3, "on threes")]
+ .iter()
+ .for_each(|(n, label)| {
+ if ui.button(*label).clicked() {
+ chosen = Some(SpanAction::Retime(Retime::On(*n)));
+ ui.close();
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.add(egui::DragValue::new(&mut ask.fit).range(1..=10_000));
+ if ui.button("fit into this many frames").clicked() {
+ chosen = Some(SpanAction::Retime(Retime::Fit(ask.fit)));
+ ui.close();
+ }
+ });
+ if ui.button("reverse").clicked() {
+ chosen = Some(SpanAction::Retime(Retime::Reverse));
+ ui.close();
+ }
+ if ui
+ .button("ping-pong (back again as links, ends not repeated)")
+ .clicked()
+ {
+ chosen = Some(SpanAction::Retime(Retime::Pingpong));
+ ui.close();
+ }
+ });
+ let can = keys.is_some();
+ if ui
+ .add_enabled(can, egui::Button::new("in-between..."))
+ .on_disabled_hover_text("select from one drawing to the frame where another starts, on a paint layer")
+ .clicked()
+ {
+ chosen = Some(SpanAction::Inbetween);
+ ui.close();
+ }
+ if ui
+ .button("redo the in-betweens in the selection (after a key changed)...")
+ .clicked()
+ {
+ chosen = Some(SpanAction::Redo);
+ ui.close();
+ }
+ if ui.button("clear the selection (Esc)").clicked() {
+ chosen = Some(SpanAction::Clear);
+ ui.close();
+ }
+ chosen
+}
+
+impl Editor {
+ pub(super) fn span_action(&mut self, action: SpanAction) -> Result<()> {
+ let Some(span) = self.timeline.span.clone() else {
+ return Ok(());
+ };
+ match action {
+ SpanAction::Clear => self.timeline.span = None,
+ SpanAction::Retime(how) => {
+ let spec = RetimeSpec {
+ from: span.from,
+ to: span.to,
+ action: how,
+ layers: (!self.timeline.ask.every_layer).then(|| span.rows.clone()),
+ };
+ if let Some(applied) = self.timeline_apply(vec![Op::Retime(spec)])? {
+ if let Some(note) = applied.notes.first() {
+ self.say(Tone::Done, note.clone());
+ }
+ self.timeline.span = None;
+ }
+ }
+ SpanAction::Inbetween => {
+ self.windows.between = true;
+ self.between.redo = None;
+ }
+ SpanAction::Redo => self.check_redo()?,
+ }
+ Ok(())
+ }
+}
+
+pub(super) fn summary(stdout: &str) -> String {
+ let keep: Vec<&str> = stdout
+ .lines()
+ .filter(|l| l.contains(" in-between") || l.contains("left out") || l.contains("unpaired"))
+ .map(str::trim)
+ .collect();
+ keep.join("; ")
+}
+
+pub(super) fn failure(stderr: &str) -> String {
+ let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect();
+ lines[lines.len().saturating_sub(3)..].join(" ")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Cel, Layer};
+
+ #[test]
+ fn the_keys_of_a_span_are_its_first_drawing_and_the_last_one_starting_in_it() {
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 12;
+ let mut layer = Layer::paint("l1", "lines", "c1");
+ layer.cels_mut().unwrap().extend([Cel::at("c2", 4), Cel::at("c3", 8)]);
+ doc.layers.push(layer);
+ let span = |from: u32, to: u32| Span {
+ from,
+ to,
+ rows: vec!["l1".into()],
+ anchor: (from, 0),
+ };
+ assert_eq!(keys(&doc, &span(0, 4)), Some((0, 4)));
+ assert_eq!(keys(&doc, &span(0, 9)), Some((0, 8)));
+ assert_eq!(keys(&doc, &span(1, 6)), Some((1, 4)));
+ assert_eq!(keys(&doc, &span(0, 3)), None);
+ assert_eq!(keys(&doc, &span(3, 4)), None);
+ }
+}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
new file mode 100644
index 0000000..e0c9724
--- /dev/null
+++ b/crates/app/src/editor/ui_tests.rs
@@ -0,0 +1,2123 @@
+use super::{Direct, Editor, Picked, Tool};
+use crate::commands::Cmd;
+use crate::layout::{self, Pane};
+use crate::messages::Tone;
+use crate::settings::Settings;
+use crate::theme;
+use egui::accesskit::Role;
+use egui::{Key, Modifiers, Rect, pos2, vec2};
+use egui_kittest::Harness;
+use egui_kittest::kittest::{By, NodeT, Queryable};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Document, Layer};
+use klad_core::ops::parse_lines;
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
+
+const LAYERS: [&str; 7] = ["lines", "colour", "shade", "notes", "rim", "ground", "sky"];
+
+fn sample(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-ui-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(512, 384);
+ doc.timeline.frames = 24;
+ LAYERS.iter().rev().enumerate().for_each(|(i, name)| {
+ doc.layers.push(Layer::paint(&format!("l{i}"), name, &format!("c{i}")));
+ });
+ doc.next_id = 40;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .apply(
+ &parse_lines(
+ r#"{"op":"stroke","layer":"l6","path":"M40 40 L300 200","size":8}
+{"op":"stroke","layer":"l6","path":"M60 300 L400 80","size":5}
+{"op":"add","mask":{"name":"mask"},"in":"l4"}
+{"op":"add","layer":{"kind":"vector","name":"shapes"},"index":0}
+{"op":"clip","add":"walk","from":0,"to":11,"loop":true}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let shapes = bundle.doc.find_layer("shapes").unwrap().id.clone();
+ bundle
+ .apply(
+ &parse_lines(&format!(
+ r##"{{"op":"add","node":{{"type":"rect","x":20,"y":20,"w":120,"h":80,"fill":"#a04030"}},"in":"{shapes}","frame":0}}"##
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ dir
+}
+
+fn editor(path: &Path) -> Editor {
+ let mut editor = Editor::open(egui::Context::default(), path).unwrap();
+ editor.settings = Settings::default();
+ editor.settings_path = None;
+ editor
+}
+
+fn harness(editor: Editor, size: egui::Vec2) -> Harness<'static, Editor> {
+ let mut h = Harness::builder()
+ .with_size(size)
+ .build_ui_state(|ui, editor: &mut Editor| editor.frame(ui), editor);
+ h.run_steps(4);
+ if h.state().scene.bundle.doc.canvas.width <= 1024 {
+ ready(&mut h);
+ }
+ h
+}
+
+fn activate(h: &mut Harness<'static, Editor>, name: &str) {
+ let path = {
+ let ed = h.state();
+ let id = ed.scene.bundle.doc.find_layer(name).unwrap().id.clone();
+ match ed.scene.bundle.doc.locate(&id) {
+ Some(klad_core::doc::Loc::Layer(path)) => path,
+ _ => panic!("no layer {name}"),
+ }
+ };
+ h.state_mut().activate(path).unwrap();
+ h.run_steps(2);
+ ready(h);
+}
+
+fn ready(h: &mut Harness<'static, Editor>) {
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(20) {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ assert!(h.state().canvas_current(), "the canvas never caught up");
+}
+
+const CONTROLS: [Role; 9] = [
+ Role::Button,
+ Role::CheckBox,
+ Role::Slider,
+ Role::SpinButton,
+ Role::TextInput,
+ Role::MultilineTextInput,
+ Role::ComboBox,
+ Role::RadioButton,
+ Role::Switch,
+];
+
+fn controls(h: &Harness<'static, Editor>) -> Vec<(Role, String, Rect)> {
+ h.query_all(By::new().predicate(|n| CONTROLS.contains(&n.role())))
+ .map(|n| {
+ let node = n.accesskit_node();
+ (node.role(), node.label().unwrap_or_default(), n.rect())
+ })
+ .collect()
+}
+
+fn audit(h: &Harness<'static, Editor>, what: &str) -> usize {
+ let hinted = theme::hinted(&h.ctx);
+ let found = controls(h);
+ let small: Vec<String> = found
+ .iter()
+ .filter(|(_, _, r)| r.height() < theme::TARGET - 0.5)
+ .map(|(role, label, r)| format!("{role:?} {label:?} {:.1} high", r.height()))
+ .collect();
+ assert!(
+ small.is_empty(),
+ "{what}: controls under {} pt: {small:#?}",
+ theme::TARGET
+ );
+ let bare: Vec<String> = found
+ .iter()
+ .filter(|(_, _, r)| !hinted.iter().any(|h| h.expand(1.5).contains_rect(*r)))
+ .map(|(role, label, r)| format!("{role:?} {label:?} at {:.0},{:.0}", r.min.x, r.min.y))
+ .collect();
+ assert!(bare.is_empty(), "{what}: controls without a hover hint: {bare:#?}");
+ found.len()
+}
+
+#[test]
+fn every_control_is_pen_sized_and_has_a_hover_hint() {
+ let path = sample("audit");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "lines");
+ let mut checked = 0;
+ [Tool::Brush, Tool::Fill, Tool::Note].iter().for_each(|tool| {
+ h.state_mut().tool = *tool;
+ h.run_steps(2);
+ checked += audit(&h, &format!("{tool:?}"));
+ });
+ h.state_mut().tool = Tool::Strokes;
+ h.state_mut().select_all_strokes();
+ h.run_steps(2);
+ assert!(h.state().picked.is_some());
+ checked += audit(&h, "strokes selected");
+ activate(&mut h, "shade");
+ checked += audit(&h, "a layer with a mask");
+ h.state_mut().invoke(Cmd::PaintMask).unwrap();
+ h.run_steps(2);
+ checked += audit(&h, "painting on a mask");
+ activate(&mut h, "shapes");
+ let rect = {
+ let ed = h.state();
+ let layer = ed.scene.bundle.doc.find_layer("shapes").unwrap();
+ layer.cels()[0].nodes[0].id.clone()
+ };
+ h.state_mut().tool = Tool::Select;
+ h.state_mut().selection = Some(rect.clone());
+ h.run_steps(2);
+ checked += audit(&h, "a shape selected");
+ h.state_mut().tool = Tool::Direct;
+ h.state_mut().direct = Some(Direct {
+ node: rect,
+ points: BTreeSet::from([0, 1]),
+ });
+ h.run_steps(2);
+ checked += audit(&h, "points selected");
+ h.state_mut().settings.layout.numbers = true;
+ h.state_mut().windows.settings = true;
+ h.state_mut().windows.onion = true;
+ h.state_mut().windows.log = true;
+ h.state_mut().windows.brush = true;
+ h.state_mut().say(Tone::Error, "a test error with a close button");
+ h.run_steps(3);
+ checked += audit(&h, "windows open");
+ {
+ let ed = h.state_mut();
+ ed.settings.layout.numbers = false;
+ ed.windows.settings = false;
+ ed.windows.onion = false;
+ ed.windows.log = false;
+ ed.windows.brush = false;
+ }
+ let lines = h.state().scene.bundle.doc.find_layer("lines").unwrap().id.clone();
+ h.state_mut()
+ .apply(parse_lines(&format!(r#"{{"op":"cel","new":"{lines}","frame":6}}"#)).unwrap())
+ .unwrap();
+ {
+ let ed = h.state_mut();
+ ed.timeline.span = Some(super::tweens::Span {
+ from: 0,
+ to: 6,
+ rows: vec![lines.clone()],
+ anchor: (0, 0),
+ });
+ ed.between.last = Some(super::between::Request {
+ layers: vec![lines.clone()],
+ from: 0,
+ to: 6,
+ count: None,
+ spacing: "even".into(),
+ matching: "id".into(),
+ unpaired: "leave".into(),
+ pairs: vec![[1, 2]],
+ });
+ ed.between.report = super::between::report(
+ "lines: c6 -> c40, 1 marks paired (0 flood fills), 2 line ends kept touching\n unpaired, left out: c40:s2 (only in the second key)\n fills left out: c6:s3 at frame 3: it leaked\n c41 at frame 1 (t 0.2) on lines",
+ );
+ ed.between.redo = Some(vec![super::between::RedoRow {
+ cel: "c41".into(),
+ layer: lines.clone(),
+ frame: 1,
+ status: super::between::Status::Drawn(2),
+ }]);
+ ed.windows.between = true;
+ ed.windows.clip = true;
+ }
+ h.run_steps(3);
+ assert!(h.query_all(By::new().label_contains("pick its partner")).count() > 0);
+ checked += audit(&h, "the in-between and clip windows");
+ assert!(checked > 150, "only {checked} controls checked");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn the_shell_fits_a_small_window_without_scrolling() {
+ let path = sample("fits");
+ let mut h = harness(editor(&path), vec2(1280.0, 800.0));
+ activate(&mut h, "lines");
+ let bottom = 800.0 - layout::STATUS + 0.5;
+ [Pane::Tool, Pane::Layers, Pane::Inspector, Pane::Notes, Pane::History]
+ .iter()
+ .for_each(|pane| {
+ let title = h.get_by_label(pane.title());
+ assert!(title.rect().bottom() <= bottom, "{} is below the window", pane.title());
+ });
+ let rows = ["shapes"]
+ .iter()
+ .chain(LAYERS.iter())
+ .filter(|name| {
+ h.query_all_by_label(name)
+ .filter(|n| n.accesskit_node().role() == Role::Button)
+ .any(|n| n.rect().bottom() <= bottom)
+ })
+ .count();
+ assert!(rows >= 6, "only {rows} timeline rows show at the default height");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn the_layout_comes_back_as_it_was_left() {
+ let path = sample("layout");
+ let mut first = editor(&path);
+ first.settings.layout.dock_width = 410.0;
+ first.settings.layout.timeline_height = 300.0;
+ first.settings.layout.toggle(Pane::History);
+ let mut h = harness(first, vec2(1440.0, 900.0));
+ let layout = h.state().settings.layout.clone();
+ assert!((layout.dock_width - 410.0).abs() < 0.5, "{}", layout.dock_width);
+ assert!(
+ (layout.timeline_height - 300.0).abs() < 0.5,
+ "{}",
+ layout.timeline_height
+ );
+ assert!(h.query_by_label(Pane::History.title()).is_none());
+ let mut again = editor(&path);
+ again.settings.layout = layout.clone();
+ let h2 = harness(again, vec2(1440.0, 900.0));
+ assert_eq!(h2.state().settings.layout, layout);
+ h.state_mut().tabs.push(false);
+ h.run_steps(2);
+ assert!(h.state().settings.layout.hidden);
+ assert!(h.query_by_label(Pane::Layers.title()).is_none());
+ h.state_mut().tabs.push(false);
+ h.state_mut().tabs.push(true);
+ h.run_steps(2);
+ assert!(!h.state().settings.layout.hidden && !h.state().settings.layout.dock);
+ assert!(h.query_by_label(Pane::Layers.title()).is_none());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn palette_field<'a>(h: &'a Harness<'static, Editor>) -> egui_kittest::Node<'a> {
+ let label: &'static str = Box::leak(format!("{} Find a command", theme::icon::SEARCH).into_boxed_str());
+ h.get_by_role_and_label(Role::TextInput, label)
+}
+
+#[test]
+fn cmd_k_finds_and_runs_commands_and_explains_refusals() {
+ let path = sample("cmdk");
+ let mut h = harness(editor(&path), vec2(1280.0, 800.0));
+ activate(&mut h, "lines");
+ h.hover_at(pos2(640.0, 200.0));
+ h.key_press_modifiers(Modifiers::COMMAND, Key::K);
+ h.run_steps(3);
+ assert!(h.state().palette.is_some());
+ palette_field(&h).type_text("onion");
+ h.run_steps(2);
+ h.key_press(Key::Enter);
+ h.run_steps(3);
+ assert!(h.state().palette.is_none());
+ assert!(h.state().scene.onion_on);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::K);
+ h.run_steps(2);
+ palette_field(&h).type_text("inb");
+ h.run_steps(2);
+ h.key_press(Key::Enter);
+ h.run_steps(3);
+ let said = h.state().messages.latest().cloned().unwrap();
+ assert_eq!(said.tone, Tone::Refused);
+ assert!(said.text.starts_with("select frames first"), "{}", said.text);
+ let shown: Vec<Rect> = h
+ .query_all_by_label_contains("select frames first")
+ .map(|n| n.rect())
+ .collect();
+ assert!(
+ shown.iter().any(|r| (r.min - pos2(640.0, 200.0)).length() < 80.0),
+ "no toast next to the pointer: {shown:?}"
+ );
+ assert!(
+ shown.iter().any(|r| r.bottom() > 800.0 - layout::STATUS),
+ "not in the status line: {shown:?}"
+ );
+ (0..3).for_each(|_| {
+ h.key_press(Key::Period);
+ h.run_steps(3);
+ });
+ assert_eq!(h.state().scene.frame, 3);
+ h.key_press(Key::K);
+ h.run_steps(2);
+ let latest = h.state().messages.latest().cloned().unwrap();
+ assert_eq!(latest.tone, Tone::Info, "{}", latest.text);
+ assert!(latest.text.starts_with("new drawing"), "{}", latest.text);
+ h.key_press(Key::O);
+ h.run_steps(2);
+ assert!(!h.state().scene.onion_on);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn every_command_answers_whether_it_can_run_and_toggles_say_their_state() {
+ let path = sample("commands");
+ let mut h = harness(editor(&path), vec2(1280.0, 800.0));
+ activate(&mut h, "lines");
+ let ed = h.state();
+ let runnable: Vec<Cmd> = Cmd::ALL.into_iter().filter(|c| ed.can_run(*c).is_none()).collect();
+ assert!(runnable.contains(&Cmd::NewDrawing) && runnable.contains(&Cmd::Play));
+ assert!(ed.can_run(Cmd::Copy).is_some() && ed.can_run(Cmd::Pan).is_some());
+ assert_eq!(ed.is_on(Cmd::Brush), Some(true));
+ assert_eq!(ed.is_on(Cmd::LayersPane), Some(true));
+ assert_eq!(ed.is_on(Cmd::Undo), None);
+ h.state_mut().picked = Some(Picked::whole("c6".into(), vec![0]));
+ h.state_mut().tool = Tool::Strokes;
+ assert!(h.state().can_run(Cmd::Copy).is_none());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn copy_dir(from: &Path, to: &Path) {
+ std::fs::create_dir_all(to).unwrap();
+ std::fs::read_dir(from).unwrap().for_each(|e| {
+ let e = e.unwrap();
+ let target = to.join(e.file_name());
+ match e.file_type().unwrap().is_dir() {
+ true if e.file_name() == ".cache" => {}
+ true => copy_dir(&e.path(), &target),
+ false => {
+ std::fs::copy(e.path(), target).unwrap();
+ }
+ }
+ });
+}
+
+#[test]
+#[ignore]
+fn ui_time_per_frame() {
+ let creature = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/creature/creature.draw");
+ let copy = std::env::temp_dir().join(format!("draw-ui-creature-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&copy);
+ if creature.exists() {
+ copy_dir(&creature, &copy);
+ }
+ let sample = sample("time");
+ let stress = std::env::temp_dir().join(format!("draw-ui-stress-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&stress);
+ let exe = std::env::current_exe().unwrap();
+ let draw = exe.parent().and_then(Path::parent).unwrap().join("klad");
+ if draw.exists() {
+ let made = std::process::Command::new(&draw)
+ .args(["stress", stress.to_str().unwrap(), "--frames", "48"])
+ .output()
+ .unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+ }
+ [
+ ("sample", sample.clone()),
+ ("creature", copy.clone()),
+ ("stress animation", stress.clone()),
+ ]
+ .into_iter()
+ .filter(|(_, p)| p.join("doc.json").exists())
+ .for_each(|(name, path)| {
+ let mut h = harness(editor(&path), vec2(1600.0, 1000.0));
+ h.state_mut().settings.layout.numbers = true;
+ h.state_mut().windows.log = true;
+ h.state_mut().tool = Tool::Strokes;
+ h.run_steps(10);
+ let start = std::time::Instant::now();
+ while !(h.state().canvas_current() && h.state().dirty.is_empty()) && start.elapsed().as_secs() < 120 {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ h.run_steps(30);
+ h.state_mut().invoke(Cmd::ResetNumbers).unwrap();
+ (0..200).for_each(|i| {
+ h.hover_at(pos2(300.0 + (i % 40) as f32 * 20.0, 200.0 + (i % 7) as f32 * 30.0));
+ h.step();
+ });
+ let line = crate::stats::lock(&h.state().stats).ui_ms.spread();
+ println!("ui per frame on the {name}, every panel and window open: {line} ms");
+ });
+ std::fs::remove_dir_all(&sample).unwrap();
+ let _ = std::fs::remove_dir_all(&copy);
+ let _ = std::fs::remove_dir_all(&stress);
+}
+
+#[test]
+#[ignore]
+fn panel_pictures() {
+ let out = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scratch/ui");
+ std::fs::create_dir_all(&out).unwrap();
+ let creature = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/creature/creature.draw");
+ let path = std::env::temp_dir().join(format!("draw-ui-pictures-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&path);
+ copy_dir(&creature, &path);
+ let mut h = Harness::builder()
+ .with_size(vec2(1440.0, 900.0))
+ .wgpu()
+ .build_ui_state(|ui, editor: &mut Editor| editor.frame(ui), editor(&path));
+ h.run_steps(6);
+ let shot = |h: &mut Harness<'static, Editor>, name: &str| {
+ h.run_steps(4);
+ let picture = h.render().unwrap();
+ picture.save(out.join(format!("{name}.png"))).unwrap();
+ };
+ shot(&mut h, "1-shell");
+ h.hover_at(pos2(22.0, 30.0));
+ h.run_steps(30);
+ shot(&mut h, "2-strip-hint");
+ h.hover_at(pos2(700.0, 260.0));
+ h.run_steps(2);
+ h.state_mut().tool = Tool::Strokes;
+ h.state_mut().invoke(Cmd::Unlink).unwrap();
+ shot(&mut h, "3-refused-toast");
+ h.state_mut().palette = Some(super::PaletteState::default());
+ h.run_steps(2);
+ palette_field(&h).type_text("in");
+ shot(&mut h, "4-palette");
+ h.key_press(Key::Escape);
+ h.state_mut().settings.layout.numbers = true;
+ h.state_mut().windows.settings = true;
+ shot(&mut h, "5-numbers-and-settings");
+ h.state_mut().settings.layout.numbers = false;
+ h.state_mut().windows.settings = false;
+ h.state_mut().tool = Tool::Strokes;
+ h.state_mut().select_all_strokes();
+ shot(&mut h, "6-selection-bar");
+ h.state_mut().picked = None;
+ h.state_mut().tabs.push(false);
+ shot(&mut h, "7-tab");
+ h.state_mut().tabs.push(false);
+ h.run_steps(2);
+ let lines = h.state().scene.bundle.doc.find_layer("lines").unwrap().id.clone();
+ let keys = {
+ let doc = &h.state().scene.bundle.doc;
+ let starts: Vec<u32> = doc.layer(&lines).unwrap().cels().iter().map(|c| c.frame).collect();
+ starts.windows(2).find(|w| w[1] > w[0] + 1).map(|w| (w[0], w[1]))
+ };
+ if let Some((from, to)) = keys {
+ h.state_mut().go_to(from).unwrap();
+ h.state_mut().timeline.span = Some(super::tweens::Span {
+ from,
+ to,
+ rows: vec![lines.clone()],
+ anchor: (from, 0),
+ });
+ h.state_mut().windows.between = true;
+ h.state_mut().between.report = super::between::report(&format!(
+ "lines: c{from} -> c{to}, 15 marks paired (0 flood fills), by part first: body, leaf, 16 line ends kept touching\n unpaired, left out: c{to}:s16 (only in the second key)\n fills left out: colour{from}:s3 at frame {}: it leaked (900 px where the keys have 300 and 320)",
+ from + 1
+ ));
+ shot(&mut h, "8-inbetween-panel");
+ h.state_mut().windows.between = false;
+ h.state_mut().timeline.span = None;
+ }
+ h.state_mut().windows.settings = true;
+ h.state_mut().key_filter = "layer".into();
+ shot(&mut h, "9-settings-keys");
+ h.state_mut().windows.settings = false;
+ [Pane::Tool, Pane::Layers, Pane::Inspector]
+ .into_iter()
+ .for_each(|pane| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = true;
+ }
+ });
+ [Pane::Notes, Pane::History].into_iter().for_each(|pane| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = false;
+ }
+ });
+ let frame = h.state().scene.frame;
+ klad_core::notes::add(
+ &h.state().scene.bundle,
+ (520.0, 380.0),
+ frame,
+ "the sprout should lag more",
+ "user",
+ )
+ .unwrap();
+ klad_core::notes::add(
+ &h.state().scene.bundle,
+ (600.0, 700.0),
+ frame + 2,
+ "feet slide here",
+ "user",
+ )
+ .unwrap();
+ let done = klad_core::notes::add(&h.state().scene.bundle, (420.0, 300.0), frame, "darker rim", "user").unwrap();
+ klad_core::notes::set_done(&h.state().scene.bundle, done.id, true).unwrap();
+ h.state_mut().pins = klad_core::notes::read(&h.state().scene.bundle);
+ h.state_mut().tool = Tool::Note;
+ h.state_mut().open_pin(1);
+ shot(&mut h, "10-history-notes-pins");
+ h.state_mut().note_open = None;
+ h.state_mut().timeline.range = Some((0, 9));
+ h.state_mut().invoke(Cmd::Prepare).unwrap();
+ settle(&mut h, |ed| ed.buffering.preparing.is_none());
+ settle(&mut h, |ed| ed.buffering.job_idle());
+ h.run_steps(4);
+ shot(&mut h, "11-prepared-frames");
+ h.state_mut().tool = Tool::Brush;
+ h.state_mut().pick("dry-brush");
+ h.state_mut().windows.brush = true;
+ h.run_steps(4);
+ shot(&mut h, "12-brush-window");
+ h.state_mut().windows.brush = false;
+ [(Pane::Inspector, false), (Pane::Notes, true), (Pane::History, true)]
+ .into_iter()
+ .for_each(|(pane, collapsed)| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = collapsed;
+ }
+ });
+ h.state_mut().invoke(Cmd::NewPaintLayer).unwrap();
+ let light = h.state().scene.active_id().unwrap();
+ h.state_mut()
+ .set(
+ &light,
+ vec![
+ ("blend".into(), serde_json::json!("add")),
+ (
+ "effects".into(),
+ serde_json::json!([{"glow": {"radius": 24, "strength": 0.8}}, {"outline": {"width": 3}}]),
+ ),
+ ],
+ )
+ .unwrap();
+ h.run_steps(4);
+ shot(&mut h, "13-effects");
+ h.state_mut().invoke(Cmd::NewAdjustLayer).unwrap();
+ h.run_steps(4);
+ shot(&mut h, "14-curves");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn each_tool_shows_its_options_and_the_strip_shows_the_eraser() {
+ let path = sample("options");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "lines");
+ [
+ (Key::B, Cmd::Brush, "brush"),
+ (Key::G, Cmd::Fill, "fill"),
+ (Key::S, Cmd::Strokes, "select strokes"),
+ (Key::V, Cmd::Shapes, "select and move"),
+ (Key::A, Cmd::Points, "edit points"),
+ (Key::P, Cmd::Pen, "pen"),
+ (Key::N, Cmd::Note, "note"),
+ (Key::E, Cmd::Eraser, "eraser"),
+ ]
+ .iter()
+ .for_each(|(key, cmd, name)| {
+ h.key_press(*key);
+ h.run_steps(2);
+ let label = format!("{} {name}", cmd.spec().icon);
+ assert!(h.query_all_by_label(&label).count() == 1, "no options for {name}");
+ });
+ assert_eq!(h.state().is_on(Cmd::Eraser), Some(true));
+ h.key_press(Key::B);
+ h.run_steps(2);
+ assert_eq!(h.state().is_on(Cmd::Eraser), Some(false));
+ let rect = h.state().canvas_rect;
+ let ctx = h.ctx.clone();
+ let turned = crate::pen::PenEvent {
+ phase: crate::pen::Phase::Move,
+ pos: rect.center(),
+ pressure: 0.0,
+ tilt: (0.0, 0.0),
+ eraser: true,
+ tablet: true,
+ device: 7,
+ at: std::time::Instant::now(),
+ };
+ h.state_mut().on_pen(&ctx, turned, rect, true).unwrap();
+ assert_eq!(h.state().is_on(Cmd::Eraser), Some(true));
+ assert_eq!(h.state().is_on(Cmd::Brush), Some(false));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_stroke_in_a_flipped_view_lands_under_the_pen() {
+ let path = sample("flip");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "notes");
+ h.key_press(Key::H);
+ h.run_steps(2);
+ let view = h.state().view.unwrap();
+ assert!(view.flip);
+ let rect = h.state().canvas_rect;
+ let (a, b) = (rect.center() + vec2(-60.0, -20.0), rect.center() + vec2(40.0, 30.0));
+ h.hover_at(a);
+ h.run_steps(1);
+ h.drag_at(a);
+ h.run_steps(1);
+ (1..=8).for_each(|i| {
+ h.hover_at(a + (b - a) * (i as f32 / 8.0));
+ h.run_steps(1);
+ });
+ h.drop_at(b);
+ h.run_steps(3);
+ let marks = h.state().scene.active_marks().to_vec();
+ let stroke = marks
+ .last()
+ .and_then(|m| m.as_stroke())
+ .expect("a stroke on notes")
+ .clone();
+ let first = stroke.samples.first().unwrap().pos();
+ let expect = view.to_canvas(a - rect.min, rect.size());
+ assert!(
+ (first.0 - expect.x).abs() < 1.5 && (first.1 - expect.y).abs() < 1.5,
+ "{first:?} vs {expect:?}"
+ );
+ let unflipped = egui::Vec2::new(2.0 * view.center.x - expect.x, expect.y);
+ assert!(
+ (first.0 - unflipped.x).abs() > 5.0,
+ "the stroke landed as if the view were not flipped"
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn palette_swatches_move_by_dragging_and_go_from_their_corner() {
+ let path = sample("palette");
+ {
+ let mut b = Bundle::open(&path).unwrap();
+ b.apply(
+ &parse_lines(
+ r##"{"op":"palette","add":"#ff0000","name":"red"}
+{"op":"palette","add":"#00ff00","name":"green"}
+{"op":"palette","add":"#0000ff","name":"blue"}"##,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ }
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ let order = |h: &Harness<'static, Editor>| -> Vec<String> {
+ h.state()
+ .scene
+ .bundle
+ .doc
+ .palette
+ .iter()
+ .map(|s| s.name.clone())
+ .collect()
+ };
+ assert_eq!(order(&h), ["red", "green", "blue"]);
+ let at = |h: &Harness<'static, Editor>, hex: &str| h.get_by_role_and_label(Role::Button, hex).rect();
+ let (red, blue) = (at(&h, "#ff0000"), at(&h, "#0000ff"));
+ h.drag_at(red.center());
+ h.run_steps(1);
+ (1..=6).for_each(|i| {
+ h.hover_at(red.center() + (blue.center() - red.center()) * (i as f32 / 6.0));
+ h.run_steps(1);
+ });
+ h.drop_at(blue.center());
+ h.run_steps(3);
+ assert_eq!(order(&h), ["green", "blue", "red"]);
+ let green = at(&h, "#00ff00");
+ let corner = egui::pos2(green.right() - 6.0, green.top() + 6.0);
+ h.hover_at(corner);
+ h.run_steps(1);
+ h.drag_at(corner);
+ h.run_steps(1);
+ h.drop_at(corner);
+ h.run_steps(3);
+ assert_eq!(order(&h), ["blue", "red"]);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn settle(h: &mut Harness<'static, Editor>, done: impl Fn(&Editor) -> bool) {
+ let start = std::time::Instant::now();
+ while !done(h.state()) && start.elapsed() < std::time::Duration::from_secs(20) {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert!(done(h.state()), "the editor did not settle");
+}
+
+fn drag(h: &mut Harness<'static, Editor>, from: egui::Pos2, to: egui::Pos2) {
+ h.hover_at(from);
+ h.run_steps(1);
+ h.drag_at(from);
+ h.run_steps(1);
+ (1..=5).for_each(|i| {
+ h.hover_at(from + (to - from) * (i as f32 / 5.0));
+ h.run_steps(1);
+ });
+ h.drop_at(to);
+ h.run_steps(1);
+}
+
+#[test]
+fn a_shape_drag_started_while_the_last_one_is_written_still_happens() {
+ let path = sample("held");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "shapes");
+ let id = {
+ let ed = h.state();
+ ed.scene.bundle.doc.find_layer("shapes").unwrap().cels()[0].nodes[0]
+ .id
+ .clone()
+ };
+ let before = h.state().node_transform(&id).unwrap();
+ h.state_mut().tool = Tool::Select;
+ h.state_mut().selection = Some(id.clone());
+ settle(&mut h, |ed| {
+ ed.lift
+ .as_ref()
+ .is_some_and(|l| l.ready.as_ref().is_some_and(|(_, p)| l.stage >= p.runs.len() + 2))
+ });
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let middle = rect.min + view.to_screen(egui::Vec2::new(80.0, 60.0), rect.size());
+ drag(&mut h, middle, middle + vec2(40.0, 0.0));
+ let writing = h.state().writing();
+ assert!(
+ writing,
+ "the first move was already written; the test would not cover a press during a write"
+ );
+ drag(&mut h, middle + vec2(40.0, 0.0), middle + vec2(40.0, 50.0));
+ settle(&mut h, |ed| !ed.writing() && ed.drag.is_none() && ed.held.len() == 0);
+ h.run_steps(3);
+ settle(&mut h, |ed| !ed.writing() && ed.drag.is_none());
+ let after = h.state().node_transform(&id).unwrap();
+ let moved = (after.x - before.x, after.y - before.y);
+ let expect = (40.0 / view.zoom, 50.0 / view.zoom);
+ assert!(
+ (moved.0 - expect.0).abs() < 2.0 && (moved.1 - expect.1).abs() < 2.0,
+ "moved {moved:?}, expected {expect:?} (the first drag was {}being written when the second began)",
+ if writing { "" } else { "not " }
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn top_down(h: &Harness<'static, Editor>) -> Vec<String> {
+ h.state()
+ .layer_rows(super::layers::Where::Panel)
+ .into_iter()
+ .map(|r| r.name)
+ .collect()
+}
+
+fn layer_named<'a>(h: &'a Harness<'static, Editor>, name: &str) -> &'a Layer {
+ h.state().scene.bundle.doc.find_layer(name).unwrap()
+}
+
+#[test]
+fn layer_rows_drag_rename_duplicate_group_and_delete() {
+ let path = sample("rows");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ [Pane::Tool, Pane::Inspector].into_iter().for_each(|pane| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = true;
+ }
+ });
+ h.run_steps(2);
+ assert_eq!(
+ top_down(&h)[..4],
+ ["lines", "colour", "shade", "mask"].map(String::from)
+ );
+ let row = |h: &Harness<'static, Editor>, name: &str| {
+ h.query_all(By::new().role(Role::Button).label(name))
+ .map(|n| n.rect())
+ .min_by(|a, b| a.top().total_cmp(&b.top()))
+ .unwrap()
+ };
+ assert!(
+ row(&h, "rim").top() < h.state().timeline.geom.unwrap().cell_centre(0, 0).y - 100.0,
+ "the drags below start in the Layers pane, not the timeline"
+ );
+ let (rim, lines) = (row(&h, "rim"), row(&h, "lines"));
+ drag(
+ &mut h,
+ egui::pos2(rim.right() - 60.0, rim.center().y),
+ egui::pos2(lines.right() - 60.0, lines.top() + 3.0),
+ );
+ h.run_steps(2);
+ assert_eq!(top_down(&h)[..2], ["rim", "lines"].map(String::from));
+ activate(&mut h, "rim");
+ h.state_mut().invoke(Cmd::RenameLayer).unwrap();
+ h.run_steps(2);
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.run_steps(1);
+ h.get_by_role_and_label(Role::TextInput, "rename")
+ .type_text("rim light");
+ h.run_steps(1);
+ h.key_press(egui::Key::Enter);
+ h.run_steps(2);
+ assert_eq!(top_down(&h)[0], "rim light");
+ activate(&mut h, "lines");
+ h.state_mut().invoke(Cmd::DuplicateLayer).unwrap();
+ h.run_steps(2);
+ assert_eq!(
+ top_down(&h)[..3],
+ ["rim light", "lines copy", "lines"].map(String::from)
+ );
+ assert_eq!(h.state().scene.active_layer().unwrap().name, "lines copy");
+ let copy = layer_named(&h, "lines copy").clone();
+ let marks = h.state().scene.bundle.read_marks(&copy.id, &copy.cels()[0].id).unwrap();
+ assert_eq!(marks.len(), 2);
+ activate(&mut h, "notes");
+ h.state_mut().invoke(Cmd::GroupLayer).unwrap();
+ h.run_steps(2);
+ let group = layer_named(&h, "notes group").clone();
+ assert_eq!(
+ group.children().iter().map(|l| l.name.as_str()).collect::<Vec<_>>(),
+ ["notes"]
+ );
+ let (colour, target) = (row(&h, "colour"), row(&h, "notes group"));
+ drag(
+ &mut h,
+ egui::pos2(colour.right() - 60.0, colour.center().y),
+ egui::pos2(target.right() - 60.0, target.center().y),
+ );
+ h.run_steps(2);
+ let group = layer_named(&h, "notes group").clone();
+ assert_eq!(
+ group.children().iter().map(|l| l.name.as_str()).collect::<Vec<_>>(),
+ ["notes", "colour"]
+ );
+ activate(&mut h, "lines copy");
+ h.state_mut().invoke(Cmd::DeleteLayer).unwrap();
+ h.run_steps(2);
+ assert!(h.state().scene.bundle.doc.find_layer("lines copy").is_err());
+ assert!(h.state().scene.active_layer().is_some());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn timeline_cells_select_by_dragging_copy_paste_move_and_open_the_clip() {
+ let path = sample("cells");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ let geom = h.state().timeline.geom.unwrap();
+ drag(&mut h, geom.cell_centre(2, 0), geom.cell_centre(5, 0));
+ h.run_steps(2);
+ let span = h.state().timeline.span.clone().unwrap();
+ assert_eq!((span.from, span.to, span.rows.len()), (2, 5, 1));
+ h.state_mut().invoke(Cmd::CopyCells).unwrap();
+ h.run_steps(1);
+ h.state_mut().go_to(10).unwrap();
+ h.state_mut().invoke(Cmd::PasteCells).unwrap();
+ h.run_steps(2);
+ let starts = |h: &Harness<'static, Editor>| -> Vec<(u32, Option<u32>)> {
+ layer_named(h, "lines")
+ .cels()
+ .iter()
+ .map(|c| (c.frame, c.hold))
+ .collect()
+ };
+ assert!(starts(&h).contains(&(10, Some(4))), "{:?}", starts(&h));
+ let pasted = layer_named(&h, "lines")
+ .cels()
+ .iter()
+ .find(|c| c.frame == 10)
+ .unwrap()
+ .id
+ .clone();
+ let id = layer_named(&h, "lines").id.clone();
+ assert_eq!(h.state().scene.bundle.read_marks(&id, &pasted).unwrap().len(), 2);
+ h.state_mut().invoke(Cmd::MoveLater).unwrap();
+ h.run_steps(2);
+ assert!(starts(&h).contains(&(11, Some(4))), "{:?}", starts(&h));
+ assert_eq!(h.state().scene.frame, 11);
+ let geom = h.state().timeline.geom.unwrap();
+ drag(
+ &mut h,
+ geom.cell_centre(11, 0) + vec2(3.0, 0.0),
+ geom.cell_centre(14, 0),
+ );
+ h.run_steps(2);
+ assert!(starts(&h).contains(&(14, Some(4))), "{:?}", starts(&h));
+ h.state_mut().go_to(3).unwrap();
+ h.state_mut().invoke(Cmd::ClipSettings).unwrap();
+ h.run_steps(2);
+ assert!(h.query_all(By::new().label_contains("Clip walk")).count() > 0);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn the_history_lists_you_and_the_agent_and_steps_back_to_a_clicked_step() {
+ let path = sample("history");
+ {
+ let mut b = Bundle::open(&path).unwrap();
+ b.apply(&parse_lines(r#"{"op":"stroke","layer":"l6","path":"M10 10 L50 50"}"#).unwrap())
+ .unwrap();
+ b.apply_as(
+ &parse_lines(r#"{"op":"stroke","layer":"l6","path":"M60 10 L90 50"}"#).unwrap(),
+ "editor",
+ )
+ .unwrap();
+ b.apply(&parse_lines(r#"{"op":"stroke","layer":"l6","path":"M100 10 L140 50"}"#).unwrap())
+ .unwrap();
+ }
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ [Pane::Tool, Pane::Layers, Pane::Inspector]
+ .into_iter()
+ .for_each(|pane| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = true;
+ }
+ });
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::History) {
+ p.collapsed = false;
+ }
+ h.run_steps(3);
+ let strokes = |h: &Harness<'static, Editor>| h.state().scene.bundle.read_marks("l6", "c6").unwrap().len();
+ assert_eq!(strokes(&h), 5);
+ let rows = h.state_mut().history_rows();
+ assert_eq!(
+ rows.iter().take(3).map(|r| r.who.as_str()).collect::<Vec<_>>(),
+ ["agent", "you", "agent"]
+ );
+ assert!(h.query_all(By::new().label_contains("the document is here")).count() > 0);
+ let click = |h: &Harness<'static, Editor>, who: &str| {
+ h.query_all(By::new().role(Role::Button).label_contains(who))
+ .next()
+ .unwrap()
+ .click();
+ };
+ click(&h, "you ");
+ h.run_steps(3);
+ assert_eq!(strokes(&h), 4);
+ let rows = h.state_mut().history_rows();
+ assert!(rows[0].undone && rows[0].what.contains("stroke"));
+ assert_eq!(rows.iter().filter(|r| r.undone).count(), 1);
+ click(&h, "undone ");
+ h.run_steps(3);
+ assert_eq!(strokes(&h), 5);
+ assert!(h.state_mut().history_rows().iter().all(|r| !r.undone));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_note_pinned_on_the_canvas_is_marked_done_by_the_agent_and_edited_from_its_pin() {
+ use klad_core::notes;
+ let path = sample("notes");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ h.state_mut().go_to(12).unwrap();
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::Notes) {
+ p.collapsed = false;
+ }
+ h.state_mut().tool = Tool::Note;
+ h.run_steps(3);
+ let c = h.state().canvas_rect.center();
+ drag(&mut h, c, c);
+ h.run_steps(2);
+ assert!(h.state().note_at.is_some());
+ h.query_all(By::new().label_contains("a note for the agent"))
+ .find(|n| n.accesskit_node().role() == Role::MultilineTextInput)
+ .unwrap()
+ .type_text("move the lamp left");
+ h.run_steps(2);
+ checked_popover(&h);
+ h.get_by_role_and_label(Role::Button, "pin it").click();
+ h.run_steps(2);
+ let pinned = notes::read(&Bundle::open(&path).unwrap());
+ assert_eq!(pinned.len(), 1);
+ assert_eq!((pinned[0].frame, pinned[0].text.as_str()), (12, "move the lamp left"));
+ notes::set_done(&Bundle::open(&path).unwrap(), pinned[0].id, true).unwrap();
+ settle(&mut h, |e| e.pins.iter().any(|n| n.done));
+ h.run_steps(2);
+ assert!(h.query_all(By::new().label_contains("done (1)")).count() > 0);
+ h.state_mut().go_to(0).unwrap();
+ h.state_mut().open_pin(pinned[0].id);
+ h.run_steps(2);
+ h.state_mut().note_edit = "move the lamp right".into();
+ h.run_steps(2);
+ h.get_by_role_and_label(Role::Button, "save").click();
+ h.run_steps(2);
+ assert_eq!(
+ notes::read(&Bundle::open(&path).unwrap())[0].text,
+ "move the lamp right"
+ );
+ h.get_by_role_and_label(Role::Button, "close").click();
+ h.run_steps(2);
+ assert!(h.state().note_open.is_none());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn checked_popover(h: &Harness<'static, Editor>) {
+ assert!(audit(h, "the pin popover") > 0);
+}
+
+#[test]
+fn a_key_changed_in_the_settings_runs_its_command_and_a_taken_key_is_refused() {
+ let path = sample("keys");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ h.state_mut().windows.settings = true;
+ h.state_mut().key_filter = "duplicate the layer".into();
+ h.run_steps(3);
+ h.get_by_role_and_label(Role::Button, "change").click();
+ h.run_steps(2);
+ assert_eq!(h.state().capturing, Some(Cmd::DuplicateLayer));
+ h.key_press_modifiers(Modifiers::SHIFT, Key::D);
+ h.run_steps(2);
+ assert_eq!(h.state().settings.keys["layer.duplicate"], ["shift D"]);
+ assert!(h.state().command_hint(Cmd::DuplicateLayer).contains("shift D"));
+ h.state_mut().windows.settings = false;
+ h.run_steps(2);
+ h.key_press_modifiers(Modifiers::SHIFT, Key::D);
+ h.run_steps(3);
+ assert!(h.state().scene.bundle.doc.find_layer("lines copy").is_ok());
+ h.state_mut().capturing = Some(Cmd::Brush);
+ h.run_steps(1);
+ h.key_press(Key::E);
+ h.run_steps(2);
+ let refused = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ assert!(refused.contains("eraser"), "{refused}");
+ assert!(!h.state().settings.keys.contains_key("tool.brush"));
+ h.state_mut().settings.ui_scale = 1.25;
+ h.run_steps(2);
+ assert!((h.ctx.zoom_factor() - 1.25).abs() < 1e-3);
+ {
+ let ed = h.state_mut();
+ ed.settings.defaults.size = Some(30.0);
+ ed.settings.defaults.exposure = 3;
+ ed.settings.defaults.onion_before = 4;
+ ed.use_defaults();
+ }
+ assert_eq!(h.state().size, 30.0);
+ assert_eq!(h.state().timeline.on, 3);
+ assert_eq!(h.state().scene.onion.before, 4);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn v_picks_and_drags_the_stroke_under_the_pen_and_alt_drags_a_copy() {
+ let path = sample("move");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "notes");
+ h.state_mut().tool = Tool::Select;
+ h.run_steps(2);
+ ready(&mut h);
+ let marks = |h: &Harness<'static, Editor>| h.state().scene.bundle.read_marks("l6", "c6").unwrap();
+ let start = |m: &klad_core::stroke::Mark| m.as_stroke().unwrap().samples[0].pos();
+ let before = marks(&h);
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let on_line = rect.min + view.to_screen(egui::Vec2::new(170.0, 120.0), rect.size());
+ drag(&mut h, on_line, on_line + vec2(40.0, 0.0));
+ settle(&mut h, |ed| !ed.writing() && ed.drag.is_none());
+ if start(&marks(&h)[0]) == start(&before[0]) {
+ ready(&mut h);
+ drag(&mut h, on_line, on_line + vec2(40.0, 0.0));
+ settle(&mut h, |ed| !ed.writing() && ed.drag.is_none());
+ }
+ h.run_steps(2);
+ assert_eq!(h.state().scene.active_layer().unwrap().name, "lines");
+ let after = marks(&h);
+ assert_eq!(after.len(), before.len());
+ let moved = start(&after[0]).0 - start(&before[0]).0;
+ assert!((moved - 40.0 / view.zoom).abs() < 1.5, "moved {moved}");
+ assert_eq!(start(&after[1]), start(&before[1]));
+ let on_line = on_line + vec2(40.0, 0.0);
+ h.event(egui::Event::ModifiersChanged(Modifiers::ALT));
+ drag(&mut h, on_line, on_line + vec2(0.0, 30.0));
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ settle(&mut h, |ed| !ed.writing() && ed.drag.is_none());
+ h.run_steps(2);
+ let copied = marks(&h);
+ assert_eq!(
+ copied.len(),
+ before.len() + 1,
+ "alt drag leaves the original and moves a copy"
+ );
+ assert_eq!(start(&copied[0]), start(&after[0]));
+ let dropped = start(copied.last().unwrap());
+ assert!(
+ (dropped.1 - start(&after[0]).1 - 30.0 / view.zoom).abs() < 1.5,
+ "{dropped:?}"
+ );
+ assert_eq!(h.state().tool, Tool::Select);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn an_agent_edit_while_the_editor_is_open_shows_in_the_history_and_keeps_its_author() {
+ let path = sample("agent-row");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::History) {
+ p.collapsed = false;
+ }
+ h.run_steps(3);
+ Bundle::open(&path)
+ .unwrap()
+ .apply(&parse_lines(r#"{"op":"stroke","layer":"l6","path":"M100 100 L300 300"}"#).unwrap())
+ .unwrap();
+ settle(&mut h, |ed| {
+ ed.scene.bundle.read_marks("l6", "c6").unwrap().len() == 3
+ && ed.scene.disk_rev() == Some(ed.scene.bundle.doc.rev)
+ });
+ h.run_steps(2);
+ let first = |h: &mut Harness<'static, Editor>| {
+ let rows = h.state_mut().history_rows();
+ (rows[0].who.clone(), rows[0].what.clone(), rows[0].undone)
+ };
+ assert_eq!(first(&mut h), ("agent".into(), "stroke on l6".into(), false));
+ assert!(
+ h.query_all(By::new().role(Role::Button).label_contains("agent stroke on l6"))
+ .count()
+ > 0
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ assert_eq!(first(&mut h), ("agent".into(), "stroke on l6".into(), true));
+ h.state_mut().invoke(Cmd::Redo).unwrap();
+ h.run_steps(2);
+ assert_eq!(first(&mut h), ("agent".into(), "stroke on l6".into(), false));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_right_click_with_the_note_tool_goes_to_a_note_and_delete_removes_it() {
+ use klad_core::notes;
+ let path = sample("note-pick");
+ notes::add(&Bundle::open(&path).unwrap(), (200.0, 150.0), 12, "the lamp", "user").unwrap();
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ h.state_mut().tool = Tool::Note;
+ h.run_steps(3);
+ assert_eq!(h.state().scene.frame, 0);
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let pin = rect.min + view.to_screen(egui::Vec2::new(200.0, 150.0), rect.size());
+ h.hover_at(pin);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton {
+ pos: pin,
+ button: egui::PointerButton::Secondary,
+ pressed: true,
+ modifiers: Modifiers::NONE,
+ });
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton {
+ pos: pin,
+ button: egui::PointerButton::Secondary,
+ pressed: false,
+ modifiers: Modifiers::NONE,
+ });
+ h.run_steps(3);
+ assert_eq!(h.state().scene.frame, 12);
+ let id = notes::read(&Bundle::open(&path).unwrap())[0].id;
+ assert_eq!(h.state().note_open, Some(id));
+ assert!(h.state().note_at.is_none(), "a right click does not start a new note");
+ h.key_press(Key::Delete);
+ h.run_steps(2);
+ assert!(notes::read(&Bundle::open(&path).unwrap()).is_empty());
+ assert!(h.state().note_open.is_none());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_drag_from_a_drawings_first_cell_selects_unless_it_starts_on_the_dot() {
+ let path = sample("first-cell");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ let geom = h.state().timeline.geom.unwrap();
+ let corner = geom.cell_centre(0, 0) + vec2(-7.0, -10.0);
+ drag(&mut h, corner, geom.cell_centre(3, 0));
+ h.run_steps(2);
+ let span = h
+ .state()
+ .timeline
+ .span
+ .clone()
+ .expect("a selection from the first cell");
+ assert_eq!((span.from, span.to), (0, 3));
+ let cels =
+ |h: &Harness<'static, Editor>| -> Vec<u32> { layer_named(h, "lines").cels().iter().map(|c| c.frame).collect() };
+ assert_eq!(cels(&h), [0]);
+ drag(&mut h, geom.cell_centre(0, 0), geom.cell_centre(4, 0));
+ h.run_steps(2);
+ assert_eq!(cels(&h), [4], "the dot moves the drawing");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+#[ignore]
+fn a_heavy_animation_keeps_the_ui_responsive_while_frames_load() {
+ let stress = std::env::temp_dir().join(format!("draw-ui-heavy-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&stress);
+ let exe = std::env::current_exe().unwrap();
+ let draw = exe.parent().and_then(Path::parent).unwrap().join("klad");
+ let size = std::env::var("KLAD_HEAVY_SIZE").unwrap_or_else(|_| "2048".into());
+ let made = std::process::Command::new(&draw)
+ .args(["stress", stress.to_str().unwrap(), "--frames", "12", "--size", &size])
+ .output()
+ .unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+ let t = std::time::Instant::now();
+ let mut h = harness(editor(&stress), vec2(1600.0, 1000.0));
+ let opened = t.elapsed().as_secs_f64() * 1000.0;
+ let mut times: Vec<f64> = Vec::new();
+ let mut step = |h: &mut Harness<'static, Editor>| {
+ let t = std::time::Instant::now();
+ h.run_steps(1);
+ times.push(t.elapsed().as_secs_f64() * 1000.0);
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ };
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(60) {
+ step(&mut h);
+ }
+ let first = start.elapsed().as_secs_f64() * 1000.0;
+ let mut ready = Vec::new();
+ [2u32, 4, 6].into_iter().for_each(|f| {
+ h.state_mut().go_to(f).unwrap();
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(60) {
+ step(&mut h);
+ }
+ ready.push((f, start.elapsed().as_millis(), h.state().scene.cache_bytes() >> 20));
+ });
+ h.state_mut().go_to(10).unwrap();
+ h.run_steps(2);
+ let c = h.state().canvas_rect.center();
+ let t = std::time::Instant::now();
+ h.hover_at(c);
+ h.run_steps(1);
+ h.drag_at(c);
+ h.run_steps(1);
+ let press = t.elapsed().as_secs_f64() * 1000.0;
+ let said = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ h.drop_at(c);
+ h.run_steps(1);
+ times.sort_by(f64::total_cmp);
+ let at = |q: f64| times[((times.len() - 1) as f64 * q) as usize];
+ eprintln!(
+ "{size} px: editor open {opened:.0} ms, frame 0 editable after {first:.0} ms more, frames ready (frame, ms, MB of drawings) {ready:?}, UI frames while loading: median {:.1} ms, p95 {:.1}, slowest {:.0} of {}; pen down on a loading frame {press:.0} ms ({said})",
+ at(0.5),
+ at(0.95),
+ at(1.0),
+ times.len()
+ );
+ assert!(said.contains("still loading"), "{said}");
+ assert!(press < 250.0 && opened < 1500.0, "the UI waited");
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(120) {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ drop(h);
+ let mut h = harness(editor(&stress), vec2(1600.0, 1000.0));
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(60) {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ let warm_first = start.elapsed().as_millis();
+ let warm: Vec<(u32, u128, u128)> = [2u32, 4, 6]
+ .into_iter()
+ .map(|f| {
+ h.state_mut().go_to(f).unwrap();
+ let start = std::time::Instant::now();
+ let mut seen = None;
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(60) {
+ h.run_steps(1);
+ if seen.is_none() && h.state().timeline.on_screen == Some(f) {
+ seen = Some(start.elapsed().as_millis());
+ }
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ (f, seen.unwrap_or(0), start.elapsed().as_millis())
+ })
+ .collect();
+ eprintln!(
+ "{size} px reopened: frame 0 editable after {warm_first} ms, frames (frame, on screen ms, ready to draw ms) {warm:?}"
+ );
+ h.state_mut().timeline.range = Some((0, 11));
+ let start = std::time::Instant::now();
+ h.state_mut().invoke(Cmd::Prepare).unwrap();
+ let mut prepare_frames: Vec<f64> = Vec::new();
+ while h.state().buffering.preparing.is_some() && start.elapsed() < std::time::Duration::from_secs(600) {
+ let t = std::time::Instant::now();
+ h.run_steps(1);
+ prepare_frames.push(t.elapsed().as_secs_f64() * 1000.0);
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ let prepared = start.elapsed().as_millis();
+ settle(&mut h, |ed| {
+ ed.buffering.job_idle() && ed.buffering.shown.watch.len() >= 12
+ });
+ prepare_frames.sort_by(f64::total_cmp);
+ let after: Vec<(u32, u128, u128)> = [8u32, 10, 11]
+ .into_iter()
+ .map(|f| {
+ h.state_mut().go_to(f).unwrap();
+ let start = std::time::Instant::now();
+ let mut seen = None;
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(60) {
+ h.run_steps(1);
+ if seen.is_none() && h.state().timeline.on_screen == Some(f) {
+ seen = Some(start.elapsed().as_millis());
+ }
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ (f, seen.unwrap_or(0), start.elapsed().as_millis())
+ })
+ .collect();
+ eprintln!(
+ "{size} px prepare frames 0 to 11: {prepared} ms (UI frames meanwhile median {:.1} ms, slowest {:.0}); frames never visited, after it (frame, on screen ms, ready to draw ms) {after:?}",
+ prepare_frames[prepare_frames.len() / 2],
+ prepare_frames.last().copied().unwrap_or(0.0)
+ );
+ let _ = std::fs::remove_dir_all(&stress);
+}
+
+#[test]
+fn the_pen_draws_closed_and_open_paths_on_a_vector_layer() {
+ let path = sample("pen");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "lines");
+ h.key_press(Key::P);
+ h.run_steps(2);
+ assert_eq!(h.state().tool, Tool::Pen);
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let at = |x: f32, y: f32| rect.min + view.to_screen(egui::Vec2::new(x, y), rect.size());
+ let click = |h: &mut Harness<'static, Editor>, p: egui::Pos2| {
+ h.hover_at(p);
+ h.run_steps(1);
+ h.drag_at(p);
+ h.run_steps(1);
+ h.drop_at(p);
+ h.run_steps(1);
+ };
+ click(&mut h, at(300.0, 100.0));
+ let refused = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ assert!(refused.contains("vector layer"), "{refused}");
+ activate(&mut h, "shapes");
+ let nodes = |h: &Harness<'static, Editor>| layer_named(h, "shapes").cels()[0].nodes.clone();
+ let before = nodes(&h).len();
+ [(300.0, 100.0), (400.0, 120.0), (350.0, 220.0)]
+ .into_iter()
+ .for_each(|(x, y)| click(&mut h, at(x, y)));
+ click(&mut h, at(300.0, 100.0));
+ h.run_steps(2);
+ let after = nodes(&h);
+ assert_eq!(after.len(), before + 1);
+ let added = after.last().unwrap();
+ match &added.shape {
+ klad_core::doc::Shape::Path { d } => assert!(d.trim_end().ends_with('Z'), "{d}"),
+ other => panic!("{other:?}"),
+ }
+ assert!(added.fill.is_some() && added.stroke.is_some());
+ click(&mut h, at(100.0, 300.0));
+ drag(&mut h, at(200.0, 300.0), at(240.0, 260.0));
+ h.key_press(Key::Enter);
+ h.run_steps(2);
+ let after = nodes(&h);
+ assert_eq!(after.len(), before + 2);
+ let open = after.last().unwrap();
+ match &open.shape {
+ klad_core::doc::Shape::Path { d } => {
+ assert!(
+ d.contains('C') && !d.contains('Z'),
+ "a dragged point makes a curve: {d}"
+ )
+ }
+ other => panic!("{other:?}"),
+ }
+ assert!(open.fill.is_none() && open.stroke.is_some());
+ assert!(h.state().pen_path.is_none());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn prepare_frames_buffers_the_clip_and_the_ruler_shows_it() {
+ let path = sample("prepare");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ settle(&mut h, |ed| ed.buffering.job_idle());
+ assert_eq!(h.state().prepare_span(), (0, 11), "the clip under the playhead");
+ let pictures = h.state().scene.pictures();
+ let on_disk = |dir: &Path| std::fs::read_dir(dir).map_or(0, |d| d.count());
+ let before = on_disk(&pictures);
+ h.get_by_role_and_label(Role::Button, Cmd::Prepare.spec().icon).click();
+ h.run_steps(2);
+ assert_eq!(h.state().is_on(Cmd::Prepare), Some(true));
+ settle(&mut h, |ed| ed.buffering.preparing.is_none());
+ settle(&mut h, |ed| {
+ ed.buffering.shown.watch.len() >= 12 && ed.buffering.job_idle()
+ });
+ let shown = h.state().buffering.shown.clone();
+ assert!(
+ (0..12).all(|f| shown.watch.contains(&f) && shown.draw.contains(&f)),
+ "{shown:?}"
+ );
+ assert!(on_disk(&pictures) >= before.max(1));
+ let keys: Vec<u64> = (0..12)
+ .map(|f| {
+ let ed = h.state_mut();
+ ed.frames.key(&mut ed.scene, f, false, &ed.brushes)
+ })
+ .collect();
+ assert!(
+ keys.iter()
+ .all(|k| crate::composite::picture_path(&pictures, *k).exists()),
+ "the clip's pictures are on disk"
+ );
+ let tiles = path.join(".cache/tiles");
+ assert!(on_disk(&tiles) >= 2, "its drawings are cached");
+ let said = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ assert!(said.contains("prepared"), "{said}");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn the_brush_window_edits_a_brush_shows_it_and_saves_it_in_the_drawing() {
+ let path = sample("brush-window");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ h.key_press(Key::F5);
+ h.run_steps(3);
+ assert!(h.state().windows.brush);
+ let shown = |h: &Harness<'static, Editor>| h.state().brush_window_preview_key();
+ let before = shown(&h);
+ h.get_by_role_and_label(Role::CheckBox, "dual tip").click();
+ h.run_steps(3);
+ assert!(h.state().custom.as_ref().is_some_and(|d| d.dual.is_some()));
+ assert_ne!(shown(&h), before, "the sample shows the change");
+ h.get_by_label("wet").click();
+ h.run_steps(3);
+ assert!(matches!(
+ h.state().custom.as_ref().and_then(|d| d.paint),
+ Some(klad_core::brushes::PaintDef::Wet { .. })
+ ));
+ h.key_press(Key::F5);
+ h.run_steps(2);
+ let rect = h.state().canvas_rect;
+ let (a, b) = (rect.center() + vec2(-80.0, 0.0), rect.center() + vec2(80.0, 20.0));
+ h.key_press(Key::B);
+ h.run_steps(1);
+ let count = h.state().scene.active_marks().len();
+ drag(&mut h, a, b);
+ h.run_steps(2);
+ assert_eq!(h.state().scene.active_marks().len(), count + 1);
+ let drawn = h
+ .state()
+ .scene
+ .active_marks()
+ .last()
+ .and_then(|m| m.as_stroke())
+ .unwrap()
+ .brush
+ .clone();
+ assert!(
+ drawn.starts_with("ink-"),
+ "drawn with the edited brush as a variant: {drawn}"
+ );
+ h.key_press(Key::F5);
+ h.run_steps(2);
+ h.state_mut().brush_window.name = "Wet Dry".into();
+ h.get_by_role_and_label(Role::Button, "save in this drawing").click();
+ h.run_steps(3);
+ let saved = Bundle::open(&path)
+ .unwrap()
+ .brush("wet-dry")
+ .unwrap()
+ .expect("saved in the bundle");
+ assert!(saved.dual.is_some() && saved.paint.is_some());
+ assert_eq!(h.state().brush, "wet-dry");
+ assert!(h.state().custom.is_none());
+ let mut png = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut png, 2, 2);
+ encoder.set_color(png::ColorType::Grayscale);
+ let mut writer = encoder.write_header().unwrap();
+ writer.write_image_data(&[0, 255, 255, 0]).unwrap();
+ }
+ h.state_mut().add_brush_picture("checks", &png).unwrap();
+ assert!(path.join("brushes/images/checks.png").exists());
+ assert!(h.state().brushes.pictures().contains_key("checks"));
+ assert!(h.state_mut().add_brush_picture("checks", &[1, 2, 3]).is_err());
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_bends_a_brush_stroke_and_the_stroke_keeps_its_pressure() {
+ let path = sample("reshape");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "notes");
+ h.key_press(Key::A);
+ h.run_steps(2);
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let at = |x: f32, y: f32| rect.min + view.to_screen(egui::Vec2::new(x, y), rect.size());
+ let click = |h: &mut Harness<'static, Editor>, p: egui::Pos2| {
+ h.hover_at(p);
+ h.run_steps(1);
+ h.drag_at(p);
+ h.run_steps(1);
+ h.drop_at(p);
+ h.run_steps(2);
+ };
+ click(&mut h, at(170.0, 120.0));
+ assert_eq!(h.state().scene.active_layer().unwrap().name, "lines");
+ let node = h.state().direct.as_ref().map(|d| d.node.clone()).unwrap();
+ assert_eq!(node, "c6:s1");
+ let before = h.state().scene.bundle.read_marks("l6", "c6").unwrap()[0]
+ .as_stroke()
+ .unwrap()
+ .clone();
+ let first = h.state().shaped.as_ref().unwrap().subs[0].anchors[0].at;
+ let start = at(first[0], first[1]);
+ drag(&mut h, start, start + vec2(0.0, 60.0));
+ settle(&mut h, |ed| ed.point_drag.is_none());
+ h.run_steps(2);
+ let after = h.state().scene.bundle.read_marks("l6", "c6").unwrap()[0]
+ .as_stroke()
+ .unwrap()
+ .clone();
+ assert_eq!(after.samples.len(), before.samples.len());
+ let moved = after.samples[0].pos().1 - before.samples[0].pos().1;
+ assert!((moved - 60.0 / view.zoom).abs() < 3.0, "the start moved {moved}");
+ let end = (
+ after.samples.last().unwrap().pos(),
+ before.samples.last().unwrap().pos(),
+ );
+ assert!(
+ (end.0.0 - end.1.0).abs() < 1.5 && (end.0.1 - end.1.1).abs() < 1.5,
+ "{end:?}"
+ );
+ assert!(
+ after
+ .samples
+ .iter()
+ .zip(&before.samples)
+ .all(|(a, b)| a.pressure == b.pressure)
+ );
+ assert_eq!(h.state().direct.as_ref().map(|d| d.node.clone()), Some(node));
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ let undone = h.state().scene.bundle.read_marks("l6", "c6").unwrap()[0]
+ .as_stroke()
+ .unwrap()
+ .clone();
+ assert_eq!(undone.samples, before.samples);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn the_inspector_adds_effects_and_adjustments_and_previews_them_without_history() {
+ use klad_core::doc::Blend;
+ use klad_core::history::{Stack, entries};
+ use klad_core::look::{Adjustment, Effect};
+ let path = sample("looks");
+ let mut h = harness(editor(&path), vec2(1440.0, 1400.0));
+ [
+ (Pane::Inspector, false),
+ (Pane::Notes, true),
+ (Pane::History, true),
+ (Pane::Layers, true),
+ (Pane::Tool, true),
+ ]
+ .into_iter()
+ .for_each(|(pane, collapsed)| {
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(pane) {
+ p.collapsed = collapsed;
+ }
+ });
+ activate(&mut h, "lines");
+ h.state_mut().invoke(Cmd::NewPaintLayer).unwrap();
+ h.run_steps(3);
+ let active = |h: &Harness<'static, Editor>| h.state().scene.active_layer().unwrap().clone();
+ let light = active(&h).id;
+ h.state_mut()
+ .apply(
+ parse_lines(&format!(
+ r#"{{"op":"set","id":"{light}","blend":"add","effects":[{{"glow":{{"radius":24}}}}]}}"#
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ h.run_steps(3);
+ assert_eq!(active(&h).blend, Blend::Add);
+ assert!(matches!(active(&h).effects[..], [Effect::Glow(_)]));
+ h.get_by_label_contains("applied after the ones above").click();
+ h.run_steps(2);
+ h.get_by_label("outline").click();
+ h.run_steps(3);
+ assert!(matches!(active(&h).effects[..], [Effect::Glow(_), Effect::Outline(_)]));
+ let steps = entries(&h.state().scene.bundle, Stack::Undo).unwrap().len();
+ let rev = h.state().scene.bundle.doc.rev;
+ let mut wide = active(&h);
+ if let Effect::Glow(g) = &mut wide.effects[0] {
+ g.radius = 60.0;
+ }
+ h.state_mut().preview_look(wide).unwrap();
+ h.run_steps(2);
+ assert!(matches!(&active(&h).effects[0], Effect::Glow(g) if g.radius == 60.0));
+ assert_eq!(h.state().scene.bundle.doc.rev, rev, "a preview is not an edit");
+ h.state_mut().end_look_preview().unwrap();
+ assert!(matches!(&active(&h).effects[0], Effect::Glow(g) if g.radius == 24.0));
+ assert_eq!(entries(&h.state().scene.bundle, Stack::Undo).unwrap().len(), steps);
+ checked_audit(&mut h);
+ h.state_mut().invoke(Cmd::NewAdjustLayer).unwrap();
+ h.run_steps(3);
+ assert!(matches!(active(&h).adjustment(), Some(Adjustment::Curves(_))));
+ h.get_by_label_contains("what this adjustment layer does").click();
+ h.run_steps(2);
+ h.get_by_label("levels").click();
+ h.run_steps(3);
+ assert!(matches!(active(&h).adjustment(), Some(Adjustment::Levels(_))));
+ checked_audit(&mut h);
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ assert!(matches!(active(&h).adjustment(), Some(Adjustment::Curves(_))));
+ h.state_mut()
+ .apply(parse_lines(r##"{"op":"add","layer":{"id":"shafts","kind":"vector","name":"shafts","blend":"screen","cels":[{"frame":0,"nodes":[{"id":"rays1","type":"rays","x":200,"y":0,"fill":"#fff0c0"}]}]}}"##).unwrap())
+ .unwrap();
+ activate(&mut h, "shafts");
+ h.state_mut().tool = Tool::Select;
+ h.state_mut().selection = Some("rays1".into());
+ h.run_steps(3);
+ assert!(h.query_all(By::new().label_contains("rays")).count() > 0);
+ checked_audit(&mut h);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn checked_audit(h: &mut Harness<'static, Editor>) {
+ h.run_steps(2);
+ assert!(audit(h, "effects and adjustments in the inspector") > 20);
+}
+
+#[test]
+#[ignore = "timing: KLAD_HEAVY_SIZE=4096 cargo test --release -p klad-app heavy_edits -- --ignored --nocapture"]
+fn heavy_edits_and_revisits_keep_the_ui_free() {
+ let stress = std::env::temp_dir().join(format!("draw-ui-heavy-edit-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&stress);
+ let exe = std::env::current_exe().unwrap();
+ let draw = exe.parent().and_then(Path::parent).unwrap().join("klad");
+ let size = std::env::var("KLAD_HEAVY_SIZE").unwrap_or_else(|_| "2048".into());
+ let made = std::process::Command::new(&draw)
+ .args(["stress", stress.to_str().unwrap(), "--frames", "12", "--size", &size])
+ .output()
+ .unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+ let mut h = harness(editor(&stress), vec2(1600.0, 1000.0));
+ let wait = |h: &mut Harness<'static, Editor>| {
+ let start = std::time::Instant::now();
+ while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(120) {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ }
+ start.elapsed().as_millis()
+ };
+ wait(&mut h);
+ [2u32, 4].into_iter().for_each(|f| {
+ h.state_mut().go_to(f).unwrap();
+ wait(&mut h);
+ });
+ h.state_mut().go_to(2).unwrap();
+ let revisit = wait(&mut h);
+ settle(&mut h, |ed| ed.buffering.job_idle());
+ let layer = h.state().scene.bundle.doc.layers[3].id.clone();
+ let edit = |h: &mut Harness<'static, Editor>, opacity: f32| {
+ h.state_mut()
+ .apply(parse_lines(&format!(r#"{{"op":"set","id":"{layer}","opacity":{opacity}}}"#)).unwrap())
+ .unwrap();
+ (0..40)
+ .map(|_| {
+ let t = std::time::Instant::now();
+ h.run_steps(1);
+ let spent = t.elapsed().as_secs_f64() * 1000.0;
+ std::thread::sleep(std::time::Duration::from_millis(8));
+ spent
+ })
+ .fold(0.0f64, f64::max)
+ };
+ let slowest: Vec<f64> = [0.9f32, 0.8, 1.0].iter().map(|o| edit(&mut h, *o)).collect();
+ eprintln!(
+ "{size} px: a frame seen before is drawable again in {revisit} ms; slowest UI frame in the 40 after each of three edits {slowest:.1?} ms"
+ );
+ let _ = std::fs::remove_dir_all(&stress);
+}
+
+#[test]
+fn a_closed_panel_comes_back_from_the_strip() {
+ let path = sample("panels");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ h.state_mut().invoke(Cmd::InspectorPane).unwrap();
+ h.run_steps(2);
+ assert!(!h.state().settings.layout.is_open(Pane::Inspector));
+ h.get_by_role_and_label(Role::Button, theme::icon::SIDEBAR).click();
+ h.run_steps(2);
+ h.get_by_role_and_label(Role::CheckBox, Pane::Inspector.title()).click();
+ h.run_steps(3);
+ assert!(h.state().settings.layout.is_open(Pane::Inspector));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn strokes_select_move_and_copy_across_cmd_clicked_layers() {
+ let path = sample("across");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ h.state_mut()
+ .apply(
+ parse_lines(r##"{"op":"stroke","layer":"l5","path":"M50 60 L280 210","size":20,"color":"#d08040"}"##)
+ .unwrap(),
+ )
+ .unwrap();
+ activate(&mut h, "lines");
+ let row = |h: &Harness<'static, Editor>, name: &str| {
+ h.query_all(By::new().role(Role::Button).label(name))
+ .map(|n| n.rect())
+ .min_by(|a, b| a.top().total_cmp(&b.top()))
+ .unwrap()
+ };
+ let colour = row(&h, "colour");
+ let at = egui::pos2(colour.right() - 70.0, colour.center().y);
+ h.event(egui::Event::ModifiersChanged(Modifiers::COMMAND));
+ h.hover_at(at);
+ h.run_steps(1);
+ [true, false].into_iter().for_each(|pressed| {
+ h.event(egui::Event::PointerButton {
+ pos: at,
+ button: egui::PointerButton::Primary,
+ pressed,
+ modifiers: Modifiers::COMMAND,
+ });
+ h.run_steps(1);
+ });
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(2);
+ assert_eq!(
+ h.state().scene.active_layer().unwrap().name,
+ "lines",
+ "cmd click keeps the active layer"
+ );
+ assert_eq!(h.state().also, vec!["l5".to_string()]);
+ h.key_press(Key::S);
+ h.run_steps(2);
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ let at = |x: f32, y: f32| rect.min + view.to_screen(egui::Vec2::new(x, y), rect.size());
+ let corners = [(20.0, 20.0), (440.0, 20.0), (440.0, 340.0), (20.0, 340.0), (20.0, 24.0)];
+ h.hover_at(at(corners[0].0, corners[0].1));
+ h.run_steps(1);
+ h.drag_at(at(corners[0].0, corners[0].1));
+ h.run_steps(1);
+ corners.iter().skip(1).for_each(|&(x, y)| {
+ (1..=4).for_each(|_| {
+ h.hover_at(at(x, y));
+ h.run_steps(1);
+ });
+ });
+ h.drop_at(at(20.0, 24.0));
+ h.run_steps(2);
+ let picked = h.state().picked.clone().expect("a selection on both layers");
+ assert_eq!(
+ (picked.ids.len(), picked.more.len(), picked.more[0].ids.len()),
+ (2, 1, 1)
+ );
+ let starts = |h: &Harness<'static, Editor>| -> Vec<(f32, f32)> {
+ ["l6", "l5"]
+ .iter()
+ .map(|layer| {
+ let doc = &h.state().scene.bundle.doc;
+ let cel = doc.layer(layer).unwrap().content_at(0).unwrap().id.clone();
+ h.state().scene.bundle.read_marks(layer, &cel).unwrap()[0]
+ .as_stroke()
+ .unwrap()
+ .samples[0]
+ .pos()
+ })
+ .collect()
+ };
+ let before = starts(&h);
+ let corners = h.state().picked_corners().unwrap().1;
+ let middle = rect.min + view.to_screen((corners[0] + corners[2]) / 2.0, rect.size());
+ drag(&mut h, middle, middle + vec2(40.0 * view.zoom, 0.0));
+ settle(&mut h, |ed| ed.drag.is_none());
+ h.run_steps(3);
+ let after = starts(&h);
+ before.iter().zip(&after).for_each(|(b, a)| {
+ assert!(
+ (a.0 - b.0 - 40.0).abs() < 1.5 && (a.1 - b.1).abs() < 1.5,
+ "{b:?} -> {a:?}"
+ );
+ });
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ assert_eq!(starts(&h), before, "one undo puts both layers back");
+ h.state_mut().invoke(Cmd::Redo).unwrap();
+ h.run_steps(2);
+ let counts = |h: &Harness<'static, Editor>| -> Vec<usize> {
+ ["l6", "l5"]
+ .iter()
+ .map(|layer| {
+ let doc = &h.state().scene.bundle.doc;
+ let cel = doc.layer(layer).unwrap().content_at(0).unwrap().id.clone();
+ h.state().scene.bundle.read_marks(layer, &cel).unwrap().len()
+ })
+ .collect()
+ };
+ let had = counts(&h);
+ h.state_mut().select_all_strokes();
+ h.state_mut().invoke(Cmd::DuplicateInPlace).unwrap();
+ h.run_steps(3);
+ assert_eq!(
+ counts(&h),
+ vec![had[0] * 2, had[1] * 2],
+ "each layer gets its own copies"
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_lasso_cut_spans_the_selected_layers() {
+ use klad_core::markedit::{LassoAction, MarkTransform};
+ let path = sample("across-cut");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ h.state_mut()
+ .apply(
+ parse_lines(r##"{"op":"stroke","layer":"l5","path":"M20 200 L480 200","size":20,"color":"#d08040"}"##)
+ .unwrap(),
+ )
+ .unwrap();
+ activate(&mut h, "lines");
+ let cel = |h: &Harness<'static, Editor>, layer: &str| {
+ h.state()
+ .scene
+ .bundle
+ .doc
+ .layer(layer)
+ .unwrap()
+ .content_at(0)
+ .unwrap()
+ .id
+ .clone()
+ };
+ let (lines, colour) = (cel(&h, "l6"), cel(&h, "l5"));
+ let count =
+ |h: &Harness<'static, Editor>, layer: &str, c: &str| h.state().scene.bundle.read_marks(layer, c).unwrap().len();
+ let had = (count(&h, "l6", &lines), count(&h, "l5", &colour));
+ let polygon = vec![[0.0, 0.0], [200.0, 0.0], [200.0, 384.0], [0.0, 384.0]];
+ h.state_mut().tool = Tool::Strokes;
+ h.state_mut().picked = Some(super::Picked {
+ cel: lines.clone(),
+ ids: Vec::new(),
+ cut: Some(polygon),
+ more: vec![super::Part {
+ layer: "l5".into(),
+ cel: colour.clone(),
+ ids: Vec::new(),
+ }],
+ });
+ h.state_mut().refresh_cut();
+ h.state_mut()
+ .edit_picked(LassoAction::Transform(MarkTransform {
+ y: 30.0,
+ ..Default::default()
+ }))
+ .unwrap();
+ h.run_steps(2);
+ assert!(
+ count(&h, "l6", &lines) > had.0 && count(&h, "l5", &colour) > had.1,
+ "both layers were cut"
+ );
+ let picked = h.state().picked.clone().unwrap();
+ assert!(
+ !picked.ids.is_empty() && !picked.more[0].ids.is_empty(),
+ "the cut parts stay selected"
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+fn canvas_at(h: &Harness<'static, Editor>, x: f32, y: f32) -> egui::Pos2 {
+ let view = h.state().view.unwrap();
+ let rect = h.state().canvas_rect;
+ rect.min + view.to_screen(egui::Vec2::new(x, y), rect.size())
+}
+
+#[test]
+fn rectangles_and_ellipses_drag_onto_a_vector_layer() {
+ use klad_core::doc::Shape;
+ let path = sample("shape-tool");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "shapes");
+ h.key_press(Key::U);
+ h.run_steps(2);
+ assert_eq!(h.state().tool, Tool::Shape);
+ let nodes = |h: &Harness<'static, Editor>| {
+ h.state().scene.bundle.doc.find_layer("shapes").unwrap().cels()[0]
+ .nodes
+ .clone()
+ };
+ let had = nodes(&h).len();
+ {
+ let ed = h.state_mut();
+ ed.pen_fill = true;
+ ed.pen_stroke = true;
+ ed.color = [0.8, 0.2, 0.1, 1.0];
+ ed.second = [0.1, 0.2, 0.8, 1.0];
+ }
+ h.run_steps(3);
+ let (a, b) = (canvas_at(&h, 200.0, 100.0), canvas_at(&h, 280.0, 140.0));
+ drag(&mut h, a, b);
+ h.run_steps(2);
+ let made = nodes(&h);
+ assert_eq!(made.len(), had + 1);
+ assert_eq!(
+ made[had].fill,
+ Some(klad_core::doc::Paint::Solid(crate::color::hex([0.8, 0.2, 0.1, 1.0]))),
+ "the fill takes the first colour"
+ );
+ assert_eq!(
+ made[had].stroke.as_ref().map(|s| s.paint.clone()),
+ Some(klad_core::doc::Paint::Solid(crate::color::hex([0.1, 0.2, 0.8, 1.0]))),
+ "the outline takes the second colour"
+ );
+ match &made[had].shape {
+ Shape::Rect { x, y, w, h, .. } => {
+ assert!((x - 200.0).abs() < 1.5 && (y - 100.0).abs() < 1.5, "{x},{y}");
+ assert!((w - 80.0).abs() < 1.5 && (h - 40.0).abs() < 1.5, "{w}x{h}");
+ }
+ other => panic!("{other:?}"),
+ }
+ h.state_mut().shapes.kind = super::make::ShapeKind::Ellipse;
+ h.run_steps(3);
+ h.event(egui::Event::ModifiersChanged(Modifiers::SHIFT));
+ let (a, b) = (canvas_at(&h, 300.0, 200.0), canvas_at(&h, 340.0, 220.0));
+ drag(&mut h, a, b);
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(2);
+ match &nodes(&h)[had + 1].shape {
+ Shape::Ellipse { cx, cy, rx, ry } => {
+ assert!((rx - ry).abs() < 0.01 && (rx - 20.0).abs() < 1.5, "a circle: {rx} {ry}");
+ assert!((cx - 320.0).abs() < 1.5 && (cy - 220.0).abs() < 1.5, "{cx},{cy}");
+ }
+ other => panic!("{other:?}"),
+ }
+ checked_audit(&mut h);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn a_selected_shape_turns_into_a_repeat_and_back() {
+ use klad_core::doc::Shape;
+ let path = sample("wrap");
+ let mut h = harness(editor(&path), vec2(1440.0, 1200.0));
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::Inspector) {
+ p.collapsed = false;
+ }
+ activate(&mut h, "shapes");
+ let rect = h.state().scene.bundle.doc.find_layer("shapes").unwrap().cels()[0].nodes[0]
+ .id
+ .clone();
+ h.state_mut().tool = Tool::Select;
+ h.state_mut().selection = Some(rect.clone());
+ h.run_steps(2);
+ h.get_by_label_contains("repeat it").click();
+ h.run_steps(3);
+ let made = h.state().selection.clone().unwrap();
+ let doc = &h.state().scene.bundle.doc;
+ let Some(klad_core::doc::Item::Node(_, _, node)) = doc.item(&made) else {
+ panic!()
+ };
+ assert!(matches!(&node.shape, Shape::Repeat(r) if r.count == 4 && r.children[0].id == rect));
+ assert!(
+ h.query_all(By::new().label_contains("copies")).count() > 0,
+ "the inspector shows the repeat"
+ );
+ checked_audit(&mut h);
+ h.get_by_label_contains("take the shapes out").click();
+ h.run_steps(3);
+ let doc = &h.state().scene.bundle.doc;
+ assert!(doc.item(&made).is_none(), "the repeat is gone");
+ let layer = doc.find_layer("shapes").unwrap();
+ assert_eq!(layer.cels()[0].nodes[0].id, rect, "the rect is back where it was");
+ assert_eq!(h.state().selection.as_deref(), Some(rect.as_str()));
+ h.state_mut().invoke(Cmd::MakeMirror).unwrap();
+ h.run_steps(2);
+ let mirror = h.state().selection.clone().unwrap();
+ h.key_press(Key::Delete);
+ h.run_steps(2);
+ let doc = &h.state().scene.bundle.doc;
+ assert!(
+ doc.item(&mirror).is_none() && doc.item(&rect).is_none(),
+ "Delete removes a generator with its shapes"
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ let doc = &h.state().scene.bundle.doc;
+ assert!(
+ matches!(doc.item(&rect), Some(klad_core::doc::Item::Node(_, _, n)) if matches!(n.shape, Shape::Rect { .. }))
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn mirror_painting_makes_two_plain_strokes_in_one_step() {
+ let path = sample("mirror-paint");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "colour");
+ h.state_mut().invoke(Cmd::Symmetry).unwrap();
+ assert_eq!(h.state().mirror, Some(256.0));
+ h.state_mut().tool = Tool::Brush;
+ let marks = |h: &Harness<'static, Editor>| h.state().scene.active_marks().to_vec();
+ let had = marks(&h).len();
+ let (a, b) = (canvas_at(&h, 60.0, 80.0), canvas_at(&h, 160.0, 200.0));
+ drag(&mut h, a, b);
+ settle(&mut h, |ed| ed.live.is_none());
+ h.run_steps(2);
+ let after = marks(&h);
+ assert_eq!(after.len(), had + 2, "the stroke and its mirror image");
+ let (one, two) = (after[had].as_stroke().unwrap(), after[had + 1].as_stroke().unwrap());
+ let (p, q) = (one.samples[0].pos(), two.samples[0].pos());
+ assert!(
+ (p.0 + q.0 - 512.0).abs() < 0.2 && (p.1 - q.1).abs() < 0.01,
+ "{p:?} {q:?}"
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(2);
+ assert_eq!(marks(&h).len(), had, "one undo takes both");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn holding_d_builds_a_plane_per_layer_and_the_inspector_sets_depth_and_fog() {
+ let path = sample("parallax");
+ let mut h = harness(editor(&path), vec2(1440.0, 1200.0));
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::Inspector) {
+ p.collapsed = false;
+ }
+ activate(&mut h, "sky");
+ h.state_mut()
+ .apply(
+ parse_lines(
+ r##"{"op":"set","id":"l0","depth":3}
+{"op":"atmosphere","color":"#a0b0c0"}"##,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ h.run_steps(3);
+ assert!(
+ h.query_all(By::new().label_contains("density")).count() > 0,
+ "the atmosphere shows for a plane"
+ );
+ checked_audit(&mut h);
+ let shown = h.state().scene.bundle.doc.layers.iter().filter(|l| l.visible).count();
+ h.key_down(Key::D);
+ settle(&mut h, |ed| !ed.depth.planes.is_empty());
+ h.key_up(Key::D);
+ assert_eq!(h.state().depth.planes.len(), shown);
+ assert!(h.state().depth.planes.iter().any(|(d, _)| *d == 3.0));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
+#[test]
+fn an_imported_picture_lands_on_its_own_layer_and_can_be_a_reference() {
+ let path = sample("picture");
+ let mut h = harness(editor(&path), vec2(1440.0, 1200.0));
+ if let Some(p) = h.state_mut().settings.layout.pane_mut(Pane::Inspector) {
+ p.collapsed = false;
+ }
+ activate(&mut h, "lines");
+ let rgba = klad_render::assets::Rgba {
+ width: 4,
+ height: 2,
+ pixels: vec![200; 32],
+ };
+ let png = klad_render::assets::encode_png(&rgba).unwrap();
+ h.state_mut().import_picture(&png, "/tmp/photo.png").unwrap();
+ h.run_steps(3);
+ let layer = h.state().scene.active_layer().unwrap().clone();
+ assert_eq!(layer.name, "photo");
+ assert_eq!(layer.cels()[0].nodes[0].type_name(), "image");
+ h.get_by_role_and_label(Role::CheckBox, "reference").click();
+ h.run_steps(3);
+ assert!(h.state().scene.active_layer().unwrap().reference);
+ let _ = std::fs::remove_dir_all(&path);
+}
diff --git a/crates/app/src/frames.rs b/crates/app/src/frames.rs
new file mode 100644
index 0000000..e0327ba
--- /dev/null
+++ b/crates/app/src/frames.rs
@@ -0,0 +1,378 @@
+use crate::composite::{FrameDone, FrameImage, Scene};
+use anyhow::Result;
+use klad_brush::BrushSet;
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+use std::sync::mpsc::{Receiver, TryRecvError, channel};
+use std::time::{Duration, Instant};
+
+pub const BUDGET: usize = 640 << 20;
+pub const HEAVY: usize = 512 << 20;
+
+pub type Notify = Arc<dyn Fn() + Send + Sync>;
+
+struct Entry {
+ bytes: usize,
+ used: u64,
+}
+
+struct Job {
+ key: u64,
+ frame: u32,
+ rx: Receiver<Result<FrameDone>>,
+}
+
+pub struct FrameCache {
+ pub budget: usize,
+ pub level: u32,
+ pub max_jobs: usize,
+ pub heavy: bool,
+ pub disk: Option<std::path::PathBuf>,
+ entries: BTreeMap<u64, Entry>,
+ uploads: Vec<FrameImage>,
+ drops: Vec<u64>,
+ jobs: Vec<Job>,
+ keys: BTreeMap<(u32, bool), u64>,
+ tick: u64,
+ notify: Notify,
+ pub error: Option<String>,
+}
+
+impl FrameCache {
+ pub fn new(notify: Notify) -> Self {
+ Self {
+ budget: BUDGET,
+ level: 0,
+ max_jobs: 2,
+ heavy: false,
+ disk: None,
+ entries: BTreeMap::new(),
+ uploads: Vec::new(),
+ drops: Vec::new(),
+ jobs: Vec::new(),
+ keys: BTreeMap::new(),
+ tick: 0,
+ notify,
+ error: None,
+ }
+ }
+
+ pub fn changed(&mut self) {
+ self.keys.clear();
+ }
+
+ pub fn set_level(&mut self, level: u32) {
+ if level != self.level {
+ self.level = level;
+ self.keys.clear();
+ }
+ }
+
+ pub fn key(&mut self, scene: &mut Scene, frame: u32, onion: bool, brushes: &BrushSet) -> u64 {
+ if let Some(key) = self.keys.get(&(frame, onion)) {
+ return *key;
+ }
+ let key = scene.frame_key(frame, onion, self.level, brushes.fingerprint());
+ self.keys.insert((frame, onion), key);
+ key
+ }
+
+ pub fn on_disk(&self, key: u64) -> bool {
+ self.disk
+ .as_deref()
+ .is_some_and(|dir| crate::composite::picture_path(dir, key).exists())
+ }
+
+ pub fn has(&self, key: u64) -> bool {
+ self.entries.contains_key(&key)
+ }
+
+ pub fn touch(&mut self, key: u64) {
+ self.tick += 1;
+ if let Some(entry) = self.entries.get_mut(&key) {
+ entry.used = self.tick;
+ }
+ }
+
+ pub fn pending(&self, key: u64) -> bool {
+ self.jobs.iter().any(|j| j.key == key)
+ }
+
+ pub fn jobs(&self) -> usize {
+ self.jobs.len()
+ }
+
+ pub fn len(&self) -> usize {
+ self.entries.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+
+ pub fn bytes(&self) -> usize {
+ self.entries.values().map(|e| e.bytes).sum()
+ }
+
+ pub fn request(&mut self, scene: &mut Scene, frame: u32, onion: bool, brushes: &BrushSet, urgent: bool) -> bool {
+ let key = self.key(scene, frame, onion, brushes);
+ if self.has(key) || self.pending(key) {
+ return true;
+ }
+ let limit = match self.heavy {
+ true => 1,
+ false => self.max_jobs + usize::from(urgent),
+ };
+ if self.jobs.len() >= limit {
+ return false;
+ }
+ let request = scene.frame_request(frame, onion, self.level, brushes);
+ let (tx, rx) = channel();
+ let notify = self.notify.clone();
+ std::thread::spawn(move || {
+ let _ = tx.send(crate::background().install(|| request.run()));
+ notify();
+ });
+ self.jobs.push(Job { key, frame, rx });
+ true
+ }
+
+ pub fn collect(&mut self, scene: &mut Scene) -> Vec<u32> {
+ let mut done = Vec::new();
+ let jobs = std::mem::take(&mut self.jobs);
+ self.jobs = jobs
+ .into_iter()
+ .filter_map(|job| match job.rx.try_recv() {
+ Ok(Ok(result)) => {
+ self.heavy |= result.loaded_bytes() > HEAVY;
+ let image = scene.absorb(result);
+ self.tick += 1;
+ self.entries.insert(
+ image.key,
+ Entry {
+ bytes: image.bytes(),
+ used: self.tick,
+ },
+ );
+ self.uploads.push(image);
+ done.push(job.frame);
+ None
+ }
+ Ok(Err(e)) => {
+ self.error = Some(format!("frame {}: {e:#}", job.frame));
+ None
+ }
+ Err(TryRecvError::Empty) => Some(job),
+ Err(TryRecvError::Disconnected) => {
+ self.error = Some(format!("the job for frame {} stopped", job.frame));
+ None
+ }
+ })
+ .collect();
+ done
+ }
+
+ fn remove(&mut self, key: u64) {
+ self.entries.remove(&key);
+ self.uploads.retain(|u| u.key != key);
+ self.drops.push(key);
+ }
+
+ pub fn prune(&mut self, keep: &BTreeSet<u64>) {
+ let mut total = self.bytes();
+ if total <= self.budget {
+ return;
+ }
+ let mut order: Vec<(u64, u64, usize)> = self
+ .entries
+ .iter()
+ .filter(|(k, _)| !keep.contains(*k))
+ .map(|(k, e)| (e.used, *k, e.bytes))
+ .collect();
+ order.sort();
+ order.into_iter().for_each(|(_, key, bytes)| {
+ if total > self.budget {
+ self.remove(key);
+ total -= bytes;
+ }
+ });
+ }
+
+ pub fn forget_unused(&mut self, live: &BTreeSet<u64>) -> usize {
+ let gone: Vec<u64> = self.entries.keys().filter(|k| !live.contains(*k)).copied().collect();
+ gone.iter().for_each(|k| self.remove(*k));
+ gone.len()
+ }
+
+ pub fn take(&mut self) -> (Vec<FrameImage>, Vec<u64>) {
+ (std::mem::take(&mut self.uploads), std::mem::take(&mut self.drops))
+ }
+}
+
+pub struct Player {
+ start: Instant,
+ first: u64,
+ pub from: u32,
+ pub to: u32,
+ pub fps: u32,
+ pub once: bool,
+ shown: Option<u64>,
+ pub drops: Vec<u32>,
+}
+
+impl Player {
+ pub fn new(now: Instant, frame: u32, (from, to): (u32, u32), fps: u32, once: bool) -> Self {
+ let first = match (from..=to).contains(&frame) && !(once && frame == to && from < to) {
+ true => (frame - from) as u64,
+ false => 0,
+ };
+ Self {
+ start: now,
+ first,
+ from,
+ to,
+ fps: fps.max(1),
+ once,
+ shown: None,
+ drops: Vec::new(),
+ }
+ }
+
+ fn len(&self) -> u64 {
+ (self.to - self.from + 1) as u64
+ }
+
+ pub fn index_at(&self, now: Instant) -> u64 {
+ let elapsed = now.saturating_duration_since(self.start).as_nanos();
+ self.first + (elapsed * self.fps as u128 / 1_000_000_000) as u64
+ }
+
+ fn due(&self, now: Instant) -> u64 {
+ match self.once {
+ true => self.index_at(now).min(self.len() - 1),
+ false => self.index_at(now),
+ }
+ }
+
+ pub fn finished(&self, now: Instant) -> bool {
+ let at = self.index_at(now);
+ self.once && at >= self.len() && (self.shown == Some(self.len() - 1) || at >= self.len() + self.fps as u64)
+ }
+
+ pub fn frame_of(&self, index: u64) -> u32 {
+ match self.once {
+ true => self.from + index.min(self.len() - 1) as u32,
+ false => self.from + (index % self.len()) as u32,
+ }
+ }
+
+ pub fn shown(&self) -> Option<u32> {
+ self.shown.map(|i| self.frame_of(i))
+ }
+
+ fn loop_of(&self, index: u64) -> usize {
+ ((index - self.first) / self.len()) as usize
+ }
+
+ pub fn tick(&mut self, now: Instant, mut ready: impl FnMut(u32) -> bool) -> Option<u32> {
+ let due = self.due(now);
+ if self.shown == Some(due) || !ready(self.frame_of(due)) {
+ return None;
+ }
+ let next = self.shown.map_or(self.first, |s| s + 1);
+ let loops = self.loop_of(due) + 1;
+ if self.drops.len() < loops {
+ self.drops.resize(loops, 0);
+ }
+ (next..due).for_each(|i| {
+ let at = self.loop_of(i);
+ self.drops[at] += 1;
+ });
+ self.shown = Some(due);
+ Some(self.frame_of(due))
+ }
+
+ pub fn ahead(&self, now: Instant, count: usize) -> Vec<u32> {
+ let due = self.due(now);
+ let mut seen = BTreeSet::new();
+ (due..due + count as u64)
+ .map(|i| self.frame_of(i))
+ .filter(|f| seen.insert(*f))
+ .collect()
+ }
+
+ pub fn next_in(&self, now: Instant) -> Duration {
+ let next = self.index_at(now) + 1 - self.first;
+ let at = self.start + Duration::from_nanos((next as u128 * 1_000_000_000 / self.fps as u128) as u64);
+ at.saturating_duration_since(now)
+ }
+
+ pub fn summary(&self) -> String {
+ let total: u32 = self.drops.iter().sum();
+ let recent: Vec<String> = self
+ .drops
+ .iter()
+ .enumerate()
+ .rev()
+ .take(3)
+ .rev()
+ .map(|(i, d)| format!("loop {}: {d}", i + 1))
+ .collect();
+ format!("dropped {total} ({})", recent.join(", "))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_clock_skips_rather_than_drifts_and_counts_drops_per_loop() {
+ let t0 = Instant::now();
+ let at = |ms: u64| t0 + Duration::from_millis(ms);
+ let mut p = Player::new(t0, 2, (0, 3), 10, false);
+ assert_eq!(p.tick(at(0), |_| true), Some(2));
+ assert_eq!(p.tick(at(50), |_| true), None);
+ assert_eq!(p.tick(at(100), |_| true), Some(3));
+ assert_eq!(p.tick(at(199), |_| true), None);
+ assert_eq!(p.tick(at(200), |_| true), Some(0));
+ assert_eq!(p.drops, [0]);
+ assert_eq!(p.tick(at(300), |f| f != 1), None);
+ assert_eq!(p.tick(at(410), |_| true), Some(2));
+ assert_eq!(p.drops, [1, 0]);
+ assert_eq!(p.tick(at(1000), |_| true), Some(0));
+ assert_eq!(p.drops, [1, 3, 2]);
+ assert_eq!(p.shown(), Some(0));
+ assert_eq!(p.next_in(at(1000)), Duration::from_millis(100));
+ assert_eq!(p.ahead(at(1000), 6), [0, 1, 2, 3]);
+ assert!(p.summary().starts_with("dropped 6"));
+ let outside = Player::new(t0, 9, (4, 7), 12, false);
+ assert_eq!(outside.frame_of(outside.index_at(t0)), 4);
+ }
+
+ #[test]
+ fn a_clip_that_plays_once_stops_on_its_last_frame() {
+ let t0 = Instant::now();
+ let at = |ms: u64| t0 + Duration::from_millis(ms);
+ let mut p = Player::new(t0, 5, (4, 7), 10, true);
+ assert_eq!(p.tick(at(0), |_| true), Some(5));
+ assert_eq!(p.tick(at(100), |_| true), Some(6));
+ assert_eq!(p.tick(at(200), |_| true), Some(7));
+ assert!(!p.finished(at(250)));
+ assert_eq!(p.tick(at(260), |_| true), None);
+ assert_eq!(p.ahead(at(260), 4), [7]);
+ assert!(p.finished(at(300)));
+ assert_eq!((p.shown(), p.drops.clone()), (Some(7), vec![0]));
+ let again = Player::new(t0, 7, (4, 7), 10, true);
+ assert_eq!(
+ again.frame_of(again.index_at(t0)),
+ 4,
+ "from its last frame it starts over"
+ );
+ let late = Player::new(t0, 4, (4, 7), 10, true);
+ assert!(
+ !late.finished(at(500)) && late.finished(at(1400)),
+ "a last frame that never came is not waited on"
+ );
+ }
+}
diff --git a/crates/app/src/gpu.rs b/crates/app/src/gpu.rs
new file mode 100644
index 0000000..3d1ab8f
--- /dev/null
+++ b/crates/app/src/gpu.rs
@@ -0,0 +1,583 @@
+use crate::composite::{FrameImage, Mix};
+use crate::stats::{Stats, lock};
+use egui_wgpu::wgpu;
+use half::f16;
+use klad_brush::TILE;
+use rayon::prelude::*;
+use std::collections::BTreeMap;
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
+
+pub const MIP_LEVELS: u32 = 9;
+
+struct Plane {
+ texture: wgpu::Texture,
+ uniform: wgpu::Buffer,
+ bind_group: wgpu::BindGroup,
+ size: (u32, u32),
+ levels: u32,
+}
+
+pub fn levels_for((width, height): (u32, u32)) -> u32 {
+ (32 - width.max(height).max(1).leading_zeros()).min(MIP_LEVELS)
+}
+
+pub fn mip_chain(tile: &[f16]) -> Vec<Vec<f16>> {
+ let mut levels: Vec<Vec<f16>> = Vec::new();
+ let mut side = TILE;
+ let mut current: Vec<f32> = tile.iter().map(|v| v.to_f32()).collect();
+ while side > 1 && levels.len() + 1 < MIP_LEVELS as usize {
+ let half = side / 2;
+ let next: Vec<f32> = (0..half * half * 4)
+ .map(|i| {
+ let (c, px) = (i % 4, i / 4);
+ let (x, y) = (px % half * 2, px / half * 2);
+ let at = |x: usize, y: usize| current[(y * side + x) * 4 + c];
+ (at(x, y) + at(x + 1, y) + at(x, y + 1) + at(x + 1, y + 1)) * 0.25
+ })
+ .collect();
+ levels.push(next.iter().map(|v| f16::from_f32(*v)).collect());
+ current = next;
+ side = half;
+ }
+ levels
+}
+
+pub struct CanvasGpu {
+ canvas_pipeline: wgpu::RenderPipeline,
+ over: wgpu::RenderPipeline,
+ multiply: wgpu::RenderPipeline,
+ screen: wgpu::RenderPipeline,
+ add: wgpu::RenderPipeline,
+ layout: wgpu::BindGroupLayout,
+ sampler: wgpu::Sampler,
+ canvas: Plane,
+ base: Plane,
+ tops: Vec<Plane>,
+ lift: Plane,
+ frames: BTreeMap<u64, Plane>,
+}
+
+fn texture(device: &wgpu::Device, (width, height): (u32, u32), levels: u32) -> wgpu::Texture {
+ texture_as(device, (width, height), levels, wgpu::TextureFormat::Rgba16Float)
+}
+
+fn texture_as(
+ device: &wgpu::Device,
+ (width, height): (u32, u32),
+ levels: u32,
+ format: wgpu::TextureFormat,
+) -> wgpu::Texture {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("plane"),
+ size: wgpu::Extent3d {
+ width: width.max(1),
+ height: height.max(1),
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: levels,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ })
+}
+
+fn plane(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ sampler: &wgpu::Sampler,
+ size: (u32, u32),
+ uniform_bytes: u64,
+ levels: u32,
+) -> Plane {
+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("plane uniform"),
+ size: uniform_bytes,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let texture = texture(device, size, levels);
+ let bind_group = bind(device, layout, &uniform, &texture, sampler);
+ Plane {
+ texture,
+ uniform,
+ bind_group,
+ size,
+ levels,
+ }
+}
+
+fn bind(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ uniform: &wgpu::Buffer,
+ texture: &wgpu::Texture,
+ sampler: &wgpu::Sampler,
+) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("plane"),
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&texture.create_view(&Default::default())),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(sampler),
+ },
+ ],
+ })
+}
+
+fn pipeline(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ format: wgpu::TextureFormat,
+ source: &str,
+ blend: Option<wgpu::BlendState>,
+) -> wgpu::RenderPipeline {
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("plane"),
+ source: wgpu::ShaderSource::Wgsl(source.into()),
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("plane"),
+ bind_group_layouts: &[Some(layout)],
+ immediate_size: 0,
+ });
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("plane"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &module,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &module,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format,
+ blend,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+}
+
+impl CanvasGpu {
+ pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, size: (u32, u32)) -> Self {
+ let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility,
+ ty,
+ count: None,
+ };
+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("plane"),
+ entries: &[
+ entry(
+ 0,
+ wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
+ wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ ),
+ entry(
+ 1,
+ wgpu::ShaderStages::FRAGMENT,
+ wgpu::BindingType::Texture {
+ multisampled: false,
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ },
+ ),
+ entry(
+ 2,
+ wgpu::ShaderStages::FRAGMENT,
+ wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ ),
+ ],
+ });
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("plane"),
+ mag_filter: wgpu::FilterMode::Nearest,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: wgpu::MipmapFilterMode::Linear,
+ ..Default::default()
+ });
+ let part = |src_factor, dst_factor| wgpu::BlendComponent {
+ src_factor,
+ dst_factor,
+ operation: wgpu::BlendOperation::Add,
+ };
+ use wgpu::BlendFactor as F;
+ let over_alpha = part(F::One, F::OneMinusSrcAlpha);
+ let quad = |color, alpha| {
+ pipeline(
+ device,
+ &layout,
+ format,
+ include_str!("quad.wgsl"),
+ Some(wgpu::BlendState { color, alpha }),
+ )
+ };
+ Self {
+ canvas_pipeline: pipeline(device, &layout, format, include_str!("canvas.wgsl"), None),
+ over: quad(part(F::One, F::OneMinusSrcAlpha), over_alpha),
+ multiply: quad(part(F::Zero, F::Src), part(F::Zero, F::One)),
+ screen: quad(part(F::One, F::OneMinusSrc), over_alpha),
+ add: quad(part(F::One, F::One), part(F::One, F::One)),
+ canvas: plane(device, &layout, &sampler, size, 48, levels_for(size)),
+ base: plane(device, &layout, &sampler, size, 48, levels_for(size)),
+ tops: Vec::new(),
+ lift: plane(device, &layout, &sampler, (1, 1), 80, 1),
+ frames: BTreeMap::new(),
+ layout,
+ sampler,
+ }
+ }
+
+ fn put_frame(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, image: &FrameImage) {
+ let size = (image.width, image.height);
+ let levels = image.mips.len() as u32;
+ let texture = texture_as(device, size, levels, wgpu::TextureFormat::Rgba8Unorm);
+ image.mips.iter().enumerate().for_each(|(level, pixels)| {
+ let (w, h) = ((size.0 >> level).max(1), (size.1 >> level).max(1));
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &texture,
+ mip_level: level as u32,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ pixels,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(w * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: w,
+ height: h,
+ depth_or_array_layers: 1,
+ },
+ );
+ });
+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("frame uniform"),
+ size: 48,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let bind_group = bind(device, &self.layout, &uniform, &texture, &self.sampler);
+ self.frames.insert(
+ image.key,
+ Plane {
+ texture,
+ uniform,
+ bind_group,
+ size,
+ levels,
+ },
+ );
+ }
+
+ fn resize(&mut self, device: &wgpu::Device, which: Which, size: (u32, u32)) {
+ let target = match which {
+ Which::Canvas => &mut self.canvas,
+ Which::Base => &mut self.base,
+ Which::Top(i) => &mut self.tops[i],
+ Which::Lift => &mut self.lift,
+ };
+ let levels = match which {
+ Which::Lift => 1,
+ _ => levels_for(size),
+ };
+ target.texture = texture(device, size, levels);
+ target.bind_group = bind(device, &self.layout, &target.uniform, &target.texture, &self.sampler);
+ target.size = size;
+ target.levels = levels;
+ }
+
+ fn ensure_tops(&mut self, device: &wgpu::Device, count: usize, size: (u32, u32)) {
+ while self.tops.len() < count {
+ let plane = plane(device, &self.layout, &self.sampler, size, 80, levels_for(size));
+ self.tops.push(plane);
+ }
+ (0..self.tops.len()).for_each(|i| {
+ if self.tops[i].size != size {
+ self.resize(device, Which::Top(i), size);
+ }
+ });
+ }
+
+ fn pipeline_for(&self, mix: Mix) -> &wgpu::RenderPipeline {
+ match mix {
+ Mix::Over => &self.over,
+ Mix::Multiply => &self.multiply,
+ Mix::Screen => &self.screen,
+ Mix::Add => &self.add,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+enum Which {
+ Canvas,
+ Base,
+ Top(usize),
+ Lift,
+}
+
+type Upload = (usize, Vec<f16>);
+
+fn upload_level(queue: &wgpu::Queue, plane: &Plane, level: u32, (x, y): (u32, u32), side: u32, pixels: &[f16]) {
+ let (w, h) = ((plane.size.0 >> level).max(1), (plane.size.1 >> level).max(1));
+ if x >= w || y >= h {
+ return;
+ }
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &plane.texture,
+ mip_level: level,
+ origin: wgpu::Origin3d { x, y, z: 0 },
+ aspect: wgpu::TextureAspect::All,
+ },
+ bytemuck::cast_slice(pixels),
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(side * 8),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: side.min(w - x),
+ height: side.min(h - y),
+ depth_or_array_layers: 1,
+ },
+ );
+}
+
+fn upload_tiles(queue: &wgpu::Queue, plane: &Plane, cols: usize, tiles: &[Upload]) {
+ let chains: Vec<Vec<Vec<f16>>> = if plane.levels > 1 {
+ tiles.par_iter().map(|(_, tile)| mip_chain(tile)).collect()
+ } else {
+ tiles.iter().map(|_| Vec::new()).collect()
+ };
+ tiles.iter().zip(&chains).for_each(|((index, tile), chain)| {
+ let (tx, ty) = ((index % cols) as u32, (index / cols) as u32);
+ upload_level(queue, plane, 0, (tx * TILE as u32, ty * TILE as u32), TILE as u32, tile);
+ chain
+ .iter()
+ .enumerate()
+ .take(plane.levels as usize - 1)
+ .for_each(|(k, pixels)| {
+ let level = k as u32 + 1;
+ let side = TILE as u32 >> level;
+ upload_level(queue, plane, level, (tx * side, ty * side), side, pixels);
+ });
+ });
+}
+
+fn upload_image(queue: &wgpu::Queue, plane: &Plane, (width, height): (u32, u32), pixels: &[f16]) {
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &plane.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ bytemuck::cast_slice(pixels),
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(width * 8),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+}
+
+pub struct QuadDraw {
+ pub uniform: [f32; 20],
+ pub tiles: Mutex<Vec<(usize, Vec<f16>)>>,
+ pub image: Mutex<Option<(u32, u32, Vec<f16>)>>,
+}
+
+pub fn quad_uniform(view: &[f32; 12], affine: [f32; 6], opacity: f32, rect: [f32; 4]) -> [f32; 20] {
+ let [a, b, c, d, e, f] = affine;
+ [
+ view[0], view[1], view[2], view[3], view[4], view[5], view[6], view[7], a, b, c, d, e, f, opacity, 0.0,
+ rect[0], rect[1], rect[2], rect[3],
+ ]
+}
+
+pub struct CanvasPaint {
+ pub uniform: [f32; 12],
+ pub uploads: Mutex<Vec<(usize, Vec<f16>)>>,
+ pub size: (u32, u32),
+ pub cols: usize,
+ pub pending: Option<Instant>,
+ pub stats: Arc<Mutex<Stats>>,
+ pub base: Mutex<Vec<(usize, Vec<f16>)>>,
+ pub tops: Vec<(Mix, QuadDraw)>,
+ pub lift: Option<QuadDraw>,
+ pub lifting: bool,
+ pub show: Option<u64>,
+ pub frame_uploads: Mutex<Vec<FrameImage>>,
+ pub frame_drops: Vec<u64>,
+}
+
+impl egui_wgpu::CallbackTrait for CanvasPaint {
+ fn prepare(
+ &self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ _screen: &egui_wgpu::ScreenDescriptor,
+ _encoder: &mut wgpu::CommandEncoder,
+ resources: &mut egui_wgpu::CallbackResources,
+ ) -> Vec<wgpu::CommandBuffer> {
+ let Some(gpu) = resources.get_mut::<CanvasGpu>() else {
+ return Vec::new();
+ };
+ if gpu.canvas.size != self.size {
+ gpu.resize(device, Which::Canvas, self.size);
+ }
+ if gpu.base.size != self.size {
+ gpu.resize(device, Which::Base, self.size);
+ }
+ queue.write_buffer(&gpu.base.uniform, 0, bytemuck::cast_slice(&self.uniform));
+ upload_tiles(queue, &gpu.base, self.cols, &std::mem::take(&mut *lock(&self.base)));
+ if !self.tops.is_empty() {
+ gpu.ensure_tops(device, self.tops.len(), self.size);
+ }
+ queue.write_buffer(&gpu.canvas.uniform, 0, bytemuck::cast_slice(&self.uniform));
+ let uploads = std::mem::take(&mut *lock(&self.uploads));
+ let start = Instant::now();
+ upload_tiles(queue, &gpu.canvas, self.cols, &uploads);
+ self.tops.iter().enumerate().for_each(|(k, (_, top))| {
+ let plane = &gpu.tops[k];
+ queue.write_buffer(&plane.uniform, 0, bytemuck::cast_slice(&top.uniform));
+ upload_tiles(queue, plane, self.cols, &std::mem::take(&mut *lock(&top.tiles)));
+ });
+ if let Some(lift) = &self.lift {
+ if let Some((w, h, pixels)) = lock(&lift.image).take() {
+ if gpu.lift.size != (w, h) {
+ gpu.resize(device, Which::Lift, (w, h));
+ }
+ upload_image(queue, &gpu.lift, (w, h), &pixels);
+ }
+ queue.write_buffer(&gpu.lift.uniform, 0, bytemuck::cast_slice(&lift.uniform));
+ }
+ self.frame_drops.iter().for_each(|key| {
+ gpu.frames.remove(key);
+ });
+ let images = std::mem::take(&mut *lock(&self.frame_uploads));
+ let started = Instant::now();
+ images.iter().for_each(|image| gpu.put_frame(device, queue, image));
+ if let Some(plane) = self.show.and_then(|key| gpu.frames.get(&key)) {
+ queue.write_buffer(&plane.uniform, 0, bytemuck::cast_slice(&self.uniform));
+ }
+ let mut stats = lock(&self.stats);
+ if !images.is_empty() {
+ stats.frame_upload_ms.push(started.elapsed().as_secs_f32() * 1000.0);
+ }
+ if !uploads.is_empty() {
+ stats.upload_ms.push(start.elapsed().as_secs_f32() * 1000.0);
+ }
+ if let Some(pending) = self.pending {
+ stats.latency_ms.push(pending.elapsed().as_secs_f32() * 1000.0);
+ }
+ Vec::new()
+ }
+
+ fn paint(
+ &self,
+ _info: egui::PaintCallbackInfo,
+ pass: &mut wgpu::RenderPass<'static>,
+ resources: &egui_wgpu::CallbackResources,
+ ) {
+ let Some(gpu) = resources.get::<CanvasGpu>() else {
+ return;
+ };
+ pass.set_pipeline(&gpu.canvas_pipeline);
+ let cached = self.show.filter(|_| !self.lifting).and_then(|key| gpu.frames.get(&key));
+ let under = match (self.lifting, cached) {
+ (true, _) => &gpu.base,
+ (false, Some(plane)) => plane,
+ (false, None) => &gpu.canvas,
+ };
+ pass.set_bind_group(0, &under.bind_group, &[]);
+ pass.draw(0..6, 0..1);
+ if !self.lifting {
+ return;
+ }
+ if self.lift.is_some() {
+ pass.set_pipeline(&gpu.over);
+ pass.set_bind_group(0, &gpu.lift.bind_group, &[]);
+ pass.draw(0..6, 0..1);
+ }
+ self.tops.iter().enumerate().for_each(|(k, (mix, _))| {
+ if let Some(plane) = gpu.tops.get(k) {
+ pass.set_pipeline(gpu.pipeline_for(*mix));
+ pass.set_bind_group(0, &plane.bind_group, &[]);
+ pass.draw(0..6, 0..1);
+ }
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mip_chains_average_down_to_one_pixel() {
+ let tile: Vec<f16> = (0..TILE * TILE)
+ .flat_map(|i| {
+ let (x, y) = (i % TILE, i / TILE);
+ let v = if (x + y) % 2 == 0 { 1.0 } else { 0.0 };
+ [v, v * 0.5, 0.25, 1.0].map(f16::from_f32)
+ })
+ .collect();
+ let chain = mip_chain(&tile);
+ assert_eq!(chain.len(), 8);
+ assert_eq!(
+ chain.iter().map(|l| l.len() / 4).collect::<Vec<_>>(),
+ [16384, 4096, 1024, 256, 64, 16, 4, 1]
+ );
+ assert!(
+ chain[0]
+ .chunks(4)
+ .all(|px| px[0].to_f32() == 0.5 && px[1].to_f32() == 0.25)
+ );
+ assert_eq!(
+ chain[7].iter().map(|v| v.to_f32()).collect::<Vec<_>>(),
+ [0.5, 0.25, 0.25, 1.0]
+ );
+ assert_eq!(
+ (levels_for((4096, 2048)), levels_for((256, 256)), levels_for((300, 10))),
+ (9, 9, 9)
+ );
+ assert_eq!((levels_for((200, 100)), levels_for((1, 1))), (8, 1));
+ }
+}
diff --git a/crates/app/src/home.rs b/crates/app/src/home.rs
new file mode 100644
index 0000000..68e5ffc
--- /dev/null
+++ b/crates/app/src/home.rs
@@ -0,0 +1,519 @@
+use crate::editor::{Editor, Want};
+use crate::gpu::CanvasGpu;
+use crate::picker;
+use crate::settings::{self, Settings};
+use crate::start::{self, Section, Start};
+use crate::theme;
+use anyhow::{Result, anyhow};
+use egui::RichText;
+use egui_wgpu::wgpu;
+use std::path::{Path, PathBuf};
+
+const WIDTH: f32 = 760.0;
+
+pub fn run(path: Option<PathBuf>) -> Result<()> {
+ let options = eframe::NativeOptions {
+ viewport: egui::ViewportBuilder::default()
+ .with_title(start::title(path.as_deref()))
+ .with_inner_size([1600.0, 1000.0]),
+ renderer: eframe::Renderer::Wgpu,
+ wgpu_options: egui_wgpu::WgpuConfiguration {
+ surface: egui_wgpu::SurfaceConfig {
+ present_mode: wgpu::PresentMode::AutoVsync,
+ desired_maximum_frame_latency: Some(1),
+ },
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ eframe::run_native(
+ "klad",
+ options,
+ Box::new(move |cc| Ok(Box::new(Home::new(cc, path.as_deref())?))),
+ )
+ .map_err(|e| anyhow!("{e}"))
+}
+
+pub(crate) struct Home {
+ pub(crate) editor: Option<Box<Editor>>,
+ pub(crate) start: Option<Start>,
+ pub(crate) settings: Settings,
+ pub(crate) settings_path: Option<PathBuf>,
+ gpu: Option<egui_wgpu::RenderState>,
+ themed: bool,
+}
+
+impl Home {
+ fn new(cc: &eframe::CreationContext, path: Option<&Path>) -> Result<Self> {
+ let gpu = cc
+ .wgpu_render_state
+ .clone()
+ .ok_or_else(|| anyhow!("the wgpu renderer is not available"))?;
+ let settings_path = settings::default_path();
+ let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();
+ let mut home = Self::with(settings, settings_path, Some(gpu));
+ home.begin(&cc.egui_ctx, path);
+ Ok(home)
+ }
+
+ pub(crate) fn with(
+ settings: Settings,
+ settings_path: Option<PathBuf>,
+ gpu: Option<egui_wgpu::RenderState>,
+ ) -> Self {
+ Self {
+ editor: None,
+ start: None,
+ settings,
+ settings_path,
+ gpu,
+ themed: false,
+ }
+ }
+
+ pub(crate) fn begin(&mut self, ctx: &egui::Context, path: Option<&Path>) {
+ let Some(path) = path else {
+ self.start = Some(Start::new(&self.settings, Section::New));
+ return;
+ };
+ if let Err(e) = self.open(ctx, path) {
+ let mut start = Start::new(&self.settings, Section::Open);
+ start.path = path.display().to_string();
+ start.error = Some(format!("opening {}: {e:#}", path.display()));
+ self.start = Some(start);
+ }
+ }
+
+ pub(crate) fn open(&mut self, ctx: &egui::Context, path: &Path) -> Result<()> {
+ let mut settings = self
+ .editor
+ .as_ref()
+ .map_or_else(|| self.settings.clone(), |e| e.settings.clone());
+ let mut editor = Editor::open(ctx.clone(), path)?;
+ settings.opened(path);
+ editor.settings = settings.clone();
+ editor.settings_path = self.settings_path.clone();
+ editor.settings_dirty = true;
+ if let Some(gpu) = &self.gpu {
+ gpu.renderer.write().callback_resources.insert(CanvasGpu::new(
+ &gpu.device,
+ gpu.target_format,
+ editor.scene.size(),
+ ));
+ }
+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(start::title(Some(path))));
+ self.settings = settings;
+ self.editor = Some(Box::new(editor));
+ self.start = None;
+ Ok(())
+ }
+
+ pub(crate) fn frame(&mut self, ui: &mut egui::Ui) {
+ let ctx = ui.ctx().clone();
+ let mut chosen = None;
+ match self.editor.as_mut() {
+ Some(editor) => {
+ editor.frame(ui);
+ match editor.wants.take() {
+ Some(Want::New) => self.start = Some(Start::new(&editor.settings, Section::New)),
+ Some(Want::Recent) => self.start = Some(Start::new(&editor.settings, Section::Recent)),
+ Some(Want::Open) if picker::NATIVE => {
+ let folder = editor.settings.drawings_folder();
+ chosen = picker::choose_folder(Some(&folder), "Open").and_then(|path| {
+ start::openable(&path)
+ .map_err(|e| editor.error(format!("{e:#}")))
+ .ok()
+ .map(|_| path)
+ });
+ }
+ Some(Want::Open) => self.start = Some(Start::new(&editor.settings, Section::Open)),
+ None => {}
+ }
+ if let Some(start) = self.start.as_mut() {
+ let height = (ctx.content_rect().height() - 120.0).clamp(320.0, 760.0);
+ let modal = egui::Modal::new(egui::Id::unique("start window")).show(&ctx, |ui| {
+ ui.set_width(WIDTH);
+ ui.set_height(height);
+ let back = ui
+ .horizontal(|ui| {
+ ui.heading("Drawings");
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ ui.button("Back to this drawing").clicked()
+ })
+ .inner
+ })
+ .inner;
+ ui.add_space(8.0);
+ chosen = start.ui(ui, &mut editor.settings);
+ back
+ });
+ editor.settings_dirty |= std::mem::take(&mut start.changed);
+ if modal.inner || modal.should_close() {
+ self.start = None;
+ }
+ }
+ }
+ None => {
+ if !self.themed {
+ theme::install(&ctx);
+ self.themed = true;
+ }
+ if (ctx.zoom_factor() - self.settings.ui_scale).abs() > 1e-3 {
+ ctx.set_zoom_factor(self.settings.ui_scale);
+ }
+ let start = self
+ .start
+ .get_or_insert_with(|| Start::new(&self.settings, Section::New));
+ egui::CentralPanel::default().show(ui, |ui| {
+ let margin = ((ui.available_width() - WIDTH) / 2.0).max(16.0);
+ ui.add_space(32.0);
+ ui.horizontal_top(|ui| {
+ ui.add_space(margin);
+ ui.vertical(|ui| {
+ ui.set_max_width(WIDTH);
+ ui.heading(RichText::new("klad").size(26.0));
+ ui.add_space(12.0);
+ chosen = start.ui(ui, &mut self.settings);
+ });
+ });
+ });
+ if std::mem::take(&mut start.changed)
+ && let Some(path) = &self.settings_path
+ && let Err(e) = self.settings.save(path)
+ {
+ start.error = Some(format!("saving your settings: {e:#}"));
+ }
+ }
+ }
+ if let Some(path) = chosen
+ && let Err(e) = self.open(&ctx, &path)
+ {
+ let message = format!("opening {}: {e:#}", path.display());
+ match (self.start.as_mut(), self.editor.as_mut()) {
+ (Some(start), _) => start.error = Some(message),
+ (None, Some(editor)) => editor.error(message),
+ (None, None) => {}
+ }
+ }
+ }
+}
+
+impl eframe::App for Home {
+ fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+ self.frame(ui);
+ }
+
+ fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
+ self.editor
+ .as_ref()
+ .map_or_else(|| theme::surround(self.settings.defaults.surround), |e| e.clear())
+ }
+
+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
+ if let Some(editor) = self.editor.as_mut() {
+ editor.take_tabs(ctx, raw_input);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::accesskit::Role;
+ use egui::{Key, Modifiers, vec2};
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::Queryable;
+ use klad_core::bundle::{Blank, Bundle};
+
+ fn folder(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-home-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::canonicalize(&dir).unwrap()
+ }
+
+ fn home(dir: &Path, documents: &[&Path]) -> Home {
+ let settings = Settings {
+ drawings: Some(dir.display().to_string()),
+ documents: documents.iter().map(|p| p.display().to_string()).collect(),
+ ..Settings::default()
+ };
+ Home::with(settings, None, None)
+ }
+
+ fn harness(home: Home) -> Harness<'static, Home> {
+ let mut h = Harness::builder()
+ .with_size(vec2(1280.0, 860.0))
+ .build_ui_state(|ui, home: &mut Home| home.frame(ui), home);
+ h.run_steps(3);
+ h
+ }
+
+ fn small() -> Blank {
+ Blank {
+ width: 320,
+ height: 200,
+ ..Blank::default()
+ }
+ }
+
+ fn opened(h: &Harness<'static, Home>) -> PathBuf {
+ h.state()
+ .editor
+ .as_ref()
+ .expect("an open drawing")
+ .scene
+ .bundle
+ .root
+ .clone()
+ }
+
+ #[test]
+ fn the_start_window_makes_a_drawing_like_draw_new_and_opens_it() {
+ let dir = folder("new");
+ let mut first = home(&dir, &[]);
+ first.begin(&egui::Context::default(), None);
+ let mut h = harness(first);
+ assert!(h.state().editor.is_none());
+ assert!(h.query_by_label("Drawings you open show up here.").is_some());
+ {
+ let start = h.state_mut().start.as_mut().unwrap();
+ assert_eq!(start.name, "untitled");
+ start.name.clear();
+ start.preset = None;
+ (start.width, start.height) = (320, 200);
+ start.paper = true;
+ }
+ h.get_by_role_and_label(Role::TextInput, "Name").type_text("rock study");
+ h.run_steps(2);
+ h.get_by_label("Create").click();
+ h.run_steps(3);
+ let made = dir.join("rock study.draw");
+ assert_eq!(opened(&h), made);
+ let cli = Bundle::blank(
+ dir.join("cli.draw"),
+ &Blank {
+ background: Some("#f4efe6".into()),
+ sketch: true,
+ ..small()
+ },
+ "cli",
+ )
+ .unwrap();
+ assert_eq!(Bundle::open(&made).unwrap().doc, cli.doc);
+ let kinds: Vec<(String, bool)> = cli.doc.layers.iter().map(|l| (l.name.clone(), l.visible)).collect();
+ assert_eq!(kinds, [("paint 1".to_string(), true), ("sketch".to_string(), true)]);
+ assert_eq!(h.state().settings.documents, [made.display().to_string()]);
+ let mut again = home(&dir, &[]);
+ again.begin(&egui::Context::default(), None);
+ assert_eq!(again.start.as_ref().unwrap().name, "untitled");
+ let mut taken = Start::new(&again.settings, Section::New);
+ taken.name = "rock study".into();
+ let refused = format!("{:#}", taken.create(&mut again.settings).unwrap_err());
+ assert!(refused.contains("already exists"), "{refused}");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn recent_reopens_a_drawing_and_greys_out_a_moved_one() {
+ let dir = folder("recent");
+ let (a, b) = (dir.join("ledge.draw"), dir.join("cave.draw"));
+ [&a, &b].iter().for_each(|p| {
+ Bundle::blank(p, &small(), "cli").unwrap();
+ });
+ std::fs::rename(&b, dir.join("cave moved.draw")).unwrap();
+ let mut first = home(&dir, &[&a, &b]);
+ first.begin(&egui::Context::default(), None);
+ let mut h = harness(first);
+ assert!(h.query_by_label("moved or deleted").is_some());
+ h.get_by_label("Remove cave").click();
+ h.run_steps(2);
+ assert_eq!(h.state().settings.documents, [a.display().to_string()]);
+ h.get_by_label("ledge").click();
+ h.run_steps(3);
+ assert_eq!(opened(&h), a);
+ assert!(h.state().start.is_none());
+ let mut missing = home(&dir, &[]);
+ missing.begin(&egui::Context::default(), Some(&dir.join("nowhere.draw")));
+ assert!(missing.editor.is_none());
+ let error = missing.start.as_ref().unwrap().error.clone().unwrap();
+ assert!(error.contains("nowhere.draw"), "{error}");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn cmd_n_and_cmd_o_in_the_editor_switch_drawings_and_back_keeps_this_one() {
+ let dir = folder("switch");
+ let (a, b) = (dir.join("first.draw"), dir.join("second.draw"));
+ [&a, &b].iter().for_each(|p| {
+ Bundle::blank(p, &small(), "cli").unwrap();
+ });
+ let mut first = home(&dir, &[]);
+ first.open(&egui::Context::default(), &a).unwrap();
+ let mut h = harness(first);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::N);
+ h.run_steps(3);
+ assert!(h.state().start.is_some());
+ h.get_by_label("Back to this drawing").click();
+ h.run_steps(3);
+ assert!(h.state().start.is_none());
+ assert_eq!(opened(&h), a);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::N);
+ h.run_steps(3);
+ {
+ let start = h.state_mut().start.as_mut().unwrap();
+ start.name = "third".into();
+ start.preset = None;
+ (start.width, start.height) = (320, 200);
+ }
+ h.run_steps(2);
+ h.get_by_label("Create").click();
+ h.run_steps(3);
+ assert_eq!(opened(&h), dir.join("third.draw"));
+ h.key_press_modifiers(Modifiers::COMMAND, Key::O);
+ h.run_steps(3);
+ h.get_by_role_and_label(Role::TextInput, "Or paste its path")
+ .type_text(&b.display().to_string());
+ h.run_steps(2);
+ h.get_by_label("Open").click();
+ h.run_steps(3);
+ assert_eq!(opened(&h), b);
+ let order: Vec<String> = h.state().settings.documents.clone();
+ assert_eq!(
+ order,
+ [&b, &dir.join("third.draw"), &a].map(|p| p.display().to_string())
+ );
+ h.state_mut().editor.as_mut().unwrap().wants = None;
+ h.get_by_label(theme::icon::FILE).click();
+ h.run_steps(2);
+ h.get_by_label(&format!("{} copy path", theme::icon::COPY)).click();
+ h.run_steps(1);
+ let copied = h
+ .output()
+ .platform_output
+ .commands
+ .iter()
+ .any(|c| matches!(c, egui::OutputCommand::CopyText(text) if *text == b.display().to_string()));
+ assert!(copied);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ #[ignore]
+ fn start_pictures() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let out = root.join("scratch/ui");
+ std::fs::create_dir_all(&out).unwrap();
+ let shown: Vec<PathBuf> = [
+ "samples/solids/solids.draw",
+ "samples/lantern/lantern-painted.draw",
+ "samples/creature/creature.draw",
+ ]
+ .iter()
+ .map(|p| std::fs::canonicalize(root.join(p)).expect("run just samples and build the painted lantern first"))
+ .collect();
+ let gone = PathBuf::from("/Users/you/Drawings/old sketch.draw");
+ let settings = Settings {
+ drawings: Some("~/Drawings".into()),
+ documents: shown
+ .iter()
+ .chain(std::iter::once(&gone))
+ .map(|p| p.display().to_string())
+ .collect(),
+ ..Settings::default()
+ };
+ let mut first = Home::with(settings, None, None);
+ first.begin(&egui::Context::default(), None);
+ let mut h = Harness::builder()
+ .with_size(vec2(1440.0, 900.0))
+ .wgpu()
+ .build_ui_state(|ui, home: &mut Home| home.frame(ui), first);
+ let started = std::time::Instant::now();
+ while started.elapsed() < std::time::Duration::from_secs(60) {
+ h.run_steps(2);
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ if shown.iter().all(|p| p.join(".cache/thumb.png").exists()) && started.elapsed().as_secs() > 2 {
+ break;
+ }
+ }
+ h.run_steps(6);
+ h.render().unwrap().save(out.join("start-1-window.png")).unwrap();
+ h.state_mut().open(&egui::Context::default(), &shown[1]).unwrap();
+ h.run_steps(6);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::N);
+ h.run_steps(8);
+ h.render()
+ .unwrap()
+ .save(out.join("start-2-over-the-editor.png"))
+ .unwrap();
+ }
+
+ #[test]
+ fn the_document_menu_shows_the_licence_and_the_notices() {
+ let dir = folder("about");
+ let path = dir.join("about.draw");
+ Bundle::blank(&path, &small(), "cli").unwrap();
+ let mut first = home(&dir, &[]);
+ first.open(&egui::Context::default(), &path).unwrap();
+ let mut h = harness(first);
+ h.get_by_label(theme::icon::FILE).click();
+ h.run_steps(2);
+ h.get_by_label(&format!("{} about and licences", theme::icon::INFO))
+ .click();
+ h.run_steps(3);
+ assert!(
+ h.query_by_label_contains("Source-available licence, copyright Indicode BV")
+ .is_some()
+ );
+ assert!(h.query_by_label("# Third-party notices").is_some());
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ #[ignore]
+ fn editor_picture() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let out = root.join("scratch/ui");
+ std::fs::create_dir_all(&out).unwrap();
+ let source = std::fs::canonicalize(root.join("samples/lantern/lantern-painted.draw")).expect(
+ "build it first: PAINTED=1 FORCE=1 bash samples/lantern/build.sh samples/lantern/lantern-painted.draw",
+ );
+ let dir = folder("editor-picture");
+ let path = dir.join("lantern.draw");
+ let copied = std::process::Command::new("cp")
+ .arg("-R")
+ .arg(&source)
+ .arg(&path)
+ .status()
+ .unwrap();
+ assert!(copied.success());
+ let mut bundle = Bundle::open(&path).unwrap();
+ bundle.doc.canvas.background = Some("#ebe6dc".into());
+ bundle.save().unwrap();
+ let gpu = egui_kittest::wgpu::create_render_state(
+ egui_kittest::wgpu::default_wgpu_setup(),
+ egui_wgpu::RendererOptions::PREDICTABLE,
+ );
+ let mut settings = Settings::default();
+ settings.layout.timeline_height = 190.0;
+ let mut first = Home::with(settings, None, Some(gpu.clone()));
+ first.open(&egui::Context::default(), &path).unwrap();
+ let mut h = Harness::builder()
+ .with_size(vec2(1600.0, 1000.0))
+ .renderer(egui_kittest::wgpu::WgpuTestRenderer::from_render_state(gpu))
+ .build_ui_state(|ui, home: &mut Home| home.frame(ui), first);
+ let started = std::time::Instant::now();
+ while !h.state().editor.as_ref().unwrap().canvas_current() && started.elapsed().as_secs() < 60 {
+ h.step();
+ h.render().unwrap();
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ h.state_mut().editor.as_mut().unwrap().redraw_canvas();
+ (0..6).for_each(|_| {
+ h.step();
+ h.render().unwrap();
+ });
+ h.render().unwrap().save(out.join("editor-lantern.png")).unwrap();
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/app/src/jobs.rs b/crates/app/src/jobs.rs
new file mode 100644
index 0000000..8b62974
--- /dev/null
+++ b/crates/app/src/jobs.rs
@@ -0,0 +1,368 @@
+use crate::stats::lock;
+use std::io::Read;
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc::{Receiver, TryRecvError, channel};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+pub const CHANGED: i32 = 75;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Tag {
+ Inbetween,
+ Export,
+}
+
+#[derive(Clone)]
+pub struct Spec {
+ pub tag: Tag,
+ pub name: String,
+ pub exe: PathBuf,
+ pub args: Vec<String>,
+ pub env: Vec<(String, String)>,
+ pub reruns: u32,
+ pub summary: fn(&str, &str) -> String,
+ pub failure: fn(&str, &str) -> String,
+}
+
+struct Ended {
+ code: Option<i32>,
+ stdout: String,
+ stderr: String,
+}
+
+struct Running {
+ id: u64,
+ spec: Spec,
+ started: Instant,
+ child: Arc<Mutex<Child>>,
+ cancelled: Arc<AtomicBool>,
+ rx: Receiver<std::io::Result<Ended>>,
+ reruns: u32,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Outcome {
+ Done(String),
+ Failed(String),
+ Cancelled,
+ Rerun,
+}
+
+#[derive(Clone, Debug)]
+pub struct Event {
+ pub tag: Tag,
+ pub name: String,
+ pub outcome: Outcome,
+ pub took: Duration,
+ pub output: String,
+}
+
+#[derive(Default)]
+pub struct Jobs {
+ running: Vec<Running>,
+ next: u64,
+}
+
+type Launched = (Arc<Mutex<Child>>, Receiver<std::io::Result<Ended>>);
+
+fn launch(spec: &Spec) -> std::io::Result<Launched> {
+ let mut child = Command::new(&spec.exe)
+ .args(&spec.args)
+ .envs(spec.env.iter().map(|(k, v)| (k, v)))
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()?;
+ let mut out = child.stdout.take();
+ let mut err = child.stderr.take();
+ let child = Arc::new(Mutex::new(child));
+ let waiter = child.clone();
+ let (tx, rx) = channel();
+ std::thread::spawn(move || {
+ let errors = std::thread::spawn(move || {
+ let mut text = String::new();
+ if let Some(e) = err.as_mut() {
+ let _ = e.read_to_string(&mut text);
+ }
+ text
+ });
+ let mut stdout = String::new();
+ if let Some(o) = out.as_mut() {
+ let _ = o.read_to_string(&mut stdout);
+ }
+ let stderr = errors.join().unwrap_or_default();
+ let status = lock(&waiter).wait();
+ let _ = tx.send(status.map(|s| Ended {
+ code: s.code(),
+ stdout,
+ stderr,
+ }));
+ });
+ Ok((child, rx))
+}
+
+impl Jobs {
+ pub fn start(&mut self, spec: Spec) -> std::io::Result<u64> {
+ let (child, rx) = launch(&spec)?;
+ self.next += 1;
+ self.running.push(Running {
+ id: self.next,
+ spec,
+ started: Instant::now(),
+ child,
+ cancelled: Arc::new(AtomicBool::new(false)),
+ rx,
+ reruns: 0,
+ });
+ Ok(self.next)
+ }
+
+ pub fn cancel(&mut self, id: u64) {
+ self.running.iter().filter(|r| r.id == id).for_each(|r| {
+ r.cancelled.store(true, Ordering::Relaxed);
+ let _ = lock(&r.child).kill();
+ });
+ }
+
+ pub fn busy(&self, tag: Tag) -> bool {
+ self.running.iter().any(|r| r.spec.tag == tag)
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.running.is_empty()
+ }
+
+ pub fn running(&self, now: Instant) -> Vec<(u64, String, Duration)> {
+ self.running
+ .iter()
+ .map(|r| (r.id, r.spec.name.clone(), now.duration_since(r.started)))
+ .collect()
+ }
+
+ pub fn poll(&mut self) -> Vec<Event> {
+ let mut events = Vec::new();
+ let mut keep = Vec::new();
+ std::mem::take(&mut self.running).into_iter().for_each(|mut r| {
+ let result = match r.rx.try_recv() {
+ Err(TryRecvError::Empty) => {
+ keep.push(r);
+ return;
+ }
+ Err(TryRecvError::Disconnected) => Err("the job stopped without a result".to_string()),
+ Ok(Err(e)) => Err(format!("cannot run {}: {e}", r.spec.exe.display())),
+ Ok(Ok(ended)) => Ok(ended),
+ };
+ let took = r.started.elapsed();
+ let output = match &result {
+ Ok(e) => format!("{}{}", e.stdout, e.stderr),
+ Err(_) => String::new(),
+ };
+ let event = |outcome| Event {
+ tag: r.spec.tag,
+ name: r.spec.name.clone(),
+ outcome,
+ took,
+ output: output.clone(),
+ };
+ let outcome = match result {
+ _ if r.cancelled.load(Ordering::Relaxed) => Outcome::Cancelled,
+ Err(text) => Outcome::Failed(text),
+ Ok(e) if e.code == Some(0) => Outcome::Done((r.spec.summary)(&e.stdout, &e.stderr)),
+ Ok(e) if e.code == Some(CHANGED) && r.reruns < r.spec.reruns => match launch(&r.spec) {
+ Ok((child, rx)) => {
+ events.push(event(Outcome::Rerun));
+ r.child = child;
+ r.rx = rx;
+ r.reruns += 1;
+ keep.push(r);
+ return;
+ }
+ Err(e) => Outcome::Failed(format!("cannot run it again: {e}")),
+ },
+ Ok(e) => Outcome::Failed((r.spec.failure)(&e.stdout, &e.stderr)),
+ };
+ events.push(event(outcome));
+ });
+ self.running = keep;
+ events
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::composite::Scene;
+ use klad_brush::BrushSet;
+ use klad_core::bundle::Bundle;
+ use klad_core::doc::{Document, Layer};
+ use klad_core::ops::parse_lines;
+ use std::path::Path;
+
+ fn shell(name: &str, script: &str, reruns: u32) -> Spec {
+ Spec {
+ tag: Tag::Export,
+ name: name.into(),
+ exe: PathBuf::from("sh"),
+ args: vec!["-c".into(), script.into()],
+ env: Vec::new(),
+ reruns,
+ summary: |out, _| out.trim().to_string(),
+ failure: |_, err| err.trim().to_string(),
+ }
+ }
+
+ fn until_done(jobs: &mut Jobs, seconds: u64) -> Vec<Event> {
+ let start = Instant::now();
+ let mut seen = Vec::new();
+ while !jobs.is_empty() && start.elapsed() < Duration::from_secs(seconds) {
+ seen.extend(jobs.poll());
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ seen
+ }
+
+ #[test]
+ fn jobs_report_done_failed_cancelled_and_run_again_when_the_document_changed() {
+ let dir = std::env::temp_dir().join(format!("draw-jobs-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join("seen");
+ let mut jobs = Jobs::default();
+ jobs.start(shell("ok", "echo made 3; echo noise >&2", 0)).unwrap();
+ jobs.start(shell("bad", "echo broke >&2; exit 3", 0)).unwrap();
+ let slow = jobs.start(shell("slow", "sleep 5", 0)).unwrap();
+ let again = format!(
+ "if [ -f {0} ]; then echo second; else touch {0}; exit 75; fi",
+ marker.display()
+ );
+ jobs.start(shell("again", &again, 2)).unwrap();
+ assert!(jobs.busy(Tag::Export) && !jobs.busy(Tag::Inbetween));
+ assert_eq!(jobs.running(Instant::now()).len(), 4);
+ jobs.cancel(slow);
+ let events = until_done(&mut jobs, 10);
+ let of = |name: &str| {
+ events
+ .iter()
+ .filter(|e| e.name == name)
+ .map(|e| e.outcome.clone())
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(of("ok"), [Outcome::Done("made 3".into())]);
+ assert_eq!(of("bad"), [Outcome::Failed("broke".into())]);
+ assert_eq!(of("slow"), [Outcome::Cancelled]);
+ assert_eq!(of("again"), [Outcome::Rerun, Outcome::Done("second".into())]);
+ jobs.start(shell("stubborn", "exit 75", 1)).unwrap();
+ let events = until_done(&mut jobs, 10);
+ assert_eq!(events.len(), 2);
+ assert!(matches!(events[1].outcome, Outcome::Failed(_)));
+ assert!(jobs.start(shell("x", "true", 0)).is_ok());
+ let mut missing = shell("missing", "", 0);
+ missing.exe = dir.join("no-such-binary");
+ assert!(jobs.start(missing).is_err());
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ fn draw_binary() -> PathBuf {
+ let exe = std::env::current_exe().unwrap();
+ let bin = exe.parent().and_then(Path::parent).unwrap().join("klad");
+ assert!(
+ bin.exists(),
+ "{} is missing: cargo test --workspace builds it (the klad-cli binary test needs it)",
+ bin.display()
+ );
+ bin
+ }
+
+ #[test]
+ fn an_edit_made_while_an_in_between_job_runs_survives_it() {
+ let dir = std::env::temp_dir().join(format!("draw-jobs-tween-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(256, 256);
+ doc.timeline.frames = 5;
+ doc.layers.push(Layer::paint("l1", "lines", "c1"));
+ doc.layers.push(Layer::paint("l2", "notes", "c2"));
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .apply(
+ &parse_lines(
+ r#"{"op":"set","id":"c2","hold":1}
+{"op":"stroke","layer":"l1","path":"M40 40 L140 60","size":6}
+{"op":"cel","dup":"c1","frame":4}"#,
+ )
+ .unwrap(),
+ )
+ .map(|a| {
+ let key = a.added[0].clone();
+ let id = bundle.read_marks("l1", &key).unwrap()[0].id();
+ let moved = format!(r#"{{"op":"transform","ids":["{key}:s{id}"],"x":50,"y":80}}"#);
+ bundle.apply(&parse_lines(&moved).unwrap()).unwrap();
+ })
+ .unwrap();
+ let mut jobs = Jobs::default();
+ let marker = dir.join(".cache/write-delay");
+ jobs.start(Spec {
+ tag: Tag::Inbetween,
+ name: "in-betweens".into(),
+ exe: draw_binary(),
+ args: [
+ "inbetween",
+ &dir.to_string_lossy(),
+ "--layers",
+ "l1",
+ "--from",
+ "0",
+ "--to",
+ "4",
+ ]
+ .map(String::from)
+ .to_vec(),
+ env: vec![("DRAW_TEST_WRITE_DELAY_MS".into(), "700".into())],
+ reruns: 2,
+ summary: |out, _| out.trim().to_string(),
+ failure: |_, err| err.trim().to_string(),
+ })
+ .unwrap();
+ let start = Instant::now();
+ let mut early = Vec::new();
+ while !marker.exists() && !jobs.is_empty() && start.elapsed() < Duration::from_secs(30) {
+ early.extend(jobs.poll());
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert!(marker.exists(), "the CLI never reached its write: {early:?}");
+ std::fs::remove_file(&marker).unwrap();
+ let mut scene = Scene::open(&dir).unwrap();
+ let brushes = BrushSet::for_bundle(&scene.bundle).unwrap();
+ scene
+ .apply(
+ &parse_lines(r#"{"op":"stroke","layer":"l2","path":"M10 10 L60 60","frame":3}"#).unwrap(),
+ &brushes,
+ )
+ .unwrap();
+ let events = until_done(&mut jobs, 60);
+ let outcomes: Vec<&Outcome> = events.iter().map(|e| &e.outcome).collect();
+ assert_eq!(outcomes.first(), Some(&&Outcome::Rerun), "{outcomes:?}");
+ assert!(matches!(outcomes.last(), Some(Outcome::Done(_))), "{outcomes:?}");
+ let after = Bundle::open(&dir).unwrap();
+ let notes = after.doc.layer("l2").unwrap();
+ let painted = notes
+ .cels()
+ .iter()
+ .find(|c| c.frame == 3)
+ .expect("the editor's new drawing at frame 3");
+ assert_eq!(after.read_marks("l2", &painted.id).unwrap().len(), 1);
+ let tweens = after
+ .doc
+ .layer("l1")
+ .unwrap()
+ .cels()
+ .iter()
+ .filter(|c| c.tween.is_some())
+ .count();
+ assert_eq!(tweens, 3);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs
new file mode 100644
index 0000000..b928640
--- /dev/null
+++ b/crates/app/src/layout.rs
@@ -0,0 +1,353 @@
+use egui::Vec2;
+use serde::{Deserialize, Serialize};
+
+pub const STRIP: f32 = 44.0;
+pub const STATUS: f32 = 28.0;
+pub const TITLE: f32 = 30.0;
+pub const DOCK_MIN: f32 = 260.0;
+pub const DOCK_DEFAULT: f32 = 330.0;
+pub const TIMELINE_MIN: f32 = 150.0;
+pub const TIMELINE_DEFAULT: f32 = 330.0;
+pub const TIMELINE_FOLDED: f32 = 64.0;
+pub const CANVAS_MIN: Vec2 = Vec2::new(320.0, 200.0);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Pane {
+ Tool,
+ Layers,
+ Inspector,
+ Notes,
+ History,
+}
+
+impl Pane {
+ pub fn title(self) -> &'static str {
+ match self {
+ Pane::Tool => "Colour and brush",
+ Pane::Layers => "Layers",
+ Pane::Inspector => "Inspector",
+ Pane::Notes => "Notes for the agent",
+ Pane::History => "History",
+ }
+ }
+
+ pub fn min_body(self) -> f32 {
+ match self {
+ Pane::Tool => 160.0,
+ Pane::Layers => 130.0,
+ Pane::Inspector => 110.0,
+ Pane::Notes => 60.0,
+ Pane::History => 60.0,
+ }
+ }
+
+ fn default_body(self) -> f32 {
+ match self {
+ Pane::Tool => 360.0,
+ Pane::Layers => 240.0,
+ Pane::Inspector => 220.0,
+ Pane::Notes => 90.0,
+ Pane::History => 80.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PaneState {
+ pub pane: Pane,
+ pub open: bool,
+ pub collapsed: bool,
+ pub body: f32,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Layout {
+ pub strip: bool,
+ pub dock: bool,
+ pub dock_width: f32,
+ pub timeline: bool,
+ pub timeline_height: f32,
+ pub timeline_folded: bool,
+ pub numbers: bool,
+ pub panes: Vec<PaneState>,
+ #[serde(skip)]
+ pub hidden: bool,
+}
+
+impl Default for Layout {
+ fn default() -> Self {
+ Self {
+ strip: true,
+ dock: true,
+ dock_width: DOCK_DEFAULT,
+ timeline: true,
+ timeline_height: TIMELINE_DEFAULT,
+ timeline_folded: false,
+ numbers: false,
+ panes: [
+ (Pane::Tool, false),
+ (Pane::Layers, false),
+ (Pane::Inspector, false),
+ (Pane::Notes, true),
+ (Pane::History, true),
+ ]
+ .into_iter()
+ .map(|(pane, collapsed)| PaneState {
+ pane,
+ open: true,
+ collapsed,
+ body: pane.default_body(),
+ })
+ .collect(),
+ hidden: false,
+ }
+ }
+}
+
+impl Layout {
+ pub fn repaired(mut self) -> Self {
+ let known: Vec<Pane> = self.panes.iter().map(|p| p.pane).collect();
+ self.panes.dedup_by_key(|p| p.pane);
+ Layout::default()
+ .panes
+ .into_iter()
+ .filter(|p| !known.contains(&p.pane))
+ .for_each(|p| self.panes.push(p));
+ self.panes
+ .iter_mut()
+ .for_each(|p| p.body = p.body.max(p.pane.min_body()));
+ self
+ }
+
+ pub fn shows_strip(&self) -> bool {
+ self.strip && !self.hidden
+ }
+
+ pub fn shows_dock(&self) -> bool {
+ self.dock && !self.hidden && self.panes.iter().any(|p| p.open)
+ }
+
+ pub fn shows_timeline(&self) -> bool {
+ self.timeline && !self.hidden
+ }
+
+ pub fn pane(&self, pane: Pane) -> Option<&PaneState> {
+ self.panes.iter().find(|p| p.pane == pane)
+ }
+
+ pub fn pane_mut(&mut self, pane: Pane) -> Option<&mut PaneState> {
+ self.panes.iter_mut().find(|p| p.pane == pane)
+ }
+
+ pub fn is_open(&self, pane: Pane) -> bool {
+ self.pane(pane).is_some_and(|p| p.open)
+ }
+
+ pub fn toggle(&mut self, pane: Pane) {
+ let show = !(self.is_open(pane) && self.dock);
+ if let Some(p) = self.pane_mut(pane) {
+ p.open = show;
+ if show {
+ p.collapsed = false;
+ }
+ }
+ if show {
+ self.dock = true;
+ self.hidden = false;
+ }
+ }
+
+ pub fn dock_range(window: Vec2) -> (f32, f32) {
+ (DOCK_MIN, (window.x * 0.45).max(DOCK_MIN))
+ }
+
+ pub fn timeline_range(window: Vec2) -> (f32, f32) {
+ (TIMELINE_MIN, (window.y * 0.6).max(TIMELINE_MIN))
+ }
+
+ pub fn clamp(&mut self, window: Vec2) {
+ let (lo, hi) = Self::dock_range(window);
+ self.dock_width = self.dock_width.clamp(lo, hi);
+ let (lo, hi) = Self::timeline_range(window);
+ self.timeline_height = self.timeline_height.clamp(lo, hi);
+ let room = window.y - STATUS - CANVAS_MIN.y;
+ if self.timeline_height > room {
+ self.timeline_height = room.max(TIMELINE_MIN);
+ }
+ }
+
+ pub fn bodies(&self, available: f32) -> Vec<(Pane, Option<f32>)> {
+ let open: Vec<&PaneState> = self.panes.iter().filter(|p| p.open).collect();
+ let expanded: Vec<&PaneState> = open.iter().copied().filter(|p| !p.collapsed).collect();
+ let room = (available - open.len() as f32 * TITLE).max(0.0);
+ let wanted: f32 = expanded.iter().map(|p| p.body).sum();
+ let floor: f32 = expanded.iter().map(|p| p.pane.min_body()).sum();
+ let sizes: Vec<f32> = match wanted <= room {
+ true => {
+ let spare = room - wanted;
+ expanded
+ .iter()
+ .enumerate()
+ .map(|(i, p)| p.body + if i + 1 == expanded.len() { spare } else { 0.0 })
+ .collect()
+ }
+ false if floor >= room => expanded.iter().map(|p| p.pane.min_body()).collect(),
+ false => {
+ let k = (room - floor) / (wanted - floor);
+ expanded
+ .iter()
+ .map(|p| p.pane.min_body() + (p.body - p.pane.min_body()) * k)
+ .collect()
+ }
+ };
+ open.iter()
+ .map(|p| {
+ let size = expanded.iter().position(|e| e.pane == p.pane).map(|i| sizes[i]);
+ (p.pane, size)
+ })
+ .collect()
+ }
+
+ pub fn resize_pane(&mut self, pane: Pane, by: f32) {
+ if let Some(p) = self.pane_mut(pane) {
+ p.body = (p.body + by).max(p.pane.min_body());
+ }
+ }
+}
+
+pub fn take_tabs(raw: &mut egui::RawInput) -> Vec<bool> {
+ let mut shifts = Vec::new();
+ raw.events.retain(|e| match e {
+ egui::Event::Key {
+ key: egui::Key::Tab,
+ pressed,
+ modifiers,
+ ..
+ } if !modifiers.alt && !modifiers.command => {
+ if *pressed {
+ shifts.push(modifiers.shift);
+ }
+ false
+ }
+ _ => true,
+ });
+ shifts
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::vec2;
+
+ #[test]
+ fn panes_fit_the_dock_and_the_last_one_takes_what_is_left() {
+ let layout = Layout::default();
+ let bodies = layout.bodies(1200.0);
+ assert_eq!(bodies.len(), 5);
+ let used: f32 = bodies.iter().map(|(_, b)| b.unwrap_or(0.0)).sum::<f32>() + 5.0 * TITLE;
+ assert!((used - 1200.0).abs() < 0.01, "{used}");
+ assert_eq!(bodies[3], (Pane::Notes, None));
+ assert!(bodies[2].1.unwrap() > Pane::Inspector.default_body());
+ let small = layout.bodies(560.0);
+ small.iter().filter_map(|(p, b)| b.map(|b| (p, b))).for_each(|(p, b)| {
+ assert!(b >= p.min_body() - 0.01, "{p:?} {b}");
+ });
+ let used: f32 = small.iter().map(|(_, b)| b.unwrap_or(0.0)).sum::<f32>() + 5.0 * TITLE;
+ assert!((used - 560.0).abs() < 0.01);
+ let tiny = layout.bodies(200.0);
+ assert!(tiny.iter().all(|(p, b)| b.is_none_or(|b| b == p.min_body())));
+ }
+
+ #[test]
+ fn closing_collapsing_and_toggling_panes() {
+ let mut layout = Layout::default();
+ layout.toggle(Pane::Layers);
+ assert!(!layout.is_open(Pane::Layers));
+ assert_eq!(layout.bodies(900.0).len(), 4);
+ layout.toggle(Pane::Notes);
+ layout.toggle(Pane::Notes);
+ assert!(layout.is_open(Pane::Notes) && !layout.pane(Pane::Notes).unwrap().collapsed);
+ layout.dock = false;
+ layout.toggle(Pane::Tool);
+ assert!(layout.dock && layout.is_open(Pane::Tool));
+ layout.panes.iter_mut().for_each(|p| p.open = false);
+ assert!(!layout.shows_dock());
+ layout.resize_pane(Pane::Tool, -1000.0);
+ assert_eq!(layout.pane(Pane::Tool).unwrap().body, Pane::Tool.min_body());
+ }
+
+ #[test]
+ fn sizes_clamp_to_the_window() {
+ let mut layout = Layout {
+ dock_width: 2000.0,
+ timeline_height: 2000.0,
+ ..Layout::default()
+ };
+ layout.clamp(vec2(1280.0, 800.0));
+ assert_eq!(layout.dock_width, 1280.0 * 0.45);
+ assert_eq!(layout.timeline_height, 800.0 * 0.6);
+ layout.timeline_height = 2000.0;
+ layout.clamp(vec2(1280.0, 500.0));
+ assert_eq!(layout.timeline_height, 500.0 - STATUS - CANVAS_MIN.y);
+ layout.dock_width = 10.0;
+ layout.timeline_height = 10.0;
+ layout.clamp(vec2(1280.0, 800.0));
+ assert_eq!((layout.dock_width, layout.timeline_height), (DOCK_MIN, TIMELINE_MIN));
+ layout.clamp(vec2(300.0, 260.0));
+ assert_eq!((layout.dock_width, layout.timeline_height), (DOCK_MIN, TIMELINE_MIN));
+ let tab = Layout {
+ hidden: true,
+ ..Layout::default()
+ };
+ assert!(!tab.shows_dock() && !tab.shows_strip() && !tab.shows_timeline());
+ }
+
+ #[test]
+ fn the_layout_survives_a_restart_and_old_settings_gain_new_panes() {
+ let mut layout = Layout {
+ dock_width: 410.0,
+ ..Layout::default()
+ };
+ layout.toggle(Pane::History);
+ layout.hidden = true;
+ let text = serde_json::to_string(&layout).unwrap();
+ let back: Layout = serde_json::from_str(&text).unwrap();
+ assert_eq!(back.dock_width, 410.0);
+ assert!(!back.hidden && !back.is_open(Pane::History));
+ let old = serde_json::from_str::<Layout>(
+ r#"{"dockWidth":300,"panes":[{"pane":"layers","open":true,"collapsed":false,"body":5}]}"#,
+ )
+ .unwrap()
+ .repaired();
+ assert_eq!(old.panes.len(), 5);
+ assert_eq!(old.panes[0].pane, Pane::Layers);
+ assert_eq!(old.panes[0].body, Pane::Layers.min_body());
+ }
+
+ #[test]
+ fn tab_is_taken_before_egui_moves_focus_with_it() {
+ let key = |key, shift, pressed| egui::Event::Key {
+ key,
+ physical_key: None,
+ pressed,
+ repeat: false,
+ modifiers: egui::Modifiers {
+ shift,
+ ..Default::default()
+ },
+ };
+ let mut raw = egui::RawInput {
+ events: vec![
+ key(egui::Key::Tab, false, true),
+ key(egui::Key::Tab, false, false),
+ key(egui::Key::K, false, true),
+ key(egui::Key::Tab, true, true),
+ ],
+ ..Default::default()
+ };
+ assert_eq!(take_tabs(&mut raw), [false, true]);
+ assert_eq!(raw.events.len(), 1);
+ }
+}
diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs
new file mode 100644
index 0000000..71991c6
--- /dev/null
+++ b/crates/app/src/lib.rs
@@ -0,0 +1,34 @@
+mod color;
+mod commands;
+mod composite;
+mod editor;
+mod frames;
+mod gpu;
+mod home;
+mod jobs;
+mod layout;
+mod lift;
+mod messages;
+mod pen;
+mod picker;
+mod planes;
+mod settings;
+mod start;
+mod stats;
+mod sync;
+mod theme;
+mod view;
+
+pub use home::run;
+
+fn background() -> &'static rayon::ThreadPool {
+ static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();
+ POOL.get_or_init(|| {
+ let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
+ rayon::ThreadPoolBuilder::new()
+ .num_threads(cores.saturating_sub(1).max(1))
+ .thread_name(|i| format!("draw background {i}"))
+ .build()
+ .expect("a background thread pool")
+ })
+}
diff --git a/crates/app/src/lift.rs b/crates/app/src/lift.rs
new file mode 100644
index 0000000..b2f29db
--- /dev/null
+++ b/crates/app/src/lift.rs
@@ -0,0 +1,265 @@
+use anyhow::{Result, anyhow};
+use half::f16;
+use klad_brush::{BrushSet, CelReplay, Raster, TILE};
+use klad_core::doc::{Node, Transform};
+use klad_core::markedit::union;
+use klad_core::rng::{FNV_OFFSET, fnv};
+use klad_core::stroke::Mark;
+use klad_render::{Lifted, rasterize_nodes, rasterize_region, vector};
+use std::sync::mpsc::{Receiver, channel};
+
+pub struct Prepared {
+ pub key: String,
+ pub rev: u64,
+ pub cel: String,
+ pub layer: Vec<usize>,
+ pub index: usize,
+ pub nodes: Vec<Node>,
+ pub lifted: Lifted,
+ pub lower: Raster,
+ pub upper: Raster,
+}
+
+pub enum Source {
+ Node {
+ index: usize,
+ nodes: Vec<Node>,
+ },
+ Marks {
+ ids: Vec<u32>,
+ marks: Option<Vec<Mark>>,
+ replay: Box<CelReplay>,
+ raster: Raster,
+ brushes: Box<BrushSet>,
+ },
+}
+
+pub struct Job {
+ pub key: String,
+ pub rev: u64,
+ pub cel: String,
+ pub layer: Vec<usize>,
+ pub source: Source,
+ pub canvas: (u32, u32),
+ pub scale: f32,
+}
+
+fn spawn<T: Send + 'static>(
+ ctx: egui::Context,
+ work: impl FnOnce() -> Result<T> + Send + 'static,
+) -> Receiver<Result<T>> {
+ let (tx, rx) = channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(work());
+ ctx.request_repaint();
+ });
+ rx
+}
+
+pub fn crop(raster: &Raster, [x, y, w, h]: [f32; 4], max_side: u32) -> Lifted {
+ let (x0, y0) = (x.floor().max(0.0) as u32, y.floor().max(0.0) as u32);
+ let x1 = ((x + w).ceil().max(0.0) as u32).min(raster.width).max(x0 + 1);
+ let y1 = ((y + h).ceil().max(0.0) as u32).min(raster.height).max(y0 + 1);
+ let step = (x1 - x0).max(y1 - y0).div_ceil(max_side).max(1);
+ let (width, height) = ((x1 - x0).div_ceil(step), (y1 - y0).div_ceil(step));
+ let pixel = |px: u32, py: u32| -> [f16; 4] {
+ if px >= raster.width || py >= raster.height {
+ return [f16::ZERO; 4];
+ }
+ let (px, py) = (px as usize, py as usize);
+ raster.get(px / TILE, py / TILE).map_or([f16::ZERO; 4], |tile| {
+ let at = ((py % TILE) * TILE + px % TILE) * 4;
+ [tile[at], tile[at + 1], tile[at + 2], tile[at + 3]]
+ })
+ };
+ let pixels = (0..height)
+ .flat_map(|j| (0..width).map(move |i| (i, j)))
+ .flat_map(|(i, j)| pixel(x0 + i * step, y0 + j * step))
+ .collect();
+ Lifted {
+ rect: [x0 as f32, y0 as f32, (width * step) as f32, (height * step) as f32],
+ width,
+ height,
+ pixels,
+ }
+}
+
+pub fn prepare(job: Job, ctx: egui::Context) -> Receiver<Result<Prepared>> {
+ spawn(ctx, move || {
+ let (cw, ch) = job.canvas;
+ let (index, nodes, lifted, lower, upper) = match job.source {
+ Source::Node { index, nodes } => {
+ let target = nodes.get(index).ok_or_else(|| anyhow!("node index out of range"))?;
+ let [x, y, w, h] =
+ vector::node_box(target)?.ok_or_else(|| anyhow!("{} has nothing to draw", job.key))?;
+ let lifted = rasterize_region(
+ std::slice::from_ref(target),
+ [x - 2.0, y - 2.0, w + 4.0, h + 4.0],
+ 4096,
+ job.scale,
+ )?;
+ let lower = rasterize_nodes(&nodes[..index], cw, ch)?;
+ let upper = rasterize_nodes(&nodes[index + 1..], cw, ch)?;
+ (index, nodes, lifted, lower, upper)
+ }
+ Source::Marks {
+ ids,
+ marks,
+ mut replay,
+ mut raster,
+ brushes,
+ } => {
+ let all = marks.unwrap_or_else(|| replay.marks().to_vec());
+ let (chosen, rest): (Vec<Mark>, Vec<Mark>) = all.into_iter().partition(|m| ids.contains(&m.id()));
+ let [x0, y0, x1, y1] = union(&chosen.iter().collect::<Vec<_>>())
+ .ok_or_else(|| anyhow!("the selected strokes have nothing to draw"))?;
+ let (_, alone, _) = CelReplay::replay(cw, ch, chosen, &brushes)?;
+ let lifted = crop(&alone, [x0 - 2.0, y0 - 2.0, x1 - x0 + 4.0, y1 - y0 + 4.0], 4096);
+ replay.update(&mut raster, rest, &brushes)?;
+ (0, Vec::new(), lifted, raster, Raster::new(cw, ch))
+ }
+ };
+ Ok(Prepared {
+ key: job.key,
+ rev: job.rev,
+ cel: job.cel,
+ layer: job.layer,
+ index,
+ nodes,
+ lifted,
+ lower,
+ upper,
+ })
+ })
+}
+
+pub fn render(nodes: Vec<Node>, canvas: (u32, u32), ctx: egui::Context) -> Receiver<Result<(u64, Raster)>> {
+ spawn(ctx, move || {
+ let hash = fnv(FNV_OFFSET, &serde_json::to_vec(&nodes)?);
+ Ok((hash, rasterize_nodes(&nodes, canvas.0, canvas.1)?))
+ })
+}
+
+pub fn finish(
+ mut nodes: Vec<Node>,
+ index: usize,
+ transform: Transform,
+ canvas: (u32, u32),
+ ctx: egui::Context,
+) -> Receiver<Result<(u64, Raster)>> {
+ if let Some(node) = nodes.get_mut(index) {
+ node.transform = transform;
+ }
+ render(nodes, canvas, ctx)
+}
+
+pub fn affine_apply(a: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
+ (a[0] * x + a[1] * y + a[4], a[2] * x + a[3] * y + a[5])
+}
+
+pub fn committed(node: &Node, affine: [f32; 6], scale: f32, degrees: f32) -> Result<Transform> {
+ let mut t = node.transform;
+ let pivot = match t.pivot {
+ Some(p) => p,
+ None => {
+ let mut plain = node.clone();
+ plain.transform = Transform::default();
+ vector::local_bounds(&plain)?.map_or([0.0, 0.0], |r| [r.center_x(), r.center_y()])
+ }
+ };
+ let (qx, qy) = affine_apply(affine, (t.x + pivot[0], t.y + pivot[1]));
+ t.x = qx - pivot[0];
+ t.y = qy - pivot[1];
+ t.sx *= scale;
+ t.sy *= scale;
+ t.rotate += degrees;
+ Ok(t)
+}
+
+pub fn square(node: &Node) -> bool {
+ let r = node.transform.rotate.rem_euclid(90.0);
+ !(0.5..=89.5).contains(&r)
+}
+
+pub fn stretched(node: &Node, affine: [f32; 6], axis: usize, k: f32) -> Result<Transform> {
+ let mut t = committed(node, affine, 1.0, 0.0)?;
+ let quarter = (t.rotate / 90.0).round() as i64;
+ match (axis + quarter.rem_euclid(2) as usize) % 2 {
+ 0 => t.sx *= k,
+ _ => t.sy *= k,
+ }
+ Ok(t)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Shape;
+
+ #[test]
+ fn crops_copy_pixels_across_tiles_and_shrink_big_regions() {
+ let mut raster = Raster::new(600, 300);
+ raster.ensure(raster.index(1, 0))[((10 * TILE) + 3) * 4 + 3] = f16::ONE;
+ let lifted = crop(&raster, [250.0, 5.0, 20.0, 10.0], 4096);
+ assert_eq!((lifted.width, lifted.height), (20, 10));
+ assert_eq!(lifted.rect, [250.0, 5.0, 20.0, 10.0]);
+ assert_eq!(lifted.pixels[(5 * 20 + 9) * 4 + 3], f16::ONE);
+ let small = crop(&raster, [0.0, 0.0, 600.0, 300.0], 100);
+ assert_eq!((small.width, small.height), (100, 50));
+ assert_eq!(small.rect, [0.0, 0.0, 600.0, 300.0]);
+ }
+
+ #[test]
+ fn stretching_a_square_shape_scales_its_own_axis_and_keeps_the_far_edge() {
+ let mut node = Node::new(
+ "r",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 100.0,
+ h: 50.0,
+ radius: 0.0,
+ },
+ );
+ assert!(square(&node));
+ let t = stretched(&node, [2.0, 0.0, 0.0, 1.0, 0.0, 0.0], 0, 2.0).unwrap();
+ assert_eq!((t.sx, t.sy, t.x, t.y), (2.0, 1.0, 50.0, 0.0));
+ node.transform.rotate = 90.0;
+ let t = stretched(&node, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], 0, 3.0).unwrap();
+ assert_eq!((t.sx, t.sy), (1.0, 3.0));
+ node.transform.rotate = 30.0;
+ assert!(!square(&node));
+ }
+
+ #[test]
+ fn committed_transforms_follow_the_preview() {
+ let node = Node::new(
+ "n",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 100.0,
+ h: 50.0,
+ radius: 0.0,
+ },
+ );
+ let moved = committed(&node, [1.0, 0.0, 0.0, 1.0, 30.0, -10.0], 1.0, 0.0).unwrap();
+ assert_eq!((moved.x, moved.y), (30.0, -10.0));
+ let (c, k) = ((50.0, 25.0), 2.0);
+ let scaled = committed(&node, [k, 0.0, 0.0, k, c.0 * (1.0 - k), c.1 * (1.0 - k)], k, 0.0).unwrap();
+ assert_eq!((scaled.x, scaled.y, scaled.sx), (0.0, 0.0, 2.0));
+ let mut pinned = node.clone();
+ pinned.transform.pivot = Some([0.0, 50.0]);
+ let grown = committed(&pinned, [k, 0.0, 0.0, k, c.0 * (1.0 - k), c.1 * (1.0 - k)], k, 0.0).unwrap();
+ let m = klad_render::vector::node_matrix(&Node {
+ transform: grown,
+ ..pinned.clone()
+ })
+ .unwrap();
+ let corner = m.map_point((100.0, 50.0));
+ assert!(
+ (corner.x - 150.0).abs() < 0.01 && (corner.y - 75.0).abs() < 0.01,
+ "{corner:?}"
+ );
+ }
+}
diff --git a/crates/app/src/messages.rs b/crates/app/src/messages.rs
new file mode 100644
index 0000000..e5e2da2
--- /dev/null
+++ b/crates/app/src/messages.rs
@@ -0,0 +1,149 @@
+use egui::Pos2;
+use std::collections::VecDeque;
+use std::time::{Duration, Instant};
+
+pub const KEEP: usize = 200;
+pub const SHOWN: usize = 3;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Tone {
+ Info,
+ Done,
+ Refused,
+ Error,
+}
+
+impl Tone {
+ pub fn life(self) -> Option<Duration> {
+ match self {
+ Tone::Info => Some(Duration::ZERO),
+ Tone::Done => Some(Duration::from_millis(3500)),
+ Tone::Refused => Some(Duration::from_secs(6)),
+ Tone::Error => None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Message {
+ pub id: u64,
+ pub tone: Tone,
+ pub text: String,
+ pub at: Instant,
+ pub anchor: Option<Pos2>,
+ pub dismissed: bool,
+ pub times: u32,
+}
+
+#[derive(Default)]
+pub struct Messages {
+ log: VecDeque<Message>,
+ next: u64,
+}
+
+impl Messages {
+ pub fn say(&mut self, tone: Tone, text: impl Into<String>, anchor: Option<Pos2>, now: Instant) -> u64 {
+ let text = text.into();
+ if let Some(last) = self
+ .log
+ .back_mut()
+ .filter(|m| m.tone == tone && m.text == text && !m.dismissed)
+ {
+ last.at = now;
+ last.anchor = anchor.or(last.anchor);
+ last.times += 1;
+ return last.id;
+ }
+ self.next += 1;
+ self.log.push_back(Message {
+ id: self.next,
+ tone,
+ text,
+ at: now,
+ anchor,
+ dismissed: false,
+ times: 1,
+ });
+ while self.log.len() > KEEP {
+ self.log.pop_front();
+ }
+ self.next
+ }
+
+ pub fn toasts(&self, now: Instant) -> Vec<&Message> {
+ let mut shown: Vec<&Message> = self
+ .log
+ .iter()
+ .rev()
+ .filter(|m| !m.dismissed)
+ .filter(|m| m.tone.life().is_none_or(|life| now.duration_since(m.at) < life))
+ .take(SHOWN)
+ .collect();
+ shown.reverse();
+ shown
+ }
+
+ pub fn latest(&self) -> Option<&Message> {
+ self.log.back()
+ }
+
+ pub fn dismiss(&mut self, id: u64) {
+ self.log
+ .iter_mut()
+ .filter(|m| m.id == id)
+ .for_each(|m| m.dismissed = true);
+ }
+
+ pub fn log(&self) -> impl DoubleEndedIterator<Item = &Message> {
+ self.log.iter()
+ }
+
+ pub fn next_change(&self, now: Instant) -> Option<Duration> {
+ self.toasts(now)
+ .iter()
+ .filter_map(|m| m.tone.life().map(|life| life.saturating_sub(now.duration_since(m.at))))
+ .min()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::pos2;
+
+ #[test]
+ fn results_fade_refusals_linger_and_errors_stay_until_dismissed() {
+ let t0 = Instant::now();
+ let mut m = Messages::default();
+ let at = Some(pos2(10.0, 20.0));
+ m.say(Tone::Info, "frame 4 shown", None, t0);
+ let done = m.say(Tone::Done, "copied 3 marks", at, t0);
+ let refused = m.say(Tone::Refused, "nothing to duplicate on this frame", at, t0);
+ let error = m.say(Tone::Error, "reading doc.json", None, t0);
+ let texts = |m: &Messages, now| m.toasts(now).iter().map(|t| t.id).collect::<Vec<_>>();
+ assert_eq!(texts(&m, t0), [done, refused, error]);
+ assert_eq!(texts(&m, t0 + Duration::from_secs(4)), [refused, error]);
+ assert_eq!(texts(&m, t0 + Duration::from_secs(60)), [error]);
+ assert_eq!(m.latest().unwrap().id, error);
+ assert_eq!(m.toasts(t0)[0].anchor, at);
+ m.dismiss(error);
+ assert!(texts(&m, t0 + Duration::from_secs(60)).is_empty());
+ assert_eq!(m.next_change(t0), Some(Duration::from_millis(3500)));
+ assert_eq!(m.log().count(), 4);
+ }
+
+ #[test]
+ fn a_message_said_again_is_one_message() {
+ let t0 = Instant::now();
+ let mut m = Messages::default();
+ let a = m.say(Tone::Error, "no watcher", None, t0);
+ let b = m.say(Tone::Error, "no watcher", None, t0 + Duration::from_secs(1));
+ assert_eq!(a, b);
+ assert_eq!(m.latest().unwrap().times, 2);
+ (0..KEEP + 20).for_each(|i| {
+ m.say(Tone::Done, format!("step {i}"), None, t0);
+ });
+ assert_eq!(m.log().count(), KEEP);
+ assert_eq!(m.toasts(t0).len(), SHOWN);
+ }
+}
diff --git a/crates/app/src/pen.rs b/crates/app/src/pen.rs
new file mode 100644
index 0000000..230246b
--- /dev/null
+++ b/crates/app/src/pen.rs
@@ -0,0 +1,286 @@
+use egui::Pos2;
+use std::time::Instant;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Phase {
+ Down,
+ Move,
+ Up,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct PenEvent {
+ pub phase: Phase,
+ pub pos: Pos2,
+ pub pressure: f32,
+ pub tilt: (f32, f32),
+ pub eraser: bool,
+ pub tablet: bool,
+ pub device: u64,
+ pub at: Instant,
+}
+
+impl PenEvent {
+ pub fn recorded_pressure(&self) -> f32 {
+ if !self.tablet && self.pressure <= 0.0 {
+ 1.0
+ } else {
+ self.pressure
+ }
+ }
+}
+
+pub fn device_key(device: u64) -> String {
+ if device == 0 {
+ "tablet".into()
+ } else {
+ format!("pen-{device:016x}")
+ }
+}
+
+pub fn from_egui(events: &[egui::Event]) -> Vec<PenEvent> {
+ let at = Instant::now();
+ let event = |phase, pos, pressure| PenEvent {
+ phase,
+ pos,
+ pressure,
+ tilt: (0.0, 0.0),
+ eraser: false,
+ tablet: false,
+ device: 0,
+ at,
+ };
+ events
+ .iter()
+ .filter_map(|e| match e {
+ egui::Event::PointerMoved(pos) => Some(event(Phase::Move, *pos, 1.0)),
+ egui::Event::PointerButton {
+ pos,
+ button: egui::PointerButton::Primary,
+ pressed,
+ ..
+ } => Some(if *pressed {
+ event(Phase::Down, *pos, 1.0)
+ } else {
+ event(Phase::Up, *pos, 0.0)
+ }),
+ _ => None,
+ })
+ .collect()
+}
+
+#[cfg(target_os = "macos")]
+pub use mac::Pen;
+
+#[cfg(not(target_os = "macos"))]
+pub struct Pen;
+
+#[cfg(not(target_os = "macos"))]
+impl Pen {
+ pub fn install() -> Option<Self> {
+ None
+ }
+
+ pub fn drain(&self, _content_height: f32) -> Vec<PenEvent> {
+ Vec::new()
+ }
+}
+
+#[cfg(target_os = "macos")]
+mod mac {
+ use super::{PenEvent, Phase};
+ use block2::RcBlock;
+ use klad_core::rng::{FNV_OFFSET, fnv};
+ use objc2::rc::Retained;
+ use objc2::runtime::AnyObject;
+ use objc2_app_kit::{NSEvent, NSEventMask, NSEventSubtype, NSEventType, NSPointingDeviceType};
+ use std::ptr::NonNull;
+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::time::Instant;
+
+ #[derive(Clone, Copy)]
+ struct Raw {
+ phase: Phase,
+ x: f32,
+ y_from_bottom: f32,
+ pressure: f32,
+ tilt: (f32, f32),
+ eraser: bool,
+ tablet: bool,
+ device: u64,
+ at: Instant,
+ }
+
+ #[derive(Default)]
+ struct Proximity {
+ eraser: AtomicBool,
+ device: AtomicU64,
+ }
+
+ pub struct Pen {
+ queue: Arc<Mutex<Vec<Raw>>>,
+ _monitor: Retained<AnyObject>,
+ }
+
+ fn phase_of(kind: NSEventType) -> Option<Phase> {
+ [
+ (NSEventType::LeftMouseDown, Phase::Down),
+ (NSEventType::LeftMouseDragged, Phase::Move),
+ (NSEventType::LeftMouseUp, Phase::Up),
+ (NSEventType::MouseMoved, Phase::Move),
+ ]
+ .iter()
+ .find(|(k, _)| *k == kind)
+ .map(|(_, p)| *p)
+ }
+
+ fn identify(event: &NSEvent) -> u64 {
+ let parts = [
+ event.vendorID() as u64,
+ event.uniqueID(),
+ event.pointingDeviceSerialNumber() as u64,
+ ];
+ if parts.iter().all(|p| *p == 0) {
+ return 0;
+ }
+ fnv(FNV_OFFSET, &parts.map(u64::to_le_bytes).concat())
+ }
+
+ fn near(event: &NSEvent, proximity: &Proximity) {
+ let entering = event.isEnteringProximity();
+ proximity.eraser.store(
+ entering && event.pointingDeviceType() == NSPointingDeviceType::Eraser,
+ Ordering::Relaxed,
+ );
+ if entering {
+ proximity.device.store(identify(event), Ordering::Relaxed);
+ }
+ }
+
+ fn record(event: &NSEvent, proximity: &Proximity, queue: &Mutex<Vec<Raw>>) {
+ let kind = event.r#type();
+ if kind == NSEventType::TabletProximity {
+ near(event, proximity);
+ return;
+ }
+ let Some(phase) = phase_of(kind) else {
+ return;
+ };
+ let subtype = event.subtype();
+ if subtype == NSEventSubtype::TabletProximity {
+ near(event, proximity);
+ return;
+ }
+ let tablet = subtype == NSEventSubtype::TabletPoint;
+ let tilt = if tablet {
+ let t = event.tilt();
+ (t.x as f32, t.y as f32)
+ } else {
+ (0.0, 0.0)
+ };
+ let location = event.locationInWindow();
+ let raw = Raw {
+ phase,
+ x: location.x as f32,
+ y_from_bottom: location.y as f32,
+ pressure: event.pressure(),
+ tilt,
+ eraser: tablet && proximity.eraser.load(Ordering::Relaxed),
+ tablet,
+ device: if tablet {
+ proximity.device.load(Ordering::Relaxed)
+ } else {
+ 0
+ },
+ at: Instant::now(),
+ };
+ if let Ok(mut q) = queue.lock() {
+ q.push(raw);
+ }
+ }
+
+ impl Pen {
+ pub fn install() -> Option<Self> {
+ let queue = Arc::new(Mutex::new(Vec::new()));
+ let proximity = Arc::new(Proximity::default());
+ let (q, e) = (queue.clone(), proximity.clone());
+ NSEvent::setMouseCoalescingEnabled(false);
+ let mask = NSEventMask::LeftMouseDown
+ | NSEventMask::LeftMouseUp
+ | NSEventMask::LeftMouseDragged
+ | NSEventMask::MouseMoved
+ | NSEventMask::TabletProximity;
+ let block = RcBlock::new(move |event: NonNull<NSEvent>| -> *mut NSEvent {
+ record(unsafe { event.as_ref() }, &e, &q);
+ event.as_ptr()
+ });
+ let monitor = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(mask, &block) }?;
+ Some(Self {
+ queue,
+ _monitor: monitor,
+ })
+ }
+
+ pub fn drain(&self, content_height: f32) -> Vec<PenEvent> {
+ let raw = self
+ .queue
+ .lock()
+ .map(|mut q| std::mem::take(&mut *q))
+ .unwrap_or_default();
+ raw.into_iter()
+ .map(|r| PenEvent {
+ phase: r.phase,
+ pos: egui::pos2(r.x, content_height - r.y_from_bottom),
+ pressure: r.pressure,
+ tilt: r.tilt,
+ eraser: r.eraser,
+ tablet: r.tablet,
+ device: r.device,
+ at: r.at,
+ })
+ .collect()
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn egui_pointer_events_become_pen_events() {
+ let events = [
+ egui::Event::PointerButton {
+ pos: egui::pos2(1.0, 2.0),
+ button: egui::PointerButton::Primary,
+ pressed: true,
+ modifiers: egui::Modifiers::NONE,
+ },
+ egui::Event::PointerMoved(egui::pos2(3.0, 4.0)),
+ egui::Event::PointerButton {
+ pos: egui::pos2(3.0, 4.0),
+ button: egui::PointerButton::Secondary,
+ pressed: false,
+ modifiers: egui::Modifiers::NONE,
+ },
+ ];
+ let pen = from_egui(&events);
+ assert_eq!(pen.len(), 2);
+ assert_eq!(pen[0].phase, Phase::Down);
+ assert_eq!(pen[1].pos, egui::pos2(3.0, 4.0));
+ }
+
+ #[test]
+ fn mouse_drags_without_pressure_record_full_pressure() {
+ let mut e = from_egui(&[egui::Event::PointerMoved(egui::pos2(3.0, 4.0))])[0];
+ e.pressure = 0.0;
+ assert_eq!(e.recorded_pressure(), 1.0);
+ e.tablet = true;
+ assert_eq!(e.recorded_pressure(), 0.0);
+ e.pressure = 0.42;
+ assert_eq!(e.recorded_pressure(), 0.42);
+ assert_eq!(device_key(0), "tablet");
+ assert_eq!(device_key(0xab), "pen-00000000000000ab");
+ }
+}
diff --git a/crates/app/src/picker.rs b/crates/app/src/picker.rs
new file mode 100644
index 0000000..aea115e
--- /dev/null
+++ b/crates/app/src/picker.rs
@@ -0,0 +1,32 @@
+use std::path::{Path, PathBuf};
+
+pub const NATIVE: bool = cfg!(target_os = "macos");
+
+#[cfg(target_os = "macos")]
+pub fn choose_folder(start: Option<&Path>, prompt: &str) -> Option<PathBuf> {
+ use objc2::MainThreadMarker;
+ use objc2_app_kit::{NSModalResponseOK, NSOpenPanel};
+ use objc2_foundation::{NSString, NSURL};
+ let mtm = MainThreadMarker::new()?;
+ let panel = NSOpenPanel::openPanel(mtm);
+ panel.setCanChooseDirectories(true);
+ panel.setCanChooseFiles(false);
+ panel.setAllowsMultipleSelection(false);
+ panel.setCanCreateDirectories(true);
+ panel.setPrompt(Some(&NSString::from_str(prompt)));
+ if let Some(dir) = start.and_then(Path::to_str) {
+ panel.setDirectoryURL(Some(&NSURL::fileURLWithPath(&NSString::from_str(dir))));
+ }
+ if panel.runModal() != NSModalResponseOK {
+ return None;
+ }
+ panel
+ .URL()
+ .and_then(|url| url.path())
+ .map(|path| PathBuf::from(path.to_string()))
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn choose_folder(_start: Option<&Path>, _prompt: &str) -> Option<PathBuf> {
+ None
+}
diff --git a/crates/app/src/planes.rs b/crates/app/src/planes.rs
new file mode 100644
index 0000000..3f00c85
--- /dev/null
+++ b/crates/app/src/planes.rs
@@ -0,0 +1,139 @@
+use anyhow::{Result, bail};
+use egui::{Color32, ColorImage};
+use klad_brush::Raster;
+use klad_brush::cache::{compress, prune};
+use klad_core::bundle::write_atomic;
+use klad_core::rng::fnv;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::SystemTime;
+
+pub const BUDGET: u64 = 1 << 30;
+const VERSION: u64 = 1;
+
+pub type Thumbs = Vec<(String, ColorImage)>;
+
+pub struct Stored {
+ pub below: Raster,
+ pub above: Raster,
+ pub thumbs: Thumbs,
+}
+
+pub fn key(base: u64, cels: &[u64]) -> u64 {
+ cels.iter()
+ .fold(fnv(base, &VERSION.to_le_bytes()), |h, k| fnv(h, &k.to_le_bytes()))
+}
+
+pub fn path(dir: &Path, key: u64) -> PathBuf {
+ dir.join(format!("{key:016x}.planes"))
+}
+
+fn section(out: &mut Vec<u8>, bytes: Vec<u8>) {
+ out.extend((bytes.len() as u64).to_le_bytes());
+ out.extend(bytes);
+}
+
+fn thumbs_bytes(thumbs: &Thumbs) -> Vec<u8> {
+ thumbs.iter().fold(Vec::new(), |mut out, (cel, image)| {
+ out.extend((cel.len() as u32).to_le_bytes());
+ out.extend(cel.as_bytes());
+ out.extend((image.size[0] as u32).to_le_bytes());
+ out.extend((image.size[1] as u32).to_le_bytes());
+ out.extend(image.pixels.iter().flat_map(|c| c.to_array()));
+ out
+ })
+}
+
+fn read_thumbs(mut bytes: &[u8]) -> Result<Thumbs> {
+ let mut out = Thumbs::new();
+ let take = |n: usize, bytes: &mut &[u8]| -> Result<Vec<u8>> {
+ if bytes.len() < n {
+ bail!("the thumbnails are cut short");
+ }
+ let (head, rest) = bytes.split_at(n);
+ *bytes = rest;
+ Ok(head.to_vec())
+ };
+ let word = |b: Vec<u8>| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize;
+ while !bytes.is_empty() {
+ let n = word(take(4, &mut bytes)?);
+ let cel = String::from_utf8(take(n, &mut bytes)?)?;
+ let (w, h) = (word(take(4, &mut bytes)?), word(take(4, &mut bytes)?));
+ let pixels = take(w * h * 4, &mut bytes)?
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .map(|p| Color32::from_rgba_premultiplied(p[0], p[1], p[2], p[3]))
+ .collect();
+ out.push((cel, ColorImage::new([w, h], pixels)));
+ }
+ Ok(out)
+}
+
+pub fn write(dir: &Path, key: u64, below: &Raster, above: &Raster, thumbs: &Thumbs) -> Result<()> {
+ let mut bytes = key.to_le_bytes().to_vec();
+ section(&mut bytes, compress(below)?);
+ section(&mut bytes, compress(above)?);
+ section(&mut bytes, zstd::encode_all(&thumbs_bytes(thumbs)[..], 1)?);
+ write_atomic(&path(dir, key), &bytes)?;
+ prune(dir, BUDGET);
+ Ok(())
+}
+
+pub fn read(dir: &Path, key: u64) -> Result<Stored> {
+ let file = path(dir, key);
+ let bytes = fs::read(&file)?;
+ if bytes.len() < 8 || bytes[..8] != key.to_le_bytes() {
+ bail!("stale planes");
+ }
+ let mut rest = &bytes[8..];
+ let mut next = || -> Result<Vec<u8>> {
+ if rest.len() < 8 {
+ bail!("the planes are cut short");
+ }
+ let n = u64::from_le_bytes(rest[..8].try_into()?) as usize;
+ if rest.len() < 8 + n {
+ bail!("the planes are cut short");
+ }
+ let part = zstd::decode_all(&rest[8..8 + n])?;
+ rest = &rest[8 + n..];
+ Ok(part)
+ };
+ let below = Raster::decode(&next()?)?;
+ let above = Raster::decode(&next()?)?;
+ let thumbs = read_thumbs(&next()?)?;
+ let _ = fs::File::options()
+ .write(true)
+ .open(&file)
+ .and_then(|f| f.set_modified(SystemTime::now()));
+ Ok(Stored { below, above, thumbs })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use half::f16;
+ use klad_brush::tiles::TILE_PX;
+
+ #[test]
+ fn planes_read_back_as_written() {
+ let dir = std::env::temp_dir().join(format!("draw-planes-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut below = Raster::new(600, 300);
+ below.put(1, vec![f16::from_f32(0.25); TILE_PX * 4].into_boxed_slice());
+ let above = Raster::new(600, 300);
+ let thumbs = vec![(
+ "c4".to_string(),
+ ColorImage::new([2, 1], vec![Color32::from_rgb(10, 20, 30), Color32::TRANSPARENT]),
+ )];
+ write(&dir, 77, &below, &above, &thumbs).unwrap();
+ let back = read(&dir, 77).unwrap();
+ assert_eq!(back.below.at(1), below.at(1));
+ assert_eq!(back.above.count(), 0);
+ assert_eq!(back.thumbs[0].0, "c4");
+ assert_eq!(back.thumbs[0].1.pixels, thumbs[0].1.pixels);
+ assert!(read(&dir, 78).is_err());
+ assert_ne!(key(1, &[2, 3]), key(1, &[3, 2]));
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/app/src/quad.wgsl b/crates/app/src/quad.wgsl
new file mode 100644
index 0000000..3840968
--- /dev/null
+++ b/crates/app/src/quad.wgsl
@@ -0,0 +1,43 @@
+struct Quad {
+ view_a: vec4<f32>,
+ view_b: vec4<f32>,
+ drag_a: vec4<f32>,
+ drag_b: vec4<f32>,
+ rect: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> q: Quad;
+@group(0) @binding(1) var tex: texture_2d<f32>;
+@group(0) @binding(2) var samp: sampler;
+
+struct Out {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) index: u32) -> Out {
+ var corners = array<vec2<f32>, 6>(
+ vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
+ vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0),
+ );
+ let uv = corners[index];
+ let p = q.rect.xy + uv * q.rect.zw;
+ let d = vec2<f32>(
+ q.drag_a.x * p.x + q.drag_a.y * p.y + q.drag_b.x,
+ q.drag_a.z * p.x + q.drag_a.w * p.y + q.drag_b.y,
+ );
+ let px = vec2<f32>(
+ q.view_a.x * d.x + q.view_a.y * d.y + q.view_b.x,
+ q.view_a.z * d.x + q.view_a.w * d.y + q.view_b.y,
+ );
+ var out: Out;
+ out.pos = vec4<f32>(px.x / q.view_b.z * 2.0 - 1.0, 1.0 - px.y / q.view_b.w * 2.0, 0.0, 1.0);
+ out.uv = uv;
+ return out;
+}
+
+@fragment
+fn fs_main(in: Out) -> @location(0) vec4<f32> {
+ return textureSample(tex, samp, in.uv) * q.drag_b.z;
+}
diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs
new file mode 100644
index 0000000..1069978
--- /dev/null
+++ b/crates/app/src/settings.rs
@@ -0,0 +1,328 @@
+use anyhow::Result;
+use klad_brush::PressureCurve;
+use klad_core::bundle::write_atomic;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+pub const VERSION: u32 = 2;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Defaults {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub brush: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option<f32>,
+ #[serde(default = "two")]
+ pub exposure: u32,
+ #[serde(default = "two")]
+ pub onion_before: u32,
+ #[serde(default = "two")]
+ pub onion_after: u32,
+ #[serde(default = "half")]
+ pub onion_opacity: f32,
+ #[serde(default = "surround")]
+ pub surround: [u8; 3],
+}
+
+fn two() -> u32 {
+ 2
+}
+
+fn half() -> f32 {
+ 0.5
+}
+
+fn surround() -> [u8; 3] {
+ crate::theme::SURROUND
+}
+
+fn one() -> f32 {
+ 1.0
+}
+
+impl Default for Defaults {
+ fn default() -> Self {
+ Self {
+ brush: None,
+ size: None,
+ exposure: two(),
+ onion_before: two(),
+ onion_after: two(),
+ onion_opacity: half(),
+ surround: surround(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Settings {
+ #[serde(default)]
+ pub version: u32,
+ #[serde(default)]
+ pub pens: BTreeMap<String, PenSettings>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub recent: Vec<String>,
+ #[serde(default)]
+ pub layout: crate::layout::Layout,
+ #[serde(default, rename = "recentCommands", skip_serializing_if = "Vec::is_empty")]
+ pub recent_commands: Vec<String>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub keys: BTreeMap<String, Vec<String>>,
+ #[serde(default = "one", rename = "uiScale")]
+ pub ui_scale: f32,
+ #[serde(default)]
+ pub defaults: Defaults,
+ #[serde(default, rename = "recentDocuments", skip_serializing_if = "Vec::is_empty")]
+ pub documents: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub drawings: Option<String>,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Self {
+ version: VERSION,
+ pens: BTreeMap::new(),
+ recent: Vec::new(),
+ layout: crate::layout::Layout::default(),
+ recent_commands: Vec::new(),
+ keys: BTreeMap::new(),
+ ui_scale: one(),
+ defaults: Defaults::default(),
+ documents: Vec::new(),
+ drawings: None,
+ }
+ }
+}
+
+fn migrate(mut value: serde_json::Value) -> serde_json::Value {
+ if let Some(map) = value.as_object_mut() {
+ map.insert("version".into(), VERSION.into());
+ }
+ value
+}
+
+pub const RECENT: usize = 16;
+
+pub const DOCUMENTS: usize = 12;
+
+pub const ANY_PEN: &str = "tablet";
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct PenSettings {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub curve: Option<PressureCurve>,
+ #[serde(default)]
+ pub peak: f32,
+}
+
+pub fn default_path() -> Option<PathBuf> {
+ if let Some(path) = std::env::var_os("KLAD_SETTINGS") {
+ return Some(PathBuf::from(path));
+ }
+ let home = PathBuf::from(std::env::var_os("HOME")?);
+ let config = match cfg!(target_os = "macos") {
+ true => home.join("Library/Application Support"),
+ false => std::env::var_os("XDG_CONFIG_HOME").map_or(home.join(".config"), PathBuf::from),
+ };
+ Some(carried_over(&config))
+}
+
+pub fn carried_over(config: &Path) -> PathBuf {
+ let path = config.join("klad").join("settings.json");
+ let old = config.join("draw-anything").join("settings.json");
+ if !path.exists() && old.is_file() {
+ let _ = fs::create_dir_all(config.join("klad")).and_then(|_| fs::copy(&old, &path));
+ }
+ path
+}
+
+impl Settings {
+ pub fn load(path: &Path) -> Self {
+ let mut settings: Self = fs::read_to_string(path)
+ .ok()
+ .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
+ .map(migrate)
+ .and_then(|value| serde_json::from_value(value).ok())
+ .unwrap_or_default();
+ settings.layout = settings.layout.repaired();
+ settings.ui_scale = settings.ui_scale.clamp(0.75, 2.0);
+ settings
+ }
+
+ pub fn save(&self, path: &Path) -> Result<()> {
+ let mut text = serde_json::to_string_pretty(self)?;
+ text.push('\n');
+ write_atomic(path, text.as_bytes())
+ }
+
+ pub fn curve(&self, key: &str) -> PressureCurve {
+ [key, ANY_PEN]
+ .iter()
+ .find_map(|k| self.pens.get(*k).and_then(|p| p.curve))
+ .unwrap_or_default()
+ }
+
+ pub fn set_curve(&mut self, key: &str, curve: PressureCurve) {
+ [key, ANY_PEN].iter().for_each(|k| {
+ self.pens.entry(k.to_string()).or_default().curve = Some(curve);
+ });
+ }
+
+ pub fn note_peak(&mut self, key: &str, pressure: f32) -> bool {
+ let pen = self.pens.entry(key.to_string()).or_default();
+ if pressure > pen.peak {
+ pen.peak = pressure;
+ return true;
+ }
+ false
+ }
+
+ pub fn peak(&self, key: &str) -> f32 {
+ self.pens.get(key).map_or(0.0, |p| p.peak)
+ }
+
+ pub fn opened(&mut self, path: &Path) {
+ let path = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+ let text = path.display().to_string();
+ self.documents.retain(|p| *p != text);
+ self.documents.insert(0, text);
+ self.documents.truncate(DOCUMENTS);
+ }
+
+ pub fn forget(&mut self, path: &str) {
+ self.documents.retain(|p| p != path);
+ }
+
+ pub fn drawings_folder(&self) -> PathBuf {
+ self.drawings.as_ref().map_or_else(
+ || {
+ std::env::var_os("HOME")
+ .map_or_else(|| PathBuf::from("Drawings"), |h| PathBuf::from(h).join("Drawings"))
+ },
+ PathBuf::from,
+ )
+ }
+
+ pub fn used(&mut self, hex: &str) -> bool {
+ if self.recent.first().is_some_and(|h| h.eq_ignore_ascii_case(hex)) {
+ return false;
+ }
+ self.recent.retain(|h| !h.eq_ignore_ascii_case(hex));
+ self.recent.insert(0, hex.to_string());
+ self.recent.truncate(RECENT);
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn curves_are_kept_per_pen_and_survive_a_restart() {
+ let dir = std::env::temp_dir().join(format!("draw-settings-{}", std::process::id()));
+ let path = dir.join("settings.json");
+ let mut settings = Settings::load(&path);
+ assert_eq!(settings.curve("pen-1"), PressureCurve::default());
+ let heavy = PressureCurve {
+ low: 0.02,
+ high: 0.88,
+ gamma: 1.2,
+ };
+ settings.set_curve("pen-1", heavy);
+ assert!(settings.note_peak("pen-2", 0.7));
+ assert!(!settings.note_peak("pen-2", 0.6));
+ settings.save(&path).unwrap();
+ let back = Settings::load(&path);
+ assert_eq!(back.curve("pen-1"), heavy);
+ assert_eq!(back.curve("pen-2"), heavy);
+ assert_eq!(back.peak("pen-2"), 0.7);
+ let mut two = back.clone();
+ let light = PressureCurve {
+ gamma: 0.7,
+ ..PressureCurve::default()
+ };
+ two.set_curve("pen-2", light);
+ assert_eq!((two.curve("pen-1"), two.curve("pen-2")), (heavy, light));
+ assert_eq!(Settings::default().curve("pen-9"), PressureCurve::default());
+ let mut colours = Settings::default();
+ assert!(colours.used("#ff0000") && colours.used("#00ff00") && !colours.used("#00FF00"));
+ assert!(colours.used("#ff0000"));
+ (0..30).for_each(|i| {
+ colours.used(&format!("#0000{i:02x}"));
+ });
+ assert_eq!(colours.recent.len(), RECENT);
+ colours.layout.dock_width = 402.0;
+ colours.layout.toggle(crate::layout::Pane::History);
+ colours.recent_commands = vec!["clip.godot".into()];
+ colours.save(&path).unwrap();
+ let again = Settings::load(&path);
+ assert_eq!(again.recent, colours.recent);
+ assert_eq!(again.layout, colours.layout);
+ assert_eq!(again.recent_commands, colours.recent_commands);
+ fs::write(&path, r##"{"pens":{},"recent":["#ff0000"]}"##).unwrap();
+ assert_eq!(Settings::load(&path).layout, crate::layout::Layout::default());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn settings_from_before_the_rename_carry_over_once() {
+ let config = std::env::temp_dir().join(format!("draw-settings-rename-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&config);
+ fs::create_dir_all(config.join("draw-anything")).unwrap();
+ fs::write(config.join("draw-anything/settings.json"), r#"{"uiScale":1.5}"#).unwrap();
+ let path = carried_over(&config);
+ assert_eq!(path, config.join("klad/settings.json"));
+ assert_eq!(Settings::load(&path).ui_scale, 1.5);
+ fs::write(&path, r#"{"uiScale":1.25}"#).unwrap();
+ assert_eq!(Settings::load(&carried_over(&config)).ui_scale, 1.25);
+ fs::remove_dir_all(&config).unwrap();
+ }
+
+ #[test]
+ fn older_settings_load_and_new_ones_keep_keys_scale_and_defaults() {
+ let dir = std::env::temp_dir().join(format!("draw-settings-v1-{}", std::process::id()));
+ let path = dir.join("settings.json");
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(
+ &path,
+ r##"{"pens":{"tablet":{"peak":0.8}},"recent":["#ff0000"],"recentCommands":["tool.brush"]}"##,
+ )
+ .unwrap();
+ let old = Settings::load(&path);
+ assert_eq!(old.version, VERSION);
+ assert_eq!(old.peak("tablet"), 0.8);
+ assert_eq!(old.recent_commands, ["tool.brush"]);
+ assert_eq!(old.ui_scale, 1.0);
+ assert_eq!(old.defaults, Defaults::default());
+ let mut new = old.clone();
+ new.keys.insert("layer.duplicate".into(), vec!["shift D".into()]);
+ new.ui_scale = 1.5;
+ new.defaults.brush = Some("pencil".into());
+ new.defaults.size = Some(6.0);
+ new.defaults.exposure = 3;
+ new.defaults.surround = [20, 20, 24];
+ new.save(&path).unwrap();
+ assert_eq!(Settings::load(&path), new);
+ let (a, b) = (dir.join("a.draw"), dir.join("b.draw"));
+ new.opened(&a);
+ new.opened(&b);
+ new.opened(&a);
+ assert_eq!(new.documents, [a.display().to_string(), b.display().to_string()]);
+ (0..20).for_each(|i| new.opened(&dir.join(format!("{i}.draw"))));
+ assert_eq!(new.documents.len(), DOCUMENTS);
+ new.forget(&new.documents[0].clone());
+ assert_eq!(new.documents.len(), DOCUMENTS - 1);
+ new.drawings = Some("/art".into());
+ assert_eq!(new.drawings_folder(), PathBuf::from("/art"));
+ new.save(&path).unwrap();
+ assert_eq!(Settings::load(&path), new);
+ fs::write(&path, r#"{"version":2,"uiScale":9}"#).unwrap();
+ assert_eq!(Settings::load(&path).ui_scale, 2.0);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/app/src/start.rs b/crates/app/src/start.rs
new file mode 100644
index 0000000..81728e4
--- /dev/null
+++ b/crates/app/src/start.rs
@@ -0,0 +1,566 @@
+use crate::picker;
+use crate::settings::Settings;
+use crate::theme::{self, icon};
+use anyhow::{Result, anyhow, bail};
+use egui::{RichText, TextureHandle, vec2};
+use klad_core::bundle::{Blank, Bundle};
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::sync::mpsc::{Receiver, TryRecvError, channel};
+use std::time::{Duration, SystemTime};
+
+pub const PRESETS: [(&str, u32, u32); 5] = [
+ ("square", 2048, 2048),
+ ("screen", 1920, 1080),
+ ("4K screen", 3840, 2160),
+ ("sprite", 1024, 1024),
+ ("large", 4096, 4096),
+];
+
+const THUMB: f32 = 168.0;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Section {
+ New,
+ Open,
+ Recent,
+}
+
+enum Card {
+ Open(PathBuf),
+ Forget,
+ Idle,
+}
+
+enum Thumb {
+ Waiting(Receiver<Option<egui::ColorImage>>),
+ Ready(TextureHandle),
+ Missing,
+}
+
+pub struct Start {
+ pub name: String,
+ pub folder: String,
+ pub preset: Option<usize>,
+ pub width: u32,
+ pub height: u32,
+ pub paper: bool,
+ pub colour: [u8; 3],
+ pub fps: u32,
+ pub sketch: bool,
+ pub path: String,
+ pub error: Option<String>,
+ pub section: Section,
+ pub changed: bool,
+ focused: bool,
+ thumbs: BTreeMap<String, Thumb>,
+}
+
+impl Start {
+ pub fn new(settings: &Settings, section: Section) -> Self {
+ let blank = Blank::default();
+ let folder = settings.drawings_folder();
+ Self {
+ name: free_name(&folder),
+ folder: folder.display().to_string(),
+ preset: Some(0),
+ width: blank.width,
+ height: blank.height,
+ paper: blank.background.is_some(),
+ colour: [244, 239, 230],
+ fps: blank.fps,
+ sketch: true,
+ path: String::new(),
+ error: None,
+ section,
+ changed: false,
+ focused: false,
+ thumbs: BTreeMap::new(),
+ }
+ }
+
+ pub fn blank(&self) -> Blank {
+ let (width, height) = self
+ .preset
+ .map_or((self.width, self.height), |i| (PRESETS[i].1, PRESETS[i].2));
+ let [r, g, b] = self.colour;
+ Blank {
+ width,
+ height,
+ background: self.paper.then(|| format!("#{r:02x}{g:02x}{b:02x}")),
+ fps: self.fps,
+ sketch: self.sketch,
+ ..Blank::default()
+ }
+ }
+
+ pub fn target(&self) -> PathBuf {
+ let name = self.name.trim();
+ let file = match name.ends_with(".draw") {
+ true => name.to_string(),
+ false => format!("{name}.draw"),
+ };
+ expand(&self.folder).join(file)
+ }
+
+ pub fn create(&self, settings: &mut Settings) -> Result<PathBuf> {
+ let name = self.name.trim();
+ if name.is_empty() {
+ bail!("give the drawing a name");
+ }
+ if name.contains('/') {
+ bail!("a name cannot hold a /: pick the folder in the field below it");
+ }
+ let path = self.target();
+ if path.exists() {
+ bail!("{} already exists: pick another name", path.display());
+ }
+ std::fs::create_dir_all(expand(&self.folder))?;
+ Bundle::blank(&path, &self.blank(), "editor")?;
+ if expand(&self.folder) != settings.drawings_folder() {
+ settings.drawings = Some(expand(&self.folder).display().to_string());
+ }
+ Ok(path)
+ }
+
+ pub fn ui(&mut self, ui: &mut egui::Ui, settings: &mut Settings) -> Option<PathBuf> {
+ let mut chosen = None;
+ egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| {
+ ui.horizontal_top(|ui| {
+ ui.group(|ui| {
+ ui.vertical(|ui| {
+ ui.set_width(420.0);
+ chosen = chosen.take().or_else(|| self.new_section(ui, settings));
+ });
+ });
+ ui.group(|ui| {
+ ui.vertical(|ui| {
+ ui.set_width(290.0);
+ chosen = chosen.take().or_else(|| self.open_section(ui, settings));
+ });
+ });
+ });
+ if let Some(error) = &self.error {
+ ui.add_space(4.0);
+ ui.colored_label(theme::ERROR, error);
+ }
+ ui.add_space(10.0);
+ chosen = chosen.take().or_else(|| self.recent_section(ui, settings));
+ });
+ self.focused = true;
+ chosen
+ }
+
+ fn new_section(&mut self, ui: &mut egui::Ui, settings: &mut Settings) -> Option<PathBuf> {
+ ui.label(
+ RichText::new(format!("{} New drawing", icon::FILE_PLUS))
+ .strong()
+ .size(16.0),
+ );
+ ui.add_space(6.0);
+ let mut entered = false;
+ egui::Grid::new("start new")
+ .num_columns(2)
+ .spacing(vec2(10.0, 8.0))
+ .show(ui, |ui| {
+ let label = ui.label("Name");
+ let name = ui
+ .add(egui::TextEdit::singleline(&mut self.name).desired_width(260.0))
+ .labelled_by(label.id);
+ if !self.focused && self.section == Section::New {
+ name.request_focus();
+ }
+ entered = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
+ ui.end_row();
+ let label = ui.label("Folder");
+ ui.horizontal(|ui| {
+ ui.add(egui::TextEdit::singleline(&mut self.folder).desired_width(200.0))
+ .labelled_by(label.id);
+ if picker::NATIVE
+ && ui.button("Choose").clicked()
+ && let Some(dir) = picker::choose_folder(Some(&expand(&self.folder)), "Choose")
+ {
+ self.folder = dir.display().to_string();
+ }
+ });
+ ui.end_row();
+ let label = ui.label("Size");
+ let shown = self.preset.map_or("custom".to_string(), preset_name);
+ egui::ComboBox::from_id_salt("start size")
+ .selected_text(shown)
+ .width(260.0)
+ .show_ui(ui, |ui| {
+ (0..PRESETS.len()).for_each(|i| {
+ ui.selectable_value(&mut self.preset, Some(i), preset_name(i));
+ });
+ ui.selectable_value(&mut self.preset, None, "custom");
+ })
+ .response
+ .labelled_by(label.id);
+ ui.end_row();
+ if self.preset.is_none() {
+ ui.label("Width and height");
+ ui.horizontal(|ui| {
+ ui.add(egui::DragValue::new(&mut self.width).range(1..=16384).suffix(" px"));
+ ui.label("by");
+ ui.add(egui::DragValue::new(&mut self.height).range(1..=16384).suffix(" px"));
+ });
+ ui.end_row();
+ }
+ ui.label("Background");
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut self.paper, "Colour");
+ match self.paper {
+ true => {
+ egui::color_picker::color_edit_button_srgb(ui, &mut self.colour);
+ }
+ false => {
+ ui.label(RichText::new("transparent").color(theme::WEAK));
+ }
+ }
+ });
+ ui.end_row();
+ let label = ui.label("Frames per second");
+ ui.add(egui::DragValue::new(&mut self.fps).range(1..=120))
+ .labelled_by(label.id);
+ ui.end_row();
+ });
+ ui.checkbox(&mut self.sketch, "A sketch layer for blocking in shapes");
+ ui.add_space(6.0);
+ if !(ui.add(egui::Button::new("Create").min_size(vec2(96.0, 28.0))).clicked() || entered) {
+ return None;
+ }
+ match self.create(settings) {
+ Ok(path) => {
+ self.changed = true;
+ Some(path)
+ }
+ Err(e) => {
+ self.error = Some(format!("{e:#}"));
+ None
+ }
+ }
+ }
+
+ fn open_section(&mut self, ui: &mut egui::Ui, settings: &Settings) -> Option<PathBuf> {
+ ui.label(
+ RichText::new(format!("{} Open a drawing", icon::FOLDER_OPEN))
+ .strong()
+ .size(16.0),
+ );
+ ui.add_space(6.0);
+ let mut picked = None;
+ if picker::NATIVE
+ && ui
+ .add(egui::Button::new("Choose a .draw folder...").min_size(vec2(200.0, 28.0)))
+ .clicked()
+ {
+ picked = picker::choose_folder(Some(&settings.drawings_folder()), "Open");
+ }
+ ui.add_space(6.0);
+ let label = ui.label(RichText::new("Or paste its path").color(theme::WEAK));
+ ui.horizontal(|ui| {
+ let field = ui
+ .add(egui::TextEdit::singleline(&mut self.path).desired_width(220.0))
+ .labelled_by(label.id);
+ if !self.focused && self.section == Section::Open {
+ field.request_focus();
+ }
+ let entered = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
+ if ui.button("Open").clicked() || entered {
+ picked = Some(expand(self.path.trim()));
+ }
+ });
+ let path = picked?;
+ match openable(&path) {
+ Ok(()) => Some(path),
+ Err(e) => {
+ self.error = Some(format!("{e:#}"));
+ None
+ }
+ }
+ }
+
+ fn recent_section(&mut self, ui: &mut egui::Ui, settings: &mut Settings) -> Option<PathBuf> {
+ ui.label(RichText::new(format!("{} Recent", icon::HISTORY)).strong().size(16.0));
+ ui.add_space(6.0);
+ if settings.documents.is_empty() {
+ ui.label(RichText::new("Drawings you open show up here.").color(theme::WEAK));
+ return None;
+ }
+ let mut chosen = None;
+ let documents = settings.documents.clone();
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing = vec2(12.0, 12.0);
+ documents.iter().for_each(|doc| {
+ ui.vertical(|ui| {
+ ui.set_width(THUMB + 8.0);
+ match self.card(ui, doc) {
+ Card::Open(path) => chosen = Some(path),
+ Card::Forget => {
+ settings.forget(doc);
+ self.changed = true;
+ }
+ Card::Idle => {}
+ }
+ });
+ });
+ });
+ chosen
+ }
+
+ fn card(&mut self, ui: &mut egui::Ui, doc: &str) -> Card {
+ let path = PathBuf::from(doc);
+ let there = path.join("doc.json").is_file();
+ let name = path
+ .file_stem()
+ .map_or_else(|| doc.to_string(), |s| s.to_string_lossy().to_string());
+ let (rect, response) = ui.allocate_exact_size(vec2(THUMB + 8.0, THUMB + 32.0), egui::Sense::click());
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, there, &name));
+ let look = ui.style().interact(&response);
+ let fill = match there {
+ true => look.weak_bg_fill,
+ false => ui.visuals().faint_bg_color,
+ };
+ ui.painter()
+ .rect(rect, 6.0, fill, look.bg_stroke, egui::StrokeKind::Inside);
+ let picture = egui::Rect::from_min_size(rect.min + vec2(4.0, 4.0), vec2(THUMB, THUMB));
+ if let Some(texture) = there.then(|| self.thumb(ui.ctx(), doc)).flatten() {
+ egui::Image::new(&texture).paint_at(
+ ui,
+ egui::Rect::from_center_size(picture.center(), fit(texture.size_vec2())),
+ );
+ }
+ let colour = match there {
+ true => look.text_color(),
+ false => theme::WEAK,
+ };
+ let galley = egui::WidgetText::from(name.as_str()).into_galley(
+ ui,
+ Some(egui::TextWrapMode::Truncate),
+ THUMB - 8.0,
+ egui::TextStyle::Body,
+ );
+ ui.painter()
+ .galley(egui::pos2(rect.min.x + 8.0, rect.max.y - 24.0), galley, colour);
+ let folder = path
+ .parent()
+ .and_then(Path::file_name)
+ .map_or_else(String::new, |s| s.to_string_lossy().to_string());
+ let clicked = there && response.on_hover_text(doc).clicked();
+ ui.add(egui::Label::new(RichText::new(format!("in {folder}")).color(theme::WEAK).size(11.0)).truncate());
+ if clicked {
+ return Card::Open(path);
+ }
+ if !there {
+ ui.label(RichText::new("moved or deleted").color(theme::REFUSED));
+ if ui.button(format!("Remove {name}")).clicked() {
+ return Card::Forget;
+ }
+ }
+ Card::Idle
+ }
+
+ fn thumb(&mut self, ctx: &egui::Context, doc: &str) -> Option<TextureHandle> {
+ let state = self.thumbs.entry(doc.to_string()).or_insert_with(|| {
+ let (tx, rx) = channel();
+ let path = PathBuf::from(doc);
+ let repaint = ctx.clone();
+ std::thread::spawn(move || {
+ let image = thumbnail(&path);
+ let _ = tx.send(image);
+ repaint.request_repaint();
+ });
+ Thumb::Waiting(rx)
+ });
+ if let Thumb::Waiting(rx) = state {
+ *state = match rx.try_recv() {
+ Ok(Some(image)) => {
+ Thumb::Ready(ctx.load_texture(format!("thumb {doc}"), image, egui::TextureOptions::LINEAR))
+ }
+ Ok(None) | Err(TryRecvError::Disconnected) => Thumb::Missing,
+ Err(TryRecvError::Empty) => {
+ ctx.request_repaint_after(Duration::from_millis(200));
+ return None;
+ }
+ };
+ }
+ match state {
+ Thumb::Ready(texture) => Some(texture.clone()),
+ _ => None,
+ }
+ }
+}
+
+fn preset_name(i: usize) -> String {
+ let (name, w, h) = PRESETS[i];
+ format!("{w} x {h} {name}")
+}
+
+fn fit(size: egui::Vec2) -> egui::Vec2 {
+ size * (THUMB / size.x.max(size.y).max(1.0))
+}
+
+pub fn expand(text: &str) -> PathBuf {
+ match (text.strip_prefix("~/"), std::env::var_os("HOME")) {
+ (Some(rest), Some(home)) => PathBuf::from(home).join(rest),
+ _ => PathBuf::from(text),
+ }
+}
+
+pub fn openable(path: &Path) -> Result<()> {
+ if path.as_os_str().is_empty() {
+ bail!("paste the path of a .draw folder");
+ }
+ if !path.is_dir() {
+ bail!("{} is not a folder", path.display());
+ }
+ if !path.join("doc.json").is_file() {
+ bail!("{} is not a drawing: it has no doc.json", path.display());
+ }
+ Ok(())
+}
+
+pub fn free_name(folder: &Path) -> String {
+ (1..)
+ .map(|i| match i {
+ 1 => "untitled".to_string(),
+ n => format!("untitled {n}"),
+ })
+ .find(|name| !folder.join(format!("{name}.draw")).exists())
+ .unwrap_or_default()
+}
+
+fn draw_binary() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ if exe.file_stem().is_some_and(|s| s == "klad") {
+ return Some(exe);
+ }
+ let sibling = exe.parent()?.parent()?.join("klad");
+ sibling.is_file().then_some(sibling)
+}
+
+fn modified(path: &Path) -> Option<SystemTime> {
+ std::fs::metadata(path).and_then(|m| m.modified()).ok()
+}
+
+fn thumbnail(bundle: &Path) -> Option<egui::ColorImage> {
+ static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
+ let png = bundle.join(".cache").join("thumb.png");
+ let fresh = matches!((modified(&png), modified(&bundle.join("doc.json"))), (Some(t), Some(d)) if t >= d);
+ if !fresh {
+ let _turn = ONE_AT_A_TIME.lock().ok()?;
+ let doc: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(bundle.join("doc.json")).ok()?).ok()?;
+ let side = ["width", "height"]
+ .iter()
+ .filter_map(|k| doc["canvas"][k].as_f64())
+ .fold(1.0, f64::max);
+ let done = std::process::Command::new(draw_binary()?)
+ .env("RAYON_NUM_THREADS", "2")
+ .arg("render")
+ .arg(bundle)
+ .arg("--scale")
+ .arg(format!("{:.4}", (2.0 * THUMB as f64 / side).min(1.0)))
+ .arg("-o")
+ .arg(&png)
+ .output()
+ .ok()?;
+ if !done.status.success() {
+ return None;
+ }
+ }
+ decode(&std::fs::read(&png).ok()?).ok()
+}
+
+fn decode(bytes: &[u8]) -> Result<egui::ColorImage> {
+ let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
+ decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
+ let mut reader = decoder.read_info()?;
+ let mut buffer = vec![0; reader.output_buffer_size().ok_or_else(|| anyhow!("a png too large"))?];
+ let info = reader.next_frame(&mut buffer)?;
+ let pixels = &buffer[..info.buffer_size()];
+ let size = [info.width as usize, info.height as usize];
+ Ok(match info.color_type {
+ png::ColorType::Rgba => egui::ColorImage::from_rgba_unmultiplied(size, pixels),
+ png::ColorType::Rgb => egui::ColorImage::from_rgb(size, pixels),
+ other => bail!("thumbnails are rgb or rgba pngs, not {other:?}"),
+ })
+}
+
+pub fn title(path: Option<&Path>) -> String {
+ match path {
+ Some(path) => format!(
+ "{} klad",
+ path.file_stem()
+ .map_or_else(|| path.display().to_string(), |s| s.to_string_lossy().to_string())
+ ),
+ None => "klad".to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_thumbnail_is_rendered_once_and_again_when_the_drawing_changes() {
+ assert!(draw_binary().is_some(), "build the klad binary first (just test does)");
+ let dir = std::env::temp_dir().join(format!("draw-thumb-{}.draw", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let blank = Blank {
+ width: 400,
+ height: 200,
+ background: Some("#336699".into()),
+ ..Blank::default()
+ };
+ Bundle::blank(&dir, &blank, "cli").unwrap();
+ let image = thumbnail(&dir).unwrap();
+ assert_eq!(image.size, [336, 168]);
+ let middle = image.pixels[84 * 336 + 168];
+ assert!(
+ middle.r().abs_diff(0x33) <= 2 && middle.b().abs_diff(0x99) <= 2,
+ "{middle:?}"
+ );
+ let png = dir.join(".cache").join("thumb.png");
+ let first = modified(&png).unwrap();
+ thumbnail(&dir).unwrap();
+ assert_eq!(modified(&png), Some(first));
+ std::thread::sleep(Duration::from_millis(20));
+ Bundle::open(&dir).unwrap().save().unwrap();
+ thumbnail(&dir).unwrap();
+ assert!(modified(&png).unwrap() > first);
+ assert_eq!(free_name(dir.parent().unwrap()), "untitled");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn names_paths_and_sizes_come_out_as_typed() {
+ let settings = Settings {
+ drawings: Some("/art".into()),
+ ..Settings::default()
+ };
+ let mut start = Start::new(&settings, Section::New);
+ start.name = " cave ".into();
+ assert_eq!(start.target(), PathBuf::from("/art/cave.draw"));
+ start.name = "cave.draw".into();
+ assert_eq!(start.target(), PathBuf::from("/art/cave.draw"));
+ assert_eq!(
+ (start.blank().width, start.blank().height, start.blank().background),
+ (2048, 2048, None)
+ );
+ start.preset = None;
+ (start.width, start.height, start.paper) = (640, 360, true);
+ assert_eq!(
+ (start.blank().width, start.blank().height, start.blank().background),
+ (640, 360, Some("#f4efe6".to_string()))
+ );
+ start.name = "a/b".into();
+ assert!(format!("{:#}", start.create(&mut Settings::default()).unwrap_err()).contains("cannot hold a /"));
+ assert!(format!("{:#}", openable(Path::new("/nowhere")).unwrap_err()).contains("is not a folder"));
+ if let Some(home) = std::env::var_os("HOME") {
+ assert_eq!(expand("~/art"), PathBuf::from(home).join("art"));
+ }
+ }
+}
diff --git a/crates/app/src/stats.rs b/crates/app/src/stats.rs
new file mode 100644
index 0000000..203f24e
--- /dev/null
+++ b/crates/app/src/stats.rs
@@ -0,0 +1,92 @@
+use std::collections::VecDeque;
+use std::sync::{Mutex, MutexGuard};
+
+const WINDOW: usize = 240;
+
+#[derive(Default)]
+pub struct Rolling {
+ values: VecDeque<f32>,
+}
+
+impl Rolling {
+ pub fn push(&mut self, value: f32) {
+ if self.values.len() == WINDOW {
+ self.values.pop_front();
+ }
+ self.values.push_back(value);
+ }
+
+ pub fn avg(&self) -> f32 {
+ self.values.iter().sum::<f32>() / self.values.len().max(1) as f32
+ }
+
+ pub fn max(&self) -> f32 {
+ self.values.iter().copied().fold(0.0, f32::max)
+ }
+
+ pub fn percentile(&self, p: f32) -> f32 {
+ let mut sorted: Vec<f32> = self.values.iter().copied().collect();
+ sorted.sort_by(f32::total_cmp);
+ sorted
+ .get(((sorted.len() as f32 - 1.0) * p).round().max(0.0) as usize)
+ .copied()
+ .unwrap_or(0.0)
+ }
+
+ pub fn spread(&self) -> String {
+ if self.values.is_empty() {
+ "-".to_string()
+ } else {
+ format!(
+ "median {:.2} p99 {:.2} max {:.1}",
+ self.percentile(0.5),
+ self.percentile(0.99),
+ self.max()
+ )
+ }
+ }
+
+ pub fn summary(&self) -> String {
+ if self.values.is_empty() {
+ "-".to_string()
+ } else {
+ format!("avg {:.1} max {:.1}", self.avg(), self.max())
+ }
+ }
+}
+
+#[derive(Default)]
+pub struct Stats {
+ pub frame_ms: Rolling,
+ pub latency_ms: Rolling,
+ pub compose_ms: Rolling,
+ pub tiles: Rolling,
+ pub upload_ms: Rolling,
+ pub step_ms: Rolling,
+ pub frame_upload_ms: Rolling,
+ pub ui_ms: Rolling,
+}
+
+pub fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rolling_keeps_a_window() {
+ let mut r = Rolling::default();
+ (0..WINDOW + 10).for_each(|i| r.push(i as f32));
+ assert_eq!(r.max(), (WINDOW + 9) as f32);
+ assert_eq!(r.values.len(), WINDOW);
+ assert!(r.avg() > 10.0);
+ let mut q = Rolling::default();
+ [5.0, 1.0, 3.0, 2.0, 4.0].iter().for_each(|v| q.push(*v));
+ assert_eq!(
+ (q.percentile(0.5), q.percentile(0.99), q.percentile(0.0)),
+ (3.0, 5.0, 1.0)
+ );
+ }
+}
diff --git a/crates/app/src/sync.rs b/crates/app/src/sync.rs
new file mode 100644
index 0000000..a187d6c
--- /dev/null
+++ b/crates/app/src/sync.rs
@@ -0,0 +1,48 @@
+use anyhow::Result;
+use klad_core::bundle::now_ms;
+use notify::{RecommendedWatcher, RecursiveMode, Watcher};
+use std::path::Path;
+use std::sync::mpsc::{Receiver, channel};
+
+pub struct Watch {
+ _watcher: RecommendedWatcher,
+ pub events: Receiver<u64>,
+}
+
+pub fn relevant(path: &Path) -> bool {
+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ !name.contains(".tmp-")
+ && (name == "doc.json" || name == "sync.json" || name == "notes.json" || name.ends_with(".strokes"))
+}
+
+pub fn watch(root: &Path, ctx: egui::Context) -> Result<Watch> {
+ let (tx, events) = channel();
+ let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
+ if let Ok(event) = res
+ && event.paths.iter().any(|p| relevant(p))
+ {
+ let _ = tx.send(now_ms());
+ ctx.request_repaint();
+ }
+ })?;
+ watcher.watch(root, RecursiveMode::Recursive)?;
+ Ok(Watch {
+ _watcher: watcher,
+ events,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_document_files_count() {
+ assert!(relevant(Path::new("a.draw/doc.json")));
+ assert!(relevant(Path::new("a.draw/.cache/sync.json")));
+ assert!(relevant(Path::new("a.draw/.cache/notes.json")));
+ assert!(relevant(Path::new("a.draw/strokes/l1/c0.strokes")));
+ assert!(!relevant(Path::new("a.draw/doc.json.tmp-123")));
+ assert!(!relevant(Path::new("a.draw/.cache/tiles/l1.raster")));
+ }
+}
diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs
new file mode 100644
index 0000000..d104cf8
--- /dev/null
+++ b/crates/app/src/theme.rs
@@ -0,0 +1,238 @@
+use egui::{
+ Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Id, Margin, Rect, Response, Shadow, Stroke,
+ Style, TextStyle, WidgetText, vec2,
+};
+use std::sync::Arc;
+
+pub const TARGET: f32 = 24.0;
+pub const GRAB: f32 = 12.0;
+pub const ROW: f32 = 28.0;
+pub const SMALL: f32 = 11.0;
+pub const BODY: f32 = 13.0;
+pub const HEADING: f32 = 15.0;
+pub const ICON: f32 = 17.0;
+
+pub const ACCENT: Color32 = Color32::from_rgb(64, 196, 255);
+pub const DONE: Color32 = Color32::from_rgb(120, 200, 140);
+pub const REFUSED: Color32 = Color32::from_rgb(232, 190, 110);
+pub const ERROR: Color32 = Color32::from_rgb(240, 120, 120);
+pub const TEXT: Color32 = Color32::from_gray(214);
+pub const WEAK: Color32 = Color32::from_gray(150);
+pub const PANEL: Color32 = Color32::from_gray(34);
+pub const SURROUND: [u8; 3] = [58, 58, 58];
+
+pub mod icon {
+ pub const BRUSH: &str = "\u{E6F0}";
+ pub const SUN: &str = "\u{E472}";
+ pub const ADJUST: &str = "\u{E434}";
+ pub const SPARKLE: &str = "\u{E6A2}";
+ pub const RECTANGLE: &str = "\u{E3F0}";
+ pub const MOUNTAINS: &str = "\u{E7AE}";
+ pub const REPEAT: &str = "\u{E3F6}";
+ pub const SCATTER: &str = "\u{E1FC}";
+ pub const IMAGE: &str = "\u{E2CA}";
+ pub const ERASER: &str = "\u{E21E}";
+ pub const FILL: &str = "\u{E392}";
+ pub const SHAPES: &str = "\u{E1DC}";
+ pub const STROKES: &str = "\u{E69A}";
+ pub const POINTS: &str = "\u{EB00}";
+ pub const PEN: &str = "\u{E3AC}";
+ pub const PREPARE: &str = "\u{E2DE}";
+ pub const NOTE: &str = "\u{E3E2}";
+ pub const EYEDROPPER: &str = "\u{E568}";
+ pub const MINUS: &str = "\u{E32A}";
+ pub const PLUS: &str = "\u{E3D4}";
+ pub const HAND: &str = "\u{E298}";
+ pub const ZOOM: &str = "\u{E30C}";
+ pub const SEARCH: &str = "\u{E30C}";
+ pub const FIT: &str = "\u{E1D0}";
+ pub const TURN: &str = "\u{E036}";
+ pub const UNDO: &str = "\u{E08A}";
+ pub const REDO: &str = "\u{E08C}";
+ pub const TRASH: &str = "\u{E4A6}";
+ pub const CLOSE: &str = "\u{E4F6}";
+ pub const COPY: &str = "\u{E1CA}";
+ pub const PASTE: &str = "\u{E198}";
+ pub const SELECT_ALL: &str = "\u{E746}";
+ pub const LASSO: &str = "\u{EDC6}";
+ pub const PALETTE: &str = "\u{E6C8}";
+ pub const FLIP_H: &str = "\u{ED6A}";
+ pub const FLIP_V: &str = "\u{ED6C}";
+ pub const LAYERS: &str = "\u{E466}";
+ pub const EYE: &str = "\u{E220}";
+ pub const EYE_OFF: &str = "\u{E224}";
+ pub const LOCK: &str = "\u{E2FA}";
+ pub const CLIP: &str = "\u{E2D2}";
+ pub const MASK: &str = "\u{E18C}";
+ pub const ONION: &str = "\u{E62A}";
+ pub const STEP_ON: &str = "\u{E13A}";
+ pub const STEP_BACK: &str = "\u{E138}";
+ pub const NEXT: &str = "\u{E5A6}";
+ pub const PREVIOUS: &str = "\u{E5A4}";
+ pub const NEW_DRAWING: &str = "\u{E236}";
+ pub const LINK: &str = "\u{E2E2}";
+ pub const UNLINK: &str = "\u{E2E4}";
+ pub const INSERT: &str = "\u{E542}";
+ pub const REMOVE: &str = "\u{ED4C}";
+ pub const FLIP_FRAMES: &str = "\u{E0A0}";
+ pub const PLAY: &str = "\u{E3D0}";
+ pub const LOOP: &str = "\u{E3F6}";
+ pub const SETTINGS: &str = "\u{E270}";
+ pub const RETIME: &str = "\u{E492}";
+ pub const INBETWEEN: &str = "\u{EA9A}";
+ pub const CLIP_BAR: &str = "\u{E8C2}";
+ pub const EXPORT: &str = "\u{EAF0}";
+ pub const KEYBOARD: &str = "\u{E2D8}";
+ pub const SIDEBAR: &str = "\u{EC24}";
+ pub const INSPECTOR: &str = "\u{E434}";
+ pub const HISTORY: &str = "\u{E1A0}";
+ pub const TIMELINE: &str = "\u{E792}";
+ pub const NUMBERS: &str = "\u{E628}";
+ pub const LOG: &str = "\u{E2F0}";
+ pub const UP: &str = "\u{E08E}";
+ pub const DOWN: &str = "\u{E03E}";
+ pub const LEFT: &str = "\u{E058}";
+ pub const RIGHT: &str = "\u{E06C}";
+ pub const TURN_LEFT: &str = "\u{E038}";
+ pub const SWAP: &str = "\u{E83C}";
+ pub const SIZE: &str = "\u{E18A}";
+ pub const MORE: &str = "\u{E1FE}";
+ pub const OPEN: &str = "\u{E136}";
+ pub const FOLDED: &str = "\u{E13A}";
+ pub const CHECK: &str = "\u{E182}";
+ pub const WARNING: &str = "\u{E4E2}";
+ pub const INFO: &str = "\u{E2CE}";
+ pub const FILE: &str = "\u{E230}";
+ pub const FILE_PLUS: &str = "\u{E236}";
+ pub const FOLDER_OPEN: &str = "\u{E256}";
+}
+
+pub fn install(ctx: &egui::Context) {
+ let mut fonts = FontDefinitions::default();
+ fonts.font_data.insert(
+ "phosphor".into(),
+ Arc::new(FontData::from_static(include_bytes!("../assets/Phosphor.ttf"))),
+ );
+ [FontFamily::Proportional, FontFamily::Monospace]
+ .iter()
+ .for_each(|family| {
+ fonts
+ .families
+ .entry(family.clone())
+ .or_default()
+ .push("phosphor".into());
+ });
+ ctx.set_fonts(fonts);
+ ctx.set_theme(egui::Theme::Dark);
+ ctx.all_styles_mut(apply);
+}
+
+pub fn apply(style: &mut Style) {
+ style.text_styles = [
+ (TextStyle::Small, FontId::proportional(SMALL)),
+ (TextStyle::Body, FontId::proportional(BODY)),
+ (TextStyle::Button, FontId::proportional(BODY)),
+ (TextStyle::Monospace, FontId::monospace(12.0)),
+ (TextStyle::Heading, FontId::proportional(HEADING)),
+ ]
+ .into();
+ let s = &mut style.spacing;
+ s.item_spacing = vec2(6.0, 5.0);
+ s.button_padding = vec2(8.0, 4.0);
+ s.interact_size = vec2(36.0, TARGET);
+ s.icon_width = 16.0;
+ s.icon_width_inner = 9.0;
+ s.icon_spacing = 6.0;
+ s.slider_width = 120.0;
+ s.combo_width = 140.0;
+ s.window_margin = Margin::same(10);
+ s.menu_margin = Margin::same(6);
+ style.interaction.tooltip_delay = 0.35;
+ style.interaction.show_tooltips_only_when_still = true;
+ let v = &mut style.visuals;
+ v.dark_mode = true;
+ v.panel_fill = PANEL;
+ v.window_fill = Color32::from_gray(38);
+ v.window_stroke = Stroke::new(1.0, Color32::from_gray(60));
+ v.window_corner_radius = CornerRadius::same(6);
+ v.menu_corner_radius = CornerRadius::same(5);
+ v.window_shadow = Shadow {
+ offset: [0, 4],
+ blur: 14,
+ spread: 0,
+ color: Color32::from_black_alpha(90),
+ };
+ v.popup_shadow = v.window_shadow;
+ v.extreme_bg_color = Color32::from_gray(22);
+ v.faint_bg_color = Color32::from_gray(40);
+ v.code_bg_color = Color32::from_gray(30);
+ v.selection.bg_fill = Color32::from_rgb(38, 96, 128);
+ v.selection.stroke = Stroke::new(1.0, ACCENT);
+ v.hyperlink_color = ACCENT;
+ v.warn_fg_color = REFUSED;
+ v.error_fg_color = ERROR;
+ v.override_text_color = None;
+ let w = &mut v.widgets;
+ w.noninteractive.bg_fill = PANEL;
+ w.noninteractive.weak_bg_fill = PANEL;
+ w.noninteractive.bg_stroke = Stroke::new(1.0, Color32::from_gray(52));
+ w.noninteractive.fg_stroke = Stroke::new(1.0, TEXT);
+ w.inactive.bg_fill = Color32::from_gray(52);
+ w.inactive.weak_bg_fill = Color32::from_gray(46);
+ w.inactive.bg_stroke = Stroke::NONE;
+ w.inactive.fg_stroke = Stroke::new(1.0, TEXT);
+ w.hovered.bg_fill = Color32::from_gray(64);
+ w.hovered.weak_bg_fill = Color32::from_gray(60);
+ w.hovered.bg_stroke = Stroke::new(1.0, Color32::from_gray(96));
+ w.hovered.fg_stroke = Stroke::new(1.5, Color32::from_gray(236));
+ w.active.bg_fill = Color32::from_gray(74);
+ w.active.weak_bg_fill = Color32::from_gray(70);
+ w.active.bg_stroke = Stroke::new(1.0, ACCENT);
+ w.active.fg_stroke = Stroke::new(2.0, Color32::WHITE);
+ w.open.bg_fill = Color32::from_gray(48);
+ w.open.weak_bg_fill = Color32::from_gray(48);
+ [
+ &mut w.noninteractive,
+ &mut w.inactive,
+ &mut w.hovered,
+ &mut w.active,
+ &mut w.open,
+ ]
+ .into_iter()
+ .for_each(|w| {
+ w.corner_radius = CornerRadius::same(4);
+ w.expansion = 0.0;
+ });
+}
+
+pub fn surround(rgb: [u8; 3]) -> [f32; 4] {
+ let [r, g, b] = rgb.map(|c| c as f32 / 255.0);
+ [r, g, b, 1.0]
+}
+
+fn hinted_id() -> Id {
+ Id::unique("klad hinted controls")
+}
+
+pub fn clear_hints(ctx: &egui::Context) {
+ ctx.data_mut(|d| d.insert_temp::<Vec<Rect>>(hinted_id(), Vec::new()));
+}
+
+#[cfg(test)]
+pub fn hinted(ctx: &egui::Context) -> Vec<Rect> {
+ ctx.data(|d| d.get_temp::<Vec<Rect>>(hinted_id()).unwrap_or_default())
+}
+
+pub trait Hint {
+ fn hint(self, text: impl Into<WidgetText>) -> Response;
+}
+
+impl Hint for Response {
+ fn hint(self, text: impl Into<WidgetText>) -> Response {
+ let rect = self.rect;
+ self.ctx.data_mut(|d| {
+ d.get_temp_mut_or_default::<Vec<Rect>>(hinted_id()).push(rect);
+ });
+ self.on_hover_text(text)
+ }
+}
diff --git a/crates/app/src/view.rs b/crates/app/src/view.rs
new file mode 100644
index 0000000..d9c7432
--- /dev/null
+++ b/crates/app/src/view.rs
@@ -0,0 +1,170 @@
+use egui::Vec2;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct View {
+ pub center: Vec2,
+ pub zoom: f32,
+ pub angle: f32,
+ pub flip: bool,
+}
+
+fn rotate(v: Vec2, angle: f32) -> Vec2 {
+ let (s, c) = angle.sin_cos();
+ Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c)
+}
+
+fn mirror(v: Vec2, flip: bool) -> Vec2 {
+ match flip {
+ true => Vec2::new(-v.x, v.y),
+ false => v,
+ }
+}
+
+impl View {
+ pub fn fit(canvas: Vec2, area: Vec2) -> Self {
+ Self {
+ center: canvas / 2.0,
+ zoom: (area.x / canvas.x).min(area.y / canvas.y) * 0.92,
+ angle: 0.0,
+ flip: false,
+ }
+ }
+
+ pub fn to_screen(self, canvas: Vec2, area: Vec2) -> Vec2 {
+ rotate(mirror(canvas - self.center, self.flip), self.angle) * self.zoom + area / 2.0
+ }
+
+ pub fn to_canvas(self, screen: Vec2, area: Vec2) -> Vec2 {
+ mirror(rotate((screen - area / 2.0) / self.zoom, -self.angle), self.flip) + self.center
+ }
+
+ pub fn pan(&mut self, delta: Vec2) {
+ self.center -= mirror(rotate(delta / self.zoom, -self.angle), self.flip);
+ }
+
+ fn keep(&mut self, anchor: Vec2, at: Vec2, area: Vec2) {
+ self.center = anchor - mirror(rotate((at - area / 2.0) / self.zoom, -self.angle), self.flip);
+ }
+
+ pub fn flip_at(&mut self, at: Vec2, area: Vec2) {
+ let anchor = self.to_canvas(at, area);
+ self.flip = !self.flip;
+ self.keep(anchor, at, area);
+ }
+
+ pub fn zoom_at(&mut self, factor: f32, at: Vec2, area: Vec2) {
+ let anchor = self.to_canvas(at, area);
+ self.zoom = (self.zoom * factor).clamp(0.02, 64.0);
+ self.keep(anchor, at, area);
+ }
+
+ pub fn rotate_at(&mut self, delta: f32, at: Vec2, area: Vec2) {
+ let anchor = self.to_canvas(at, area);
+ self.angle += delta;
+ self.keep(anchor, at, area);
+ }
+
+ pub fn uniform(self, area: Vec2, pixels_per_point: f32, canvas: Vec2) -> [f32; 12] {
+ let (s, c) = self.angle.sin_cos();
+ let k = pixels_per_point * self.zoom;
+ let f = if self.flip { -1.0 } else { 1.0 };
+ let (m00, m01, m10, m11) = (k * c * f, -k * s, k * s * f, k * c);
+ let t = area * pixels_per_point / 2.0
+ - Vec2::new(
+ m00 * self.center.x + m01 * self.center.y,
+ m10 * self.center.x + m11 * self.center.y,
+ );
+ [
+ m00,
+ m01,
+ m10,
+ m11,
+ t.x,
+ t.y,
+ area.x * pixels_per_point,
+ area.y * pixels_per_point,
+ canvas.x,
+ canvas.y,
+ pixels_per_point,
+ 8.0 * pixels_per_point,
+ ]
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn close(a: Vec2, b: Vec2) -> bool {
+ (a - b).length() < 1e-3
+ }
+
+ #[test]
+ fn screen_and_canvas_round_trip() {
+ let area = Vec2::new(1200.0, 800.0);
+ let mut view = View::fit(Vec2::new(4096.0, 2048.0), area);
+ view.angle = 0.7;
+ let p = Vec2::new(321.0, 654.0);
+ assert!(close(view.to_canvas(view.to_screen(p, area), area), p));
+ }
+
+ #[test]
+ fn zoom_and_rotate_keep_the_anchor() {
+ let area = Vec2::new(1000.0, 700.0);
+ let mut view = View::fit(Vec2::new(2048.0, 2048.0), area);
+ let at = Vec2::new(250.0, 600.0);
+ let anchor = view.to_canvas(at, area);
+ view.zoom_at(3.0, at, area);
+ view.rotate_at(0.4, at, area);
+ assert!(close(view.to_canvas(at, area), anchor));
+ }
+
+ #[test]
+ fn uniform_matches_to_screen() {
+ let area = Vec2::new(900.0, 600.0);
+ let mut view = View::fit(Vec2::new(1024.0, 1024.0), area);
+ view.angle = -0.3;
+ let u = view.uniform(area, 2.0, Vec2::new(1024.0, 1024.0));
+ let p = Vec2::new(100.0, 700.0);
+ let px = Vec2::new(u[0] * p.x + u[1] * p.y + u[4], u[2] * p.x + u[3] * p.y + u[5]);
+ assert!(close(px, view.to_screen(p, area) * 2.0));
+ }
+
+ #[test]
+ fn a_flipped_view_mirrors_and_still_maps_both_ways() {
+ let area = Vec2::new(900.0, 600.0);
+ let mut view = View::fit(Vec2::new(1000.0, 800.0), area);
+ let left = Vec2::new(100.0, 400.0);
+ let right = Vec2::new(900.0, 400.0);
+ let (l, r) = (view.to_screen(left, area), view.to_screen(right, area));
+ assert!(l.x < r.x);
+ view.flip_at(area / 2.0, area);
+ assert!(view.to_screen(left, area).x > view.to_screen(right, area).x);
+ assert!(close(view.to_screen(left, area), Vec2::new(r.x, l.y)));
+ view.angle = 0.4;
+ view.zoom_at(1.7, Vec2::new(200.0, 100.0), area);
+ let p = Vec2::new(321.0, 654.0);
+ assert!(close(view.to_canvas(view.to_screen(p, area), area), p));
+ let u = view.uniform(area, 2.0, Vec2::new(1000.0, 800.0));
+ let px = Vec2::new(u[0] * p.x + u[1] * p.y + u[4], u[2] * p.x + u[3] * p.y + u[5]);
+ assert!(close(px, view.to_screen(p, area) * 2.0));
+ let before = view.to_screen(p, area);
+ view.pan(Vec2::new(30.0, -12.0));
+ assert!(close(view.to_screen(p, area), before + Vec2::new(30.0, -12.0)));
+ let pen = Vec2::new(420.0, 233.0);
+ let anchor = view.to_canvas(pen, area);
+ view.flip_at(pen, area);
+ assert!(close(view.to_canvas(pen, area), anchor));
+ }
+
+ #[test]
+ fn pan_moves_content_with_the_pointer() {
+ let area = Vec2::new(800.0, 600.0);
+ let mut view = View::fit(Vec2::new(1000.0, 1000.0), area);
+ view.angle = 1.1;
+ let p = Vec2::new(500.0, 500.0);
+ let before = view.to_screen(p, area);
+ view.pan(Vec2::new(30.0, -12.0));
+ assert!(close(view.to_screen(p, area), before + Vec2::new(30.0, -12.0)));
+ }
+}
diff --git a/crates/brush/Cargo.toml b/crates/brush/Cargo.toml
new file mode 100644
index 0000000..8163a58
--- /dev/null
+++ b/crates/brush/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "klad-brush"
+version.workspace = true
+edition.workspace = true
+license-file.workspace = true
+publish.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+bytemuck = { version = "1.25.2", features = ["extern_crate_alloc"] }
+klad-core = { version = "0.1.0", path = "../core" }
+half = { version = "2.7.1", features = ["bytemuck"] }
+libm = "0.2.16"
+png = "0.18.1"
+rayon = "1.12.0"
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.154"
+zstd = "0.14.3"
+
+[dev-dependencies]
+serde_json = "1.0.154"
diff --git a/crates/brush/src/brush.rs b/crates/brush/src/brush.rs
new file mode 100644
index 0000000..b89316d
--- /dev/null
+++ b/crates/brush/src/brush.rs
@@ -0,0 +1,400 @@
+use crate::grain::Grain;
+use crate::images::{self, Pictures};
+use anyhow::{Result, anyhow, bail};
+use klad_core::brushes::{self, AngleDef, BrushBlend, BrushDef, SPEED_FULL, TIP_IMAGES, TipDef};
+use klad_core::bundle::Bundle;
+use klad_core::rng::{FNV_OFFSET, fnv, hash2_unit};
+use std::collections::BTreeMap;
+use std::sync::{Arc, Mutex, OnceLock};
+
+#[derive(Clone, Debug)]
+pub enum Tip {
+ Round { hardness: f32 },
+ Mask(Arc<TipMask>),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum Angle {
+ Fixed(f32),
+ Follow,
+ Tilt,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StrokeBlend {
+ Normal,
+ Erase,
+ Atop,
+}
+
+#[derive(Clone, Debug)]
+pub struct Texture {
+ pub grain: Arc<Grain>,
+ pub strength: f32,
+ pub scale: f32,
+ pub contrast: f32,
+ pub pressure: f32,
+}
+
+#[derive(Clone, Debug)]
+pub struct Dual {
+ pub tip: Tip,
+ pub size: f32,
+ pub scatter: f32,
+ pub count: u32,
+}
+
+#[derive(Clone, Debug)]
+pub struct Brush {
+ pub def: BrushDef,
+ pub tip: Tip,
+ pub angle: Angle,
+ pub grain: Option<Texture>,
+ pub dual: Option<Dual>,
+ pub blend: StrokeBlend,
+}
+
+#[derive(Clone, Debug)]
+pub struct TipMask {
+ pub size: usize,
+ pub data: Vec<f32>,
+}
+
+impl TipMask {
+ pub fn chalk(seed: u32) -> Self {
+ let size = 128;
+ let data = (0..size * size)
+ .map(|i| {
+ let (x, y) = (i % size, i / size);
+ let u = (x as f32 + 0.5) / size as f32 * 2.0 - 1.0;
+ let v = (y as f32 + 0.5) / size as f32 * 2.0 - 1.0;
+ let d = libm::sqrtf(u * u + v * v);
+ let body = 1.0 - smoothstep(0.55, 1.0, d);
+ let clump = (hash2_unit(x as i32 / 6, y as i32 / 6, seed) * 0.6
+ + hash2_unit(x as i32 / 2, y as i32 / 2, seed + 1) * 0.4)
+ .clamp(0.0, 1.0);
+ body * smoothstep(0.3, 0.6, clump)
+ })
+ .collect();
+ Self { size, data }
+ }
+
+ pub fn sample(&self, u: f32, v: f32) -> f32 {
+ let n = self.size as f32;
+ let fx = ((u * 0.5 + 0.5) * n - 0.5).clamp(0.0, n - 1.001);
+ let fy = ((v * 0.5 + 0.5) * n - 0.5).clamp(0.0, n - 1.001);
+ let (x, y) = (fx as usize, fy as usize);
+ let (ax, ay) = (fx - x as f32, fy - y as f32);
+ let at = |x: usize, y: usize| self.data[y * self.size + x];
+ let top = at(x, y) + (at(x + 1, y) - at(x, y)) * ax;
+ let bottom = at(x, y + 1) + (at(x + 1, y + 1) - at(x, y + 1)) * ax;
+ top + (bottom - top) * ay
+ }
+}
+
+pub fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
+ let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+fn memo<K: Ord + Copy, V>(cache: &Memo<K, V>, key: K, make: impl FnOnce() -> V) -> Arc<V> {
+ let cache = cache.get_or_init(Mutex::default);
+ if let Some(hit) = cache.lock().ok().and_then(|c| c.get(&key).cloned()) {
+ return hit;
+ }
+ let made = Arc::new(make());
+ match cache.lock() {
+ Ok(mut c) => c.entry(key).or_insert(made).clone(),
+ Err(_) => made,
+ }
+}
+
+type Memo<K, V> = OnceLock<Mutex<BTreeMap<K, Arc<V>>>>;
+
+static GRAINS: Memo<(u32, usize), Grain> = OnceLock::new();
+static CHALK: Memo<u32, TipMask> = OnceLock::new();
+static LIBRARY_TIPS: Memo<usize, TipMask> = OnceLock::new();
+static PICTURE_TIPS: Memo<u64, TipMask> = OnceLock::new();
+static PICTURE_GRAINS: Memo<u64, Grain> = OnceLock::new();
+static LIBRARY_GRAINS: Memo<usize, Grain> = OnceLock::new();
+
+fn library_index(name: &str) -> Option<usize> {
+ TIP_IMAGES.iter().position(|n| *n == name)
+}
+
+fn missing(name: &str) -> anyhow::Error {
+ anyhow!(
+ "the image {name:?} is not in the bundle's brushes/images folder (nor a library picture: {})",
+ TIP_IMAGES.join(", ")
+ )
+}
+
+fn tip_of(def: &TipDef, pictures: &Pictures) -> Result<Tip> {
+ Ok(match def {
+ TipDef::Round { hardness } => Tip::Round { hardness: *hardness },
+ TipDef::Chalk { seed } => Tip::Mask(memo(&CHALK, *seed, || TipMask::chalk(*seed))),
+ TipDef::Image { image } => match (library_index(image), pictures.get(image)) {
+ (_, Some(picture)) => Tip::Mask(memo(&PICTURE_TIPS, picture.hash, || images::tip_from(picture))),
+ (Some(i), None) => Tip::Mask(memo(&LIBRARY_TIPS, i, || {
+ images::library_tip(TIP_IMAGES[i]).expect("a library tip")
+ })),
+ (None, None) => return Err(missing(image)),
+ },
+ })
+}
+
+pub fn tilt_amount(tilt: (f32, f32)) -> f32 {
+ libm::sqrtf(tilt.0 * tilt.0 + tilt.1 * tilt.1).min(1.0)
+}
+
+pub fn speed_amount(px_per_ms: f32) -> f32 {
+ (px_per_ms / SPEED_FULL).clamp(0.0, 1.0)
+}
+
+impl Brush {
+ pub fn from_def(def: &BrushDef) -> Self {
+ Self::with_pictures(def, &Pictures::new()).unwrap_or_else(|_| {
+ let mut plain = def.clone();
+ plain.tip = TipDef::Round { hardness: 0.5 };
+ plain.dual = None;
+ plain.grain = None;
+ Self::with_pictures(&plain, &Pictures::new()).expect("a plain brush builds")
+ })
+ }
+
+ pub fn with_pictures(def: &BrushDef, pictures: &Pictures) -> Result<Self> {
+ let tip = tip_of(&def.tip, pictures)?;
+ let grain = def
+ .grain
+ .as_ref()
+ .map(|g| {
+ let grain = match (&g.paper, &g.image) {
+ (Some(paper), _) => {
+ let key = (paper.seed, paper.feature);
+ memo(&GRAINS, key, || Grain::paper(key.0, key.1))
+ }
+ (None, Some(image)) => match (pictures.get(image), library_index(image)) {
+ (Some(picture), _) => memo(&PICTURE_GRAINS, picture.hash, || Grain::from_picture(picture)),
+ (None, Some(i)) => memo(&LIBRARY_GRAINS, i, || {
+ let tip = images::library_tip(TIP_IMAGES[i]).expect("a library picture");
+ Grain::from_picture(&images::Picture {
+ width: tip.size,
+ height: tip.size,
+ data: tip.data,
+ hash: 0,
+ })
+ }),
+ (None, None) => return Err(missing(image)),
+ },
+ (None, None) => bail!("a grain is either paper or an image"),
+ };
+ Ok(Texture {
+ grain,
+ strength: g.strength,
+ scale: g.scale,
+ contrast: g.contrast,
+ pressure: g.pressure,
+ })
+ })
+ .transpose()?;
+ let dual = def
+ .dual
+ .as_ref()
+ .map(|d| {
+ Ok::<_, anyhow::Error>(Dual {
+ tip: tip_of(&d.tip, pictures)?,
+ size: d.size,
+ scatter: d.scatter,
+ count: d.count,
+ })
+ })
+ .transpose()?;
+ Ok(Self {
+ def: def.clone(),
+ tip,
+ dual,
+ angle: match def.angle {
+ AngleDef::Fixed(a) => Angle::Fixed(a),
+ AngleDef::Follow => Angle::Follow,
+ AngleDef::Tilt => Angle::Tilt,
+ },
+ grain,
+ blend: match def.blend {
+ BrushBlend::Normal => StrokeBlend::Normal,
+ BrushBlend::Erase => StrokeBlend::Erase,
+ },
+ })
+ }
+
+ pub fn size_at(&self, base: f32, pressure: f32, tilt: f32, speed: f32) -> f32 {
+ base * self.def.dynamics.size.at(pressure, tilt, speed)
+ }
+
+ pub fn flow_at(&self, base: f32, pressure: f32, tilt: f32, speed: f32) -> f32 {
+ base * self.def.flow * self.def.dynamics.flow.at(pressure, tilt, speed)
+ }
+
+ pub fn opacity_at(&self, pressure: f32, tilt: f32, speed: f32) -> f32 {
+ self.def.opacity * self.def.dynamics.opacity.at(pressure, tilt, speed)
+ }
+}
+
+#[derive(Clone)]
+struct Entry {
+ def: BrushDef,
+ built: OnceLock<Result<Brush, String>>,
+}
+
+impl Entry {
+ fn new(def: BrushDef) -> Self {
+ Self {
+ def,
+ built: OnceLock::new(),
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct BrushSet {
+ entries: BTreeMap<String, Entry>,
+ pictures: Arc<Pictures>,
+}
+
+impl BrushSet {
+ pub fn presets() -> Self {
+ Self {
+ entries: brushes::library_ids()
+ .into_iter()
+ .filter_map(|id| brushes::library(id).map(|def| (id.to_string(), Entry::new(def))))
+ .collect(),
+ pictures: Arc::new(Pictures::new()),
+ }
+ }
+
+ pub fn for_bundle(bundle: &Bundle) -> Result<Self> {
+ let mut set = Self::presets();
+ set.pictures = Arc::new(images::load(bundle)?);
+ bundle.brushes()?.into_iter().for_each(|(id, def)| set.insert(&id, def));
+ Ok(set)
+ }
+
+ pub fn pictures(&self) -> &Pictures {
+ &self.pictures
+ }
+
+ pub fn add_picture(&mut self, name: &str, picture: images::Picture) {
+ let mut pictures = (*self.pictures).clone();
+ pictures.insert(name.to_string(), Arc::new(picture));
+ self.pictures = Arc::new(pictures);
+ self.entries.values_mut().for_each(|e| *e = Entry::new(e.def.clone()));
+ }
+
+ pub fn refresh(&mut self, bundle: &Bundle) -> Result<()> {
+ let pictures = images::load(bundle)?;
+ if pictures != *self.pictures {
+ self.pictures = Arc::new(pictures);
+ self.entries.values_mut().for_each(|e| *e = Entry::new(e.def.clone()));
+ }
+ bundle.brushes()?.into_iter().for_each(|(id, def)| {
+ if self.def(&id) != Some(&def) {
+ self.insert(&id, def);
+ }
+ });
+ Ok(())
+ }
+
+ pub fn insert(&mut self, id: &str, def: BrushDef) {
+ self.entries.insert(id.to_string(), Entry::new(def));
+ }
+
+ pub fn def(&self, id: &str) -> Option<&BrushDef> {
+ self.entries.get(id).map(|e| &e.def)
+ }
+
+ pub fn defs(&self) -> impl Iterator<Item = (&str, &BrushDef)> {
+ self.entries.iter().map(|(id, e)| (id.as_str(), &e.def))
+ }
+
+ pub fn fingerprint(&self) -> u64 {
+ let brushes = self.entries.iter().fold(FNV_OFFSET, |h, (id, e)| {
+ fnv(fnv(h, id.as_bytes()), &e.def.fingerprint().to_le_bytes())
+ });
+ self.pictures.iter().fold(brushes, |h, (name, p)| {
+ fnv(fnv(h, name.as_bytes()), &p.hash.to_le_bytes())
+ })
+ }
+
+ pub fn get(&self, id: &str) -> Result<&Brush> {
+ let entry = self.entries.get(id).ok_or_else(|| {
+ let known: Vec<&str> = self.entries.keys().map(String::as_str).collect();
+ anyhow!("unknown brush {id:?}: brushes are {}", known.join(", "))
+ })?;
+ entry
+ .built
+ .get_or_init(|| Brush::with_pictures(&entry.def, &self.pictures).map_err(|e| format!("brush {id}: {e:#}")))
+ .as_ref()
+ .map_err(|e| anyhow!("{e}"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_preset_builds() {
+ let set = BrushSet::presets();
+ assert!(brushes::library_ids().iter().all(|id| set.get(id).is_ok()));
+ assert!(set.get("nope").unwrap_err().to_string().contains("marker"));
+ assert_eq!(set.get("eraser").unwrap().blend, StrokeBlend::Erase);
+ }
+
+ #[test]
+ fn ink_tapers_with_pressure() {
+ let set = BrushSet::presets();
+ let ink = set.get("ink").unwrap();
+ assert!(ink.size_at(20.0, 0.1, 0.0, 0.0) < ink.size_at(20.0, 0.5, 0.0, 0.0));
+ assert_eq!(ink.size_at(20.0, 1.0, 0.0, 0.0), 20.0);
+ }
+
+ #[test]
+ fn textures_are_shared_between_brushes() {
+ let a = BrushSet::presets();
+ let b = BrushSet::presets();
+ let (Some(ga), Some(gb)) = (&a.get("pencil").unwrap().grain, &b.get("pencil").unwrap().grain) else {
+ panic!("pencil has grain");
+ };
+ assert!(Arc::ptr_eq(&ga.grain, &gb.grain));
+ }
+
+ #[test]
+ fn chalk_mask_has_holes_and_body() {
+ let mask = TipMask::chalk(7);
+ assert!(mask.sample(0.0, 0.0) >= 0.0);
+ assert_eq!(mask.sample(1.0, 1.0), 0.0);
+ let filled = mask.data.iter().filter(|&&v| v > 0.5).count();
+ assert!(filled > mask.data.len() / 10 && filled < mask.data.len() / 2);
+ }
+
+ #[test]
+ fn tilt_and_speed_feed_the_curves() {
+ let mut def = brushes::library("ink").unwrap();
+ def.dynamics.size.tilt = Some(brushes::Curve {
+ min: 1.0,
+ max: 2.0,
+ gamma: 1.0,
+ });
+ def.dynamics.size.speed = Some(brushes::Curve {
+ min: 1.0,
+ max: 0.5,
+ gamma: 1.0,
+ });
+ let brush = Brush::from_def(&def);
+ let upright = brush.size_at(10.0, 1.0, tilt_amount((0.0, 0.0)), speed_amount(0.0));
+ let tilted = brush.size_at(10.0, 1.0, tilt_amount((0.6, 0.8)), speed_amount(0.0));
+ let fast = brush.size_at(10.0, 1.0, 0.0, speed_amount(50.0));
+ assert_eq!(upright, 10.0);
+ assert!((tilted - 20.0).abs() < 1e-4);
+ assert!((fast - 5.0).abs() < 1e-4);
+ }
+}
diff --git a/crates/brush/src/cache.rs b/crates/brush/src/cache.rs
new file mode 100644
index 0000000..c9b3e10
--- /dev/null
+++ b/crates/brush/src/cache.rs
@@ -0,0 +1,320 @@
+use crate::{BrushSet, CelReplay, ENGINE_VERSION, Raster};
+use anyhow::{Context, Result, bail};
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use klad_core::stroke::{Mark, decode_cel};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant, SystemTime};
+
+pub const BUDGET: u64 = 2 << 30;
+pub const SLOW: Duration = Duration::from_millis(30);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum How {
+ Cached,
+ Updated(usize),
+ Replayed,
+}
+
+pub struct CelLoad {
+ pub raster: Raster,
+ pub replay: CelReplay,
+ pub file_hash: u64,
+ pub how: How,
+ pub strokes: usize,
+ pub dabs: usize,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Write {
+ Always,
+ WhenSlow,
+ Never,
+}
+
+#[derive(Clone, Debug)]
+pub struct CelCache {
+ dir: PathBuf,
+ base: u64,
+ size: (u32, u32),
+ write: Write,
+}
+
+type Record = (Vec<(u32, u64)>, Vec<Vec<u32>>);
+
+impl CelCache {
+ pub fn new(bundle: &Bundle, brushes: &BrushSet, write: Write) -> Self {
+ let size = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ let base = fnv(
+ fnv(
+ FNV_OFFSET,
+ &[ENGINE_VERSION, size.0, size.1].map(u32::to_le_bytes).concat(),
+ ),
+ &brushes.fingerprint().to_le_bytes(),
+ );
+ Self {
+ dir: bundle.cache_dir().join("tiles"),
+ base,
+ size,
+ write,
+ }
+ }
+
+ pub fn key(&self, bytes: &[u8]) -> u64 {
+ fnv(self.base, bytes)
+ }
+
+ pub fn holds_key(&self, cel: &str, key: u64) -> bool {
+ let mut head = [0u8; 8];
+ fs::File::open(self.paths(cel).0)
+ .and_then(|mut f| std::io::Read::read_exact(&mut f, &mut head))
+ .is_ok_and(|_| head == key.to_le_bytes())
+ }
+
+ pub fn holds(&self, bundle: &Bundle, layer: &str, cel: &str) -> bool {
+ let bytes = fs::read(bundle.strokes_path(layer, cel)).unwrap_or_default();
+ self.holds_key(cel, self.key(&bytes))
+ }
+
+ fn paths(&self, cel: &str) -> (PathBuf, PathBuf) {
+ (
+ self.dir.join(format!("{cel}.raster")),
+ self.dir.join(format!("{cel}.marks")),
+ )
+ }
+
+ fn raster(&self, cel: &str, key: u64) -> Result<Raster> {
+ let path = self.paths(cel).0;
+ let bytes = fs::read(&path)?;
+ if bytes.len() < 8 || bytes[..8] != key.to_le_bytes() {
+ bail!("stale cache");
+ }
+ let raster = Raster::decode(&zstd::decode_all(&bytes[8..])?)?;
+ let _ = fs::File::options()
+ .write(true)
+ .open(&path)
+ .and_then(|f| f.set_modified(SystemTime::now()));
+ Ok(raster)
+ }
+
+ fn record(&self, cel: &str) -> Result<(u64, Record)> {
+ let bytes = fs::read(self.paths(cel).1)?;
+ if bytes.len() < 16 || bytes[8..16] != self.base.to_le_bytes() {
+ bail!("the record was made with other brushes or another canvas");
+ }
+ let key = u64::from_le_bytes(bytes[..8].try_into()?);
+ Ok((key, serde_json::from_slice(&zstd::decode_all(&bytes[16..])?)?))
+ }
+
+ pub fn load(&self, bundle: &Bundle, brushes: &BrushSet, layer: &str, cel: &str, want: bool) -> Result<CelLoad> {
+ let path = bundle.strokes_path(layer, cel);
+ let bytes = if path.exists() { fs::read(&path)? } else { Vec::new() };
+ let key = self.key(&bytes);
+ let file_hash = fnv(FNV_OFFSET, &bytes);
+ let marks = || -> Result<Vec<Mark>> {
+ match bytes.is_empty() {
+ true => Ok(Vec::new()),
+ false => decode_cel(&bytes).with_context(|| format!("cel {cel}")),
+ }
+ };
+ let (w, h) = self.size;
+ if let Ok(raster) = self.raster(cel, key) {
+ let replay = match want {
+ false => Some(CelReplay::new(w, h)),
+ true => self
+ .record(cel)
+ .ok()
+ .filter(|(k, _)| *k == key)
+ .and_then(|(_, (keys, footprints))| {
+ CelReplay::from_cache(w, h, keys, footprints).with_marks(marks().ok()?)
+ }),
+ };
+ if let Some(replay) = replay {
+ return Ok(CelLoad {
+ raster,
+ replay,
+ file_hash,
+ how: How::Cached,
+ strokes: 0,
+ dabs: 0,
+ });
+ }
+ }
+ let marks = marks()?;
+ let start = Instant::now();
+ let stale = self.record(cel).and_then(|(k, (keys, footprints))| {
+ Ok((CelReplay::from_cache(w, h, keys, footprints), self.raster(cel, k)?))
+ });
+ let (replay, raster, how, strokes, dabs) = match stale {
+ Ok((mut replay, mut raster)) => {
+ let done = replay
+ .update(&mut raster, marks, brushes)
+ .with_context(|| format!("cel {cel}"))?;
+ (replay, raster, How::Updated(done.replayed), done.replayed, 0)
+ }
+ Err(_) => {
+ let count = marks.len();
+ let (replay, raster, dabs) =
+ CelReplay::replay(w, h, marks, brushes).with_context(|| format!("cel {cel}"))?;
+ (replay, raster, How::Replayed, count, dabs)
+ }
+ };
+ let store = match self.write {
+ Write::Always => true,
+ Write::WhenSlow => start.elapsed() >= SLOW,
+ Write::Never => false,
+ };
+ if store {
+ self.store(cel, key, &raster, &replay)?;
+ }
+ Ok(CelLoad {
+ raster,
+ replay,
+ file_hash,
+ how,
+ strokes,
+ dabs,
+ })
+ }
+
+ pub fn strokes(&self, bundle: &Bundle, layer: &str, cel: &str) -> Result<Option<(CelReplay, u64)>> {
+ let path = bundle.strokes_path(layer, cel);
+ let bytes = if path.exists() { fs::read(&path)? } else { Vec::new() };
+ let Ok((key, (keys, footprints))) = self.record(cel) else {
+ return Ok(None);
+ };
+ if key != self.key(&bytes) {
+ return Ok(None);
+ }
+ let marks = match bytes.is_empty() {
+ true => Vec::new(),
+ false => decode_cel(&bytes).with_context(|| format!("cel {cel}"))?,
+ };
+ let (w, h) = self.size;
+ Ok(CelReplay::from_cache(w, h, keys, footprints)
+ .with_marks(marks)
+ .map(|replay| (replay, fnv(FNV_OFFSET, &bytes))))
+ }
+
+ pub fn store(&self, cel: &str, key: u64, raster: &Raster, replay: &CelReplay) -> Result<()> {
+ fs::create_dir_all(&self.dir)?;
+ let (pixels, record) = self.paths(cel);
+ let mut bytes = key.to_le_bytes().to_vec();
+ bytes.extend(compress(raster)?);
+ write_atomic(&pixels, &bytes)?;
+ let mut bytes = [key.to_le_bytes(), self.base.to_le_bytes()].concat();
+ let kept: (&[(u32, u64)], &[Vec<u32>]) = (replay.keys(), replay.footprints());
+ bytes.extend(zstd::encode_all(&serde_json::to_vec(&kept)?[..], 1)?);
+ write_atomic(&record, &bytes)?;
+ prune(&self.dir, BUDGET);
+ Ok(())
+ }
+}
+
+pub fn compress(raster: &Raster) -> Result<Vec<u8>> {
+ Ok(zstd::encode_all(&raster.encode()[..], 1)?)
+}
+
+pub fn prune(dir: &Path, budget: u64) {
+ let Ok(entries) = fs::read_dir(dir) else {
+ return;
+ };
+ let mut files: Vec<(SystemTime, u64, PathBuf)> = entries
+ .flatten()
+ .filter_map(|e| {
+ let meta = e.metadata().ok()?;
+ Some((meta.modified().ok()?, meta.len(), e.path()))
+ })
+ .collect();
+ let total: u64 = files.iter().map(|(_, len, _)| len).sum();
+ if total <= budget {
+ return;
+ }
+ files.sort();
+ files.into_iter().try_fold(total, |left, (_, len, path)| {
+ if left <= budget {
+ return None;
+ }
+ let _ = fs::remove_file(&path);
+ Some(left - len)
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Document, Layer};
+ use klad_core::stroke::marks;
+ use klad_core::synth::Synth;
+
+ #[test]
+ fn a_cached_drawing_loads_its_pixels_and_edit_record_and_an_edited_one_updates() {
+ let dir = std::env::temp_dir().join(format!("draw-cel-cache-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let mut doc = Document::new(600, 400);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let bundle = Bundle::create(&dir, doc).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let strokes = Synth::canvas(600.0, 400.0).strokes(40, 7);
+ bundle.write_marks("l1", "c1", &marks(strokes.clone())).unwrap();
+ let cache = CelCache::new(&bundle, &brushes, Write::Always);
+ let first = cache.load(&bundle, &brushes, "l1", "c1", true).unwrap();
+ assert_eq!(first.how, How::Replayed);
+ assert!(cache.holds(&bundle, "l1", "c1"));
+ let again = cache.load(&bundle, &brushes, "l1", "c1", true).unwrap();
+ assert_eq!(again.how, How::Cached);
+ assert_eq!(again.raster.hash(), first.raster.hash());
+ assert_eq!(again.replay.marks(), first.replay.marks());
+ assert_eq!(again.replay.keys(), first.replay.keys());
+ assert_eq!(again.replay.footprints(), first.replay.footprints());
+ let more = Synth::canvas(600.0, 400.0).strokes(3, 99);
+ let edited = marks(strokes.into_iter().chain(more));
+ bundle.write_marks("l1", "c1", &edited).unwrap();
+ assert!(!cache.holds(&bundle, "l1", "c1"), "a changed drawing is not held");
+ let updated = cache.load(&bundle, &brushes, "l1", "c1", true).unwrap();
+ assert!(matches!(updated.how, How::Updated(n) if n < 43), "{:?}", updated.how);
+ let (_, fresh, _) = CelReplay::replay(600, 400, edited.clone(), &brushes).unwrap();
+ assert_eq!(updated.raster.hash(), fresh.hash());
+ assert_eq!(updated.replay.marks(), &edited[..]);
+ assert!(
+ CelReplay::from_cache(
+ 600,
+ 400,
+ again.replay.keys().to_vec(),
+ again.replay.footprints().to_vec()
+ )
+ .with_marks(edited)
+ .is_none()
+ );
+ let lazy = CelCache::new(&bundle, &brushes, Write::Never);
+ fs::remove_dir_all(dir.join(".cache")).unwrap();
+ assert_eq!(
+ lazy.load(&bundle, &brushes, "l1", "c1", true).unwrap().how,
+ How::Replayed
+ );
+ assert!(!dir.join(".cache/tiles/c1.raster").exists());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn the_cache_keeps_to_its_budget_dropping_the_oldest_files() {
+ let dir = std::env::temp_dir().join(format!("draw-cel-prune-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ (0..5).for_each(|i| {
+ fs::write(dir.join(format!("c{i}.raster")), vec![0u8; 1000]).unwrap();
+ let when = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000 + i * 60);
+ fs::File::options()
+ .write(true)
+ .open(dir.join(format!("c{i}.raster")))
+ .unwrap()
+ .set_modified(when)
+ .unwrap();
+ });
+ prune(&dir, 2500);
+ let left: Vec<bool> = (0..5).map(|i| dir.join(format!("c{i}.raster")).exists()).collect();
+ assert_eq!(left, [false, false, false, true, true]);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/brush/src/cut.rs b/crates/brush/src/cut.rs
new file mode 100644
index 0000000..f98d7e5
--- /dev/null
+++ b/crates/brush/src/cut.rs
@@ -0,0 +1,125 @@
+use crate::tiles::{TILE, TILE_PX};
+use klad_core::cut::{Cut, Keep, crossings, polygon_box};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use std::cell::RefCell;
+use std::sync::Arc;
+
+const SUB: usize = 4;
+const REMEMBERED: usize = 96;
+
+type Key = (u64, usize, usize);
+type Inside = Option<Arc<[f32]>>;
+
+thread_local! {
+ static INSIDE: RefCell<Vec<(Key, Inside)>> = const { RefCell::new(Vec::new()) };
+}
+
+fn remembered(polygon: &[[f32; 2]], at: (usize, usize)) -> Inside {
+ let bytes: Vec<u8> = polygon.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
+ let key = (fnv(FNV_OFFSET, &bytes), at.0, at.1);
+ if let Some(found) = INSIDE.with_borrow(|seen| seen.iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone())) {
+ return found;
+ }
+ let fresh: Inside = inside(polygon, at).map(Arc::from);
+ INSIDE.with_borrow_mut(|seen| {
+ if seen.len() >= REMEMBERED {
+ seen.remove(0);
+ }
+ seen.push((key, fresh.clone()));
+ });
+ fresh
+}
+
+pub fn inside(polygon: &[[f32; 2]], (ox, oy): (usize, usize)) -> Option<Vec<f32>> {
+ let [x0, y0, x1, y1] = polygon_box(polygon)?;
+ let (left, top) = (ox as f32, oy as f32);
+ let (right, bottom) = (left + TILE as f32, top + TILE as f32);
+ if x1 <= left || x0 >= right || y1 <= top || y0 >= bottom {
+ return None;
+ }
+ let rows = (y0 - top).floor().max(0.0) as usize..((y1 - top).ceil().max(0.0) as usize).min(TILE);
+ let width = TILE * SUB;
+ let first = ((x0 - left).floor().max(0.0) as usize).min(TILE) * SUB;
+ let last = (((x1 - left).ceil().max(0.0) as usize).min(TILE) * SUB).max(first);
+ let mut out = vec![0.0f32; TILE_PX];
+ let mut counts = vec![0i32; width + 1];
+ rows.for_each(|row| {
+ counts[first..=last].iter_mut().for_each(|c| *c = 0);
+ (0..SUB).for_each(|k| {
+ let sy = top + row as f32 + (k as f32 + 0.5) / SUB as f32;
+ crossings(polygon, sy).as_chunks::<2>().0.iter().for_each(|[a, b]| {
+ let sub = |x: f32| ((x - left) * SUB as f32 - 0.5).ceil().clamp(0.0, width as f32) as usize;
+ let (from, to) = (sub(*a), sub(*b));
+ if from < to {
+ counts[from] += 1;
+ counts[to] -= 1;
+ }
+ });
+ });
+ let mut running = 0;
+ let mut pixel = 0;
+ counts[first..last].iter().enumerate().for_each(|(i, c)| {
+ running += c;
+ pixel += running;
+ if (first + i) % SUB == SUB - 1 {
+ out[row * TILE + (first + i) / SUB] = pixel as f32 / (SUB * SUB) as f32;
+ pixel = 0;
+ }
+ });
+ });
+ Some(out)
+}
+
+pub fn factor(cuts: &[Cut], (ox, oy): (usize, usize)) -> Option<Vec<f32>> {
+ cuts.iter().fold(None, |acc: Option<Vec<f32>>, cut| {
+ let part = match (remembered(&cut.polygon, (ox, oy)), cut.keep) {
+ (None, Keep::Outside) => return acc,
+ (None, Keep::Inside) => vec![0.0; TILE_PX],
+ (Some(inner), Keep::Inside) => inner.to_vec(),
+ (Some(inner), Keep::Outside) => inner.iter().map(|v| 1.0 - v).collect(),
+ };
+ Some(match acc {
+ None => part,
+ Some(mut all) => {
+ all.iter_mut().zip(&part).for_each(|(a, p)| *a *= p);
+ all
+ }
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn insides_are_supersampled_and_cuts_multiply() {
+ let square = vec![[10.0, 10.0], [20.5, 10.0], [20.5, 20.0], [10.0, 20.0]];
+ let inner = inside(&square, (0, 0)).unwrap();
+ assert_eq!(inner[15 * TILE + 15], 1.0);
+ assert_eq!(inner[15 * TILE + 25], 0.0);
+ assert_eq!(inner[15 * TILE + 20], 0.5);
+ assert!(inside(&square, (256, 0)).is_none());
+ let keep_out = Cut {
+ keep: Keep::Outside,
+ polygon: square.clone(),
+ };
+ let keep_in = Cut {
+ keep: Keep::Inside,
+ polygon: square,
+ };
+ assert!(factor(std::slice::from_ref(&keep_out), (256, 0)).is_none());
+ assert!(
+ factor(std::slice::from_ref(&keep_in), (256, 0))
+ .unwrap()
+ .iter()
+ .all(|v| *v == 0.0)
+ );
+ let both = factor(&[keep_out.clone(), keep_in.clone()], (0, 0)).unwrap();
+ assert_eq!(both[15 * TILE + 20], 0.25);
+ assert_eq!(both[15 * TILE + 15], 0.0);
+ let outer = factor(std::slice::from_ref(&keep_out), (0, 0)).unwrap();
+ let inner = factor(std::slice::from_ref(&keep_in), (0, 0)).unwrap();
+ assert!(outer.iter().zip(&inner).all(|(a, b)| a + b == 1.0));
+ }
+}
diff --git a/crates/brush/src/engine.rs b/crates/brush/src/engine.rs
new file mode 100644
index 0000000..d30db7f
--- /dev/null
+++ b/crates/brush/src/engine.rs
@@ -0,0 +1,1303 @@
+use crate::brush::{Angle, Brush, BrushSet, StrokeBlend, Texture, Tip, smoothstep, speed_amount, tilt_amount};
+use crate::cut;
+use crate::tiles::{Mode, Raster, StrokeBuffer, TILE};
+use anyhow::Result;
+use half::f16;
+use klad_core::brushes::PaintDef;
+use klad_core::color::Rgba;
+use klad_core::cut::Cut;
+use klad_core::rng::Rng;
+use klad_core::stroke::{Mark, Sample, Stroke};
+
+const MIN_RADIUS: f32 = 0.6;
+const SPEED_EASE: f32 = 0.5;
+
+#[derive(Clone, Copy, Debug)]
+struct Point {
+ x: f32,
+ y: f32,
+ p: f32,
+ tilt: (f32, f32),
+}
+
+fn lerp(a: Point, b: Point, t: f32) -> Point {
+ Point {
+ x: a.x + (b.x - a.x) * t,
+ y: a.y + (b.y - a.y) * t,
+ p: a.p + (b.p - a.p) * t,
+ tilt: (
+ a.tilt.0 + (b.tilt.0 - a.tilt.0) * t,
+ a.tilt.1 + (b.tilt.1 - a.tilt.1) * t,
+ ),
+ }
+}
+
+fn segment(from: (f32, f32), to: (f32, f32)) -> f32 {
+ let (dx, dy) = (to.0 - from.0, to.1 - from.1);
+ libm::sqrtf(dx * dx + dy * dy)
+}
+
+pub fn arc_length(samples: &[Sample]) -> f32 {
+ samples
+ .iter()
+ .map(Sample::pos)
+ .fold((None, 0.0f32), |(last, total), here| match last {
+ None => (Some(here), total),
+ Some(prev) => {
+ let length = segment(prev, here);
+ if length < 1e-4 {
+ (Some(prev), total)
+ } else {
+ (Some(here), total + length)
+ }
+ }
+ })
+ .1
+}
+
+pub fn needs_repaint(stroke: &Stroke) -> bool {
+ stroke.taper != [0.0, 0.0] || stroke.pressureless()
+}
+
+pub struct StrokePainter {
+ brush: Brush,
+ size: f32,
+ flow: f32,
+ rng: Rng,
+ last: Option<Point>,
+ heading: f32,
+ speed: f32,
+ carry: f32,
+ walked: f32,
+ taper: [f32; 2],
+ length: Option<f32>,
+ pressureless: bool,
+ dabs: usize,
+ first: [f32; 3],
+ second: [f32; 3],
+ shift: [f32; 3],
+ reservoir: Option<[f32; 3]>,
+ previous: Option<(f32, f32)>,
+}
+
+const STROKE_COLOUR_SEED: u64 = 0x9e37_79b9_7f4a_7c15;
+
+impl StrokePainter {
+ pub fn new(brush: &Brush, stroke: &Stroke) -> Self {
+ let length = (stroke.taper != [0.0, 0.0]).then(|| arc_length(&stroke.samples));
+ let mut painter = Self::live(brush, stroke);
+ painter.length = length;
+ painter.pressureless = stroke.pressureless();
+ if length.is_some_and(|l| l <= 0.0) {
+ painter.taper = [0.0, 0.0];
+ }
+ painter
+ }
+
+ pub fn live(brush: &Brush, stroke: &Stroke) -> Self {
+ let colour = stroke.color();
+ let first = [colour[0], colour[1], colour[2]];
+ let second = stroke.second_color().map_or(first, |c| [c[0], c[1], c[2]]);
+ let shift = match &brush.def.color {
+ Some(c) => {
+ let mut rng = Rng::new(stroke.seed as u64 ^ STROKE_COLOUR_SEED);
+ [
+ c.stroke_hue / 360.0 * rng.signed(),
+ c.stroke_saturation * rng.signed(),
+ c.stroke_value * rng.signed(),
+ ]
+ }
+ None => [0.0; 3],
+ };
+ Self {
+ brush: brush.clone(),
+ size: stroke.size,
+ flow: stroke.flow,
+ rng: Rng::new(stroke.seed as u64),
+ last: None,
+ heading: 0.0,
+ speed: 0.0,
+ carry: 0.0,
+ walked: 0.0,
+ taper: stroke.taper,
+ length: None,
+ pressureless: false,
+ dabs: 0,
+ first,
+ second,
+ shift,
+ reservoir: None,
+ previous: None,
+ }
+ }
+
+ pub fn dabs(&self) -> usize {
+ self.dabs
+ }
+
+ pub fn mode(&self) -> Mode {
+ mode_of(&self.brush)
+ }
+
+ pub fn push(&mut self, sample: &Sample, buffer: &mut StrokeBuffer) {
+ self.push_on(sample, buffer, None);
+ }
+
+ pub fn push_on(&mut self, sample: &Sample, buffer: &mut StrokeBuffer, under: Option<&Raster>) {
+ buffer.mode = self.mode();
+ let (x, y) = sample.pos();
+ let next = Point {
+ x,
+ y,
+ p: if self.pressureless { 1.0 } else { sample.pressure() },
+ tilt: sample.tilt(),
+ };
+ let Some(prev) = self.last else {
+ self.dab(next, 0.0, buffer, under);
+ self.last = Some(next);
+ return;
+ };
+ let length = segment((prev.x, prev.y), (next.x, next.y));
+ if length < 1e-4 {
+ self.last = Some(Point {
+ p: next.p,
+ tilt: next.tilt,
+ ..prev
+ });
+ return;
+ }
+ if sample.dt_ms > 0 {
+ let now = length / sample.dt_ms as f32;
+ self.speed += (now - self.speed) * SPEED_EASE;
+ }
+ self.heading = libm::atan2f(next.y - prev.y, next.x - prev.x);
+ let mut travelled = 0.0f32;
+ loop {
+ let here = lerp(prev, next, travelled / length);
+ let step = (self.spacing(here, self.walked + travelled) - self.carry).max(0.0);
+ if travelled + step > length {
+ self.carry += length - travelled;
+ break;
+ }
+ travelled += step;
+ self.carry = 0.0;
+ self.dab(
+ lerp(prev, next, travelled / length),
+ self.walked + travelled,
+ buffer,
+ under,
+ );
+ }
+ self.walked += length;
+ self.last = Some(next);
+ }
+
+ fn taper_at(&self, along: f32) -> f32 {
+ let [into, out] = self.taper;
+ let k_in = if into > 0.0 {
+ smoothstep(0.0, 1.0, along / into)
+ } else {
+ 1.0
+ };
+ let k_out = match self.length {
+ Some(total) if out > 0.0 => smoothstep(0.0, 1.0, (total - along) / out),
+ _ => 1.0,
+ };
+ k_in.min(k_out)
+ }
+
+ fn size_here(&self, at: Point, along: f32) -> f32 {
+ let size = self
+ .brush
+ .size_at(self.size, at.p, tilt_amount(at.tilt), speed_amount(self.speed));
+ size * self.taper_at(along)
+ }
+
+ fn spacing(&self, at: Point, along: f32) -> f32 {
+ (self.size_here(at, along) * self.brush.def.spacing).max(0.5)
+ }
+
+ fn colour_here(&mut self, at: Point, along: f32) -> Option<[f32; 3]> {
+ let c = self.brush.def.color?;
+ let towards_second = {
+ let pressure = c.pressure.map_or(0.0, |curve| 1.0 - curve.at(at.p).clamp(0.0, 1.0));
+ let along = match c.along > 0.0 {
+ true => (along / c.along).min(1.0),
+ false => 0.0,
+ };
+ pressure.max(along)
+ };
+ let base: [f32; 3] = std::array::from_fn(|i| self.first[i] + (self.second[i] - self.first[i]) * towards_second);
+ let jitter = match c.hue > 0.0 || c.saturation > 0.0 || c.value > 0.0 {
+ true => [
+ c.hue / 360.0 * self.rng.signed(),
+ c.saturation * self.rng.signed(),
+ c.value * self.rng.signed(),
+ ],
+ false => [0.0; 3],
+ };
+ let [h, s, v] = hsv(base);
+ Some(rgb([
+ (h + self.shift[0] + jitter[0]).rem_euclid(1.0),
+ (s + self.shift[1] + jitter[1]).clamp(0.0, 1.0),
+ (v + self.shift[2] + jitter[2]).clamp(0.0, 1.0),
+ ]))
+ }
+
+ fn dab(&mut self, at: Point, along: f32, buffer: &mut StrokeBuffer, under: Option<&Raster>) {
+ let jitter = [
+ self.rng.signed(),
+ self.rng.signed(),
+ self.rng.signed(),
+ self.rng.signed(),
+ ];
+ let (tilt, speed) = (tilt_amount(at.tilt), speed_amount(self.speed));
+ let size = self.size_here(at, along) * (1.0 + self.brush.def.jitter.size * jitter[0]);
+ let flow = self.brush.flow_at(self.flow, at.p, tilt, speed);
+ let cap = self.brush.opacity_at(at.p, tilt, speed);
+ let angle = match self.brush.angle {
+ Angle::Fixed(a) => a,
+ Angle::Follow => self.heading,
+ Angle::Tilt => libm::atan2f(at.tilt.1, at.tilt.0),
+ } + self.brush.def.jitter.angle * jitter[1];
+ let cx = at.x + self.brush.def.jitter.scatter * size * jitter[2];
+ let cy = at.y + self.brush.def.jitter.scatter * size * jitter[3];
+ let mut dual = [[0.0f32; 3]; 8];
+ let count = self.brush.dual.as_ref().map_or(0, |d| d.count.min(8) as usize);
+ let scatter = self.brush.dual.as_ref().map_or(0.0, |d| d.scatter);
+ dual.iter_mut().take(count).for_each(|d| {
+ *d = [
+ scatter * self.rng.signed(),
+ scatter * self.rng.signed(),
+ std::f32::consts::PI * self.rng.signed(),
+ ]
+ });
+ let mut color = self.colour_here(at, along);
+ let mut flow = flow;
+ if let Some(PaintDef::Wet {
+ wetness,
+ pickup,
+ dilution,
+ }) = self.brush.def.paint
+ {
+ let base = color.unwrap_or(self.first);
+ let picked = pick(buffer, under, cx, cy, size * 0.5);
+ let reservoir = self.reservoir.get_or_insert(base);
+ if picked[3] > 1e-4 {
+ let k = pickup * picked[3];
+ (0..3).for_each(|i| reservoir[i] += (picked[i] / picked[3] - reservoir[i]) * k);
+ }
+ color = Some(std::array::from_fn(|i| base[i] + (reservoir[i] - base[i]) * wetness));
+ flow *= 1.0 - dilution * 0.9;
+ }
+ let shift = self.previous.map_or((0.0, 0.0), |(px, py)| (cx - px, cy - py));
+ self.previous = Some((cx, cy));
+ self.dabs += 1;
+ let dab = Dab {
+ cx,
+ cy,
+ radius: size * 0.5,
+ angle,
+ flow,
+ cap,
+ p: at.p,
+ dual,
+ count,
+ color,
+ };
+ match self.brush.def.paint {
+ Some(PaintDef::Smudge { strength }) => {
+ stamp_replace(buffer, &self.brush, dab, under, Replace::Smudge(shift), strength)
+ }
+ Some(PaintDef::Blend { strength }) => {
+ stamp_replace(buffer, &self.brush, dab, under, Replace::Blend, strength)
+ }
+ _ => stamp(buffer, &self.brush, dab),
+ }
+ }
+}
+
+pub fn mode_of(brush: &Brush) -> Mode {
+ match brush.def.paint {
+ Some(PaintDef::Smudge { .. } | PaintDef::Blend { .. }) => Mode::Replace,
+ Some(PaintDef::Wet { .. }) => Mode::Colour,
+ None if brush.def.color.is_some() => Mode::Colour,
+ None => Mode::Flat,
+ }
+}
+
+fn hsv([r, g, b]: [f32; 3]) -> [f32; 3] {
+ let max = r.max(g).max(b);
+ let min = r.min(g).min(b);
+ let d = max - min;
+ let h = match d <= 1e-6 {
+ true => 0.0,
+ false if max == r => ((g - b) / d).rem_euclid(6.0) / 6.0,
+ false if max == g => ((b - r) / d + 2.0) / 6.0,
+ false => ((r - g) / d + 4.0) / 6.0,
+ };
+ let s = if max <= 1e-6 { 0.0 } else { d / max };
+ [h, s, max]
+}
+
+fn rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
+ let h6 = h * 6.0;
+ let sector = (h6.floor() as i32).rem_euclid(6);
+ let f = h6 - h6.floor();
+ let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
+ match sector {
+ 0 => [v, t, p],
+ 1 => [q, v, p],
+ 2 => [p, v, t],
+ 3 => [p, q, v],
+ 4 => [t, p, v],
+ _ => [v, p, q],
+ }
+}
+
+fn state_at(buffer: &StrokeBuffer, under: Option<&Raster>, x: i64, y: i64) -> [f32; 4] {
+ let grid = buffer.grid();
+ if x < 0 || y < 0 || x >= grid.width as i64 || y >= grid.height as i64 {
+ return [0.0; 4];
+ }
+ let (x, y) = (x as usize, y as usize);
+ let index = (y / TILE) * grid.cols + x / TILE;
+ let px = (y % TILE) * TILE + x % TILE;
+ let replaced = buffer.mode == Mode::Replace && buffer.coverage(index).is_some_and(|c| c[px] > 0.0);
+ match (replaced, buffer.paint(index)) {
+ (true, Some(target)) => [
+ target[px * 4],
+ target[px * 4 + 1],
+ target[px * 4 + 2],
+ target[px * 4 + 3],
+ ],
+ _ => under
+ .and_then(|r| r.at(index))
+ .map_or([0.0; 4], |t| std::array::from_fn(|c| t[px * 4 + c].to_f32())),
+ }
+}
+
+fn pick(buffer: &StrokeBuffer, under: Option<&Raster>, cx: f32, cy: f32, radius: f32) -> [f32; 4] {
+ let r = radius * 0.4;
+ let points = [(0.0, 0.0), (r, 0.0), (-r, 0.0), (0.0, r), (0.0, -r)];
+ let sum = points.iter().fold([0.0f32; 4], |acc, (dx, dy)| {
+ let s = state_at(buffer, under, (cx + dx).floor() as i64, (cy + dy).floor() as i64);
+ std::array::from_fn(|i| acc[i] + s[i])
+ });
+ sum.map(|v| v / points.len() as f32)
+}
+
+struct Dab {
+ cx: f32,
+ cy: f32,
+ radius: f32,
+ angle: f32,
+ flow: f32,
+ cap: f32,
+ p: f32,
+ dual: [[f32; 3]; 8],
+ count: usize,
+ color: Option<[f32; 3]>,
+}
+
+const RING: [(f32, f32); 8] = [
+ (1.0, 0.0),
+ (0.707, 0.707),
+ (0.0, 1.0),
+ (-0.707, 0.707),
+ (-1.0, 0.0),
+ (-0.707, -0.707),
+ (0.0, -1.0),
+ (0.707, -0.707),
+];
+
+enum Replace {
+ Smudge((f32, f32)),
+ Blend,
+}
+
+fn tip_value(tip: &Tip, u: f32, v: f32, d2: f32, radius: f32) -> f32 {
+ match tip {
+ Tip::Round { hardness } => {
+ let d = libm::sqrtf(d2);
+ let edge = ((1.0 - d) * radius + 0.5).clamp(0.0, 1.0);
+ let t = ((d - hardness) / (1.0 - hardness).max(1e-4)).clamp(0.0, 1.0);
+ (1.0 - t * t * (3.0 - 2.0 * t)).min(edge)
+ }
+ Tip::Mask(mask) => mask.sample(u, v),
+ }
+}
+
+fn dual_value(brush: &Brush, dab: &Dab, u: f32, v: f32, radius: f32) -> f32 {
+ let Some(dual) = brush.dual.as_ref() else {
+ return 1.0;
+ };
+ dab.dual.iter().take(dab.count).fold(0.0f32, |most, [dx, dy, turn]| {
+ let (su, sv) = ((u - dx) / dual.size, (v - dy) / dual.size);
+ let (sin, cos) = (libm::sinf(*turn), libm::cosf(*turn));
+ let (ru, rv) = (su * cos + sv * sin, sv * cos - su * sin);
+ let d2 = ru * ru + rv * rv;
+ match d2 >= 1.0 {
+ true => most,
+ false => most.max(tip_value(&dual.tip, ru, rv, d2, radius * dual.size)),
+ }
+ })
+}
+
+fn texture_value(texture: &Texture, x: usize, y: usize, pressure: f32) -> f32 {
+ let g = match texture.scale == 1.0 {
+ true => texture.grain.at(x, y),
+ false => texture
+ .grain
+ .at((x as f32 / texture.scale) as usize, (y as f32 / texture.scale) as usize),
+ };
+ let g = match texture.contrast == 1.0 {
+ true => g,
+ false => ((g - 0.5) * texture.contrast + 0.5).clamp(0.0, 1.0),
+ };
+ let strength = match texture.pressure == 0.0 {
+ true => texture.strength,
+ false => texture.strength * (1.0 - texture.pressure * pressure),
+ };
+ strength * (1.0 - g)
+}
+
+struct Area {
+ x0: usize,
+ y0: usize,
+ x1: usize,
+ y1: usize,
+ radius: f32,
+ flow: f32,
+ reach2: f32,
+}
+
+fn area(buffer: &StrokeBuffer, dab: &Dab) -> Option<Area> {
+ let (radius, flow) = if dab.radius < MIN_RADIUS {
+ let k = dab.radius / MIN_RADIUS;
+ (MIN_RADIUS, dab.flow * k * k)
+ } else {
+ (dab.radius, dab.flow)
+ };
+ let reach = radius + 1.0;
+ let reach2 = (reach / radius) * (reach / radius);
+ let (width, height) = (buffer.grid().width as f32, buffer.grid().height as f32);
+ let x0 = (dab.cx - reach).floor().max(0.0) as usize;
+ let y0 = (dab.cy - reach).floor().max(0.0) as usize;
+ let x1 = (dab.cx + reach).ceil().clamp(0.0, width) as usize;
+ let y1 = (dab.cy + reach).ceil().clamp(0.0, height) as usize;
+ (x0 < x1 && y0 < y1).then_some(Area {
+ x0,
+ y0,
+ x1,
+ y1,
+ radius,
+ flow,
+ reach2,
+ })
+}
+
+fn stamp(buffer: &mut StrokeBuffer, brush: &Brush, dab: Dab) {
+ let Some(Area {
+ x0,
+ y0,
+ x1,
+ y1,
+ radius,
+ flow,
+ reach2,
+ }) = area(buffer, &dab)
+ else {
+ return;
+ };
+ let (cx, cy, cap) = (dab.cx, dab.cy, dab.cap);
+ let (sin, cos) = (libm::sinf(dab.angle), libm::cosf(dab.angle));
+ let inv_radius = 1.0 / radius;
+ let inv_round = 1.0 / brush.def.roundness;
+ let full = cap >= 1.0;
+ let cols = buffer.grid().cols;
+ for ty in y0 / TILE..=(y1 - 1) / TILE {
+ for tx in x0 / TILE..=(x1 - 1) / TILE {
+ if buffer.skip(ty * cols + tx) {
+ continue;
+ }
+ let (tile, mut paint) = buffer.tiles_mut(ty * cols + tx);
+ let (ox, oy) = (tx * TILE, ty * TILE);
+ for y in y0.max(oy)..y1.min(oy + TILE) {
+ let py = y as f32 + 0.5 - cy;
+ let row = (y - oy) * TILE;
+ for x in x0.max(ox)..x1.min(ox + TILE) {
+ let px = x as f32 + 0.5 - cx;
+ let u = (px * cos + py * sin) * inv_radius;
+ let v = (py * cos - px * sin) * inv_round * inv_radius;
+ let d2 = u * u + v * v;
+ if d2 >= reach2 {
+ continue;
+ }
+ let mut a = tip_value(&brush.tip, u, v, d2, radius) * flow;
+ if dab.count > 0 {
+ a *= dual_value(brush, &dab, u, v, radius);
+ }
+ if let Some(texture) = &brush.grain {
+ a = (a - texture_value(texture, x, y, dab.p)).max(0.0);
+ }
+ if a > 0.0 {
+ let at = row + x - ox;
+ let c = &mut tile[at];
+ let gain = (cap - *c) * a.min(1.0);
+ if full || gain > 0.0 {
+ *c += gain;
+ if let (Some(paint), Some(colour)) = (paint.as_deref_mut(), dab.color)
+ && gain > 0.0
+ {
+ let w = &mut paint[at * 4..at * 4 + 4];
+ (0..3).for_each(|i| w[i] += colour[i] * gain);
+ w[3] += gain;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+fn stamp_replace(
+ buffer: &mut StrokeBuffer,
+ brush: &Brush,
+ dab: Dab,
+ under: Option<&Raster>,
+ how: Replace,
+ strength: f32,
+) {
+ let Some(Area {
+ x0,
+ y0,
+ x1,
+ y1,
+ radius,
+ flow,
+ reach2,
+ }) = area(buffer, &dab)
+ else {
+ return;
+ };
+ if let Replace::Smudge((0.0, 0.0)) = how {
+ return;
+ }
+ let (sin, cos) = (libm::sinf(dab.angle), libm::cosf(dab.angle));
+ let (inv_radius, inv_round) = (1.0 / radius, 1.0 / brush.def.roundness);
+ let cols = buffer.grid().cols;
+ let changes: Vec<(usize, usize, [f32; 4])> = (y0..y1)
+ .flat_map(|y| (x0..x1).map(move |x| (x, y)))
+ .filter(|&(x, y)| buffer.allowed((y / TILE) * cols + x / TILE))
+ .filter_map(|(x, y)| {
+ let (px, py) = (x as f32 + 0.5 - dab.cx, y as f32 + 0.5 - dab.cy);
+ let u = (px * cos + py * sin) * inv_radius;
+ let v = (py * cos - px * sin) * inv_round * inv_radius;
+ let d2 = u * u + v * v;
+ if d2 >= reach2 {
+ return None;
+ }
+ let mut a = tip_value(&brush.tip, u, v, d2, radius) * flow;
+ if dab.count > 0 {
+ a *= dual_value(brush, &dab, u, v, radius);
+ }
+ if let Some(texture) = &brush.grain {
+ a = (a - texture_value(texture, x, y, dab.p)).max(0.0);
+ }
+ let a = (a * strength * dab.cap).min(1.0);
+ if a <= 0.0 {
+ return None;
+ }
+ let here = state_at(buffer, under, x as i64, y as i64);
+ let from = match how {
+ Replace::Smudge((dx, dy)) => state_at(
+ buffer,
+ under,
+ (x as f32 - dx).round() as i64,
+ (y as f32 - dy).round() as i64,
+ ),
+ Replace::Blend => {
+ let reach = (radius * 0.3).max(1.0);
+ let sum = RING.iter().fold(here, |acc, (dx, dy)| {
+ let s = state_at(
+ buffer,
+ under,
+ (x as f32 + dx * reach).round() as i64,
+ (y as f32 + dy * reach).round() as i64,
+ );
+ std::array::from_fn(|c| acc[c] + s[c])
+ });
+ sum.map(|v| v / (RING.len() + 1) as f32)
+ }
+ };
+ Some((x, y, std::array::from_fn(|c| here[c] + (from[c] - here[c]) * a)))
+ })
+ .collect();
+ changes.into_iter().for_each(|(x, y, value)| {
+ let index = (y / TILE) * cols + x / TILE;
+ let at = (y % TILE) * TILE + x % TILE;
+ let (tile, paint) = buffer.tiles_mut(index);
+ tile[at] = 1.0;
+ if let Some(paint) = paint {
+ paint[at * 4..at * 4 + 4].copy_from_slice(&value);
+ }
+ });
+}
+
+pub fn blend_coverage(target: &mut [f16], coverage: &[f32], color: Rgba, opacity: f32, blend: StrokeBlend) {
+ let alpha = (opacity * color[3]).clamp(0.0, 1.0);
+ coverage
+ .iter()
+ .zip(target.as_chunks_mut::<4>().0)
+ .filter(|(c, _)| **c > 0.0)
+ .for_each(|(&c, px)| {
+ let a = c * alpha;
+ let keep = 1.0 - a;
+ match blend {
+ StrokeBlend::Normal => {
+ (0..3).for_each(|i| px[i] = f16::from_f32(color[i] * a + px[i].to_f32() * keep));
+ px[3] = f16::from_f32(a + px[3].to_f32() * keep);
+ }
+ StrokeBlend::Erase => px.iter_mut().for_each(|v| *v = f16::from_f32(v.to_f32() * keep)),
+ StrokeBlend::Atop => {
+ let under = px[3].to_f32();
+ (0..3).for_each(|i| px[i] = f16::from_f32(color[i] * a * under + px[i].to_f32() * keep));
+ }
+ }
+ });
+}
+
+fn blend_colours(target: &mut [f16], coverage: &[f32], paint: &[f32], color: Rgba, opacity: f32, blend: StrokeBlend) {
+ let alpha = (opacity * color[3]).clamp(0.0, 1.0);
+ coverage
+ .iter()
+ .zip(paint.as_chunks::<4>().0)
+ .zip(target.as_chunks_mut::<4>().0)
+ .filter(|((c, _), _)| **c > 0.0)
+ .for_each(|((&c, w), px)| {
+ let colour: [f32; 3] = match w[3] > 0.0 {
+ true => std::array::from_fn(|i| w[i] / w[3]),
+ false => [color[0], color[1], color[2]],
+ };
+ let a = c * alpha;
+ let keep = 1.0 - a;
+ match blend {
+ StrokeBlend::Normal => {
+ (0..3).for_each(|i| px[i] = f16::from_f32(colour[i] * a + px[i].to_f32() * keep));
+ px[3] = f16::from_f32(a + px[3].to_f32() * keep);
+ }
+ StrokeBlend::Erase => px.iter_mut().for_each(|v| *v = f16::from_f32(v.to_f32() * keep)),
+ StrokeBlend::Atop => {
+ let under = px[3].to_f32();
+ (0..3).for_each(|i| px[i] = f16::from_f32(colour[i] * a * under + px[i].to_f32() * keep));
+ }
+ }
+ });
+}
+
+fn blend_replace(target: &mut [f16], coverage: &[f32], paint: &[f32], opacity: f32, lock: bool) {
+ coverage
+ .iter()
+ .zip(paint.as_chunks::<4>().0)
+ .zip(target.as_chunks_mut::<4>().0)
+ .filter(|((c, _), _)| **c > 0.0)
+ .for_each(|((&c, w), px)| {
+ let a = (c * opacity).clamp(0.0, 1.0);
+ let alpha = px[3].to_f32();
+ let next: [f32; 4] = std::array::from_fn(|i| px[i].to_f32() + (w[i] - px[i].to_f32()) * a);
+ match lock && next[3] > 1e-6 {
+ true => (0..4).for_each(|i| px[i] = f16::from_f32(next[i] * alpha / next[3])),
+ false if lock => {}
+ false => (0..4).for_each(|i| px[i] = f16::from_f32(next[i])),
+ }
+ });
+}
+
+fn land(
+ target: &mut [f16],
+ coverage: &[f32],
+ paint: Option<&[f32]>,
+ mode: Mode,
+ color: Rgba,
+ opacity: f32,
+ blend: StrokeBlend,
+) {
+ match (mode, paint) {
+ (Mode::Colour, Some(paint)) => blend_colours(target, coverage, paint, color, opacity, blend),
+ (Mode::Replace, Some(paint)) => blend_replace(target, coverage, paint, opacity, blend == StrokeBlend::Atop),
+ _ => blend_coverage(target, coverage, color, opacity, blend),
+ }
+}
+
+pub fn land_tile(
+ target: &mut [f16],
+ buffer: &StrokeBuffer,
+ index: usize,
+ color: Rgba,
+ opacity: f32,
+ blend: StrokeBlend,
+) {
+ if let Some(coverage) = buffer.coverage(index) {
+ land(
+ target,
+ coverage,
+ buffer.paint(index),
+ buffer.mode,
+ color,
+ opacity,
+ blend,
+ );
+ }
+}
+
+pub fn commit(
+ raster: &mut Raster,
+ buffer: &mut StrokeBuffer,
+ color: Rgba,
+ opacity: f32,
+ blend: StrokeBlend,
+) -> Vec<usize> {
+ commit_cut(raster, buffer, color, opacity, Some(blend), &[])
+}
+
+fn commit_cut(
+ raster: &mut Raster,
+ buffer: &mut StrokeBuffer,
+ color: Rgba,
+ opacity: f32,
+ blend: Option<StrokeBlend>,
+ cuts: &[Cut],
+) -> Vec<usize> {
+ let touched = buffer.touched().to_vec();
+ let cols = raster.cols;
+ let mode = buffer.mode;
+ let allowed: Vec<usize> = touched.iter().copied().filter(|&i| buffer.allowed(i)).collect();
+ allowed.into_iter().for_each(|index| {
+ let Some(blend) = blend else {
+ return;
+ };
+ let factor = cut::factor(cuts, ((index % cols) * TILE, (index / cols) * TILE));
+ let Some(coverage) = buffer.coverage_mut(index) else {
+ return;
+ };
+ if let Some(factor) = factor {
+ coverage.iter_mut().zip(&factor).for_each(|(c, k)| *c *= k);
+ if coverage.iter().all(|c| *c <= 0.0) {
+ return;
+ }
+ }
+ let target = match (blend, mode) {
+ (StrokeBlend::Normal, _) | (_, Mode::Replace) => Some(raster.ensure(index)),
+ (StrokeBlend::Erase | StrokeBlend::Atop, _) => raster.at_mut(index),
+ };
+ if let (Some(target), Some(coverage)) = (target, buffer.coverage(index)) {
+ land(target, coverage, buffer.paint(index), mode, color, opacity, blend);
+ }
+ });
+ buffer.reset();
+ touched
+}
+
+pub fn stroke_blend(brush: &Brush, lock: bool) -> Option<StrokeBlend> {
+ match (brush.blend, lock) {
+ (blend, false) => Some(blend),
+ (StrokeBlend::Erase, true) => None,
+ (_, true) => Some(StrokeBlend::Atop),
+ }
+}
+
+pub fn land_stroke(raster: &mut Raster, buffer: &mut StrokeBuffer, stroke: &Stroke, brush: &Brush) -> Vec<usize> {
+ commit_cut(
+ raster,
+ buffer,
+ stroke.color(),
+ stroke.opacity,
+ stroke_blend(brush, stroke.lock),
+ &stroke.cuts,
+ )
+}
+
+pub fn draw_stroke(buffer: &mut StrokeBuffer, brush: &Brush, stroke: &Stroke) -> usize {
+ draw_stroke_on(buffer, brush, stroke, None)
+}
+
+pub fn draw_stroke_on(buffer: &mut StrokeBuffer, brush: &Brush, stroke: &Stroke, under: Option<&Raster>) -> usize {
+ let mut painter = StrokePainter::new(brush, stroke);
+ buffer.mode = painter.mode();
+ stroke.samples.iter().for_each(|s| painter.push_on(s, buffer, under));
+ painter.dabs()
+}
+
+pub fn paint_stroke(raster: &mut Raster, buffer: &mut StrokeBuffer, brush: &Brush, stroke: &Stroke) -> usize {
+ let dabs = draw_stroke_on(buffer, brush, stroke, Some(raster));
+ land_stroke(raster, buffer, stroke, brush);
+ dabs
+}
+
+pub struct Replayed {
+ pub raster: Raster,
+ pub dabs: usize,
+}
+
+pub fn paint_mark(
+ raster: &mut Raster,
+ buffer: &mut StrokeBuffer,
+ brushes: &BrushSet,
+ mark: &Mark,
+) -> Result<Vec<usize>> {
+ Ok(match mark {
+ Mark::Stroke(stroke) => {
+ let brush = brushes.get(&stroke.brush)?;
+ draw_stroke_on(buffer, brush, stroke, Some(raster));
+ land_stroke(raster, buffer, stroke, brush)
+ }
+ Mark::Fill(fill) => crate::fill::paint_fill_where(raster, fill, |i| buffer.allowed(i)),
+ })
+}
+
+pub fn replay_onto(raster: &mut Raster, marks: &[Mark], brushes: &BrushSet) -> Result<usize> {
+ let mut buffer = StrokeBuffer::new(raster.width, raster.height);
+ marks.iter().try_fold(0usize, |n, mark| {
+ Ok::<_, anyhow::Error>(
+ n + match mark {
+ Mark::Stroke(stroke) => paint_stroke(raster, &mut buffer, brushes.get(&stroke.brush)?, stroke),
+ Mark::Fill(fill) => {
+ crate::fill::paint_fill(raster, fill);
+ 0
+ }
+ },
+ )
+ })
+}
+
+pub fn replay(width: u32, height: u32, marks: &[Mark], brushes: &BrushSet) -> Result<Replayed> {
+ let mut raster = Raster::new(width, height);
+ let dabs = replay_onto(&mut raster, marks, brushes)?;
+ Ok(Replayed { raster, dabs })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::stroke::marks;
+ use klad_core::synth::Synth;
+
+ fn alpha(raster: &Raster, x: usize, y: usize) -> f32 {
+ raster
+ .get(x / TILE, y / TILE)
+ .map(|t| t[((y % TILE) * TILE + x % TILE) * 4 + 3].to_f32())
+ .unwrap_or(0.0)
+ }
+
+ fn m1() -> BrushSet {
+ let mut set = BrushSet::presets();
+ ["pencil", "ink", "soft", "chalk", "eraser"]
+ .iter()
+ .for_each(|id| set.insert(id, klad_core::brushes::legacy_m1(id).unwrap()));
+ set
+ }
+
+ fn line(brush: &str, size: f32, from: (f32, f32), to: (f32, f32), pressure: (f32, f32)) -> Stroke {
+ let points: Vec<(f32, f32, f32)> = (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,
+ pressure.0 + (pressure.1 - pressure.0) * t,
+ )
+ })
+ .collect();
+ Stroke::new(1, brush, [0.0, 0.0, 0.0, 1.0], size, 9).with_points(&points, 5.0)
+ }
+
+ fn width_at(raster: &Raster, x: usize) -> usize {
+ (0..raster.height as usize)
+ .filter(|&y| alpha(raster, x, y) > 0.5)
+ .count()
+ }
+
+ #[test]
+ fn ink_line_tapers_with_pressure() {
+ let brushes = BrushSet::presets();
+ let stroke = line("ink", 20.0, (20.0, 100.0), (480.0, 100.0), (0.1, 1.0));
+ let out = replay(512, 200, &[stroke.into()], &brushes).unwrap();
+ let (thin, thick) = (width_at(&out.raster, 40), width_at(&out.raster, 460));
+ assert!(thin >= 1 && thin < thick, "thin {thin} thick {thick}");
+ assert!((18..=21).contains(&thick), "thick {thick}");
+ assert!(alpha(&out.raster, 250, 100) > 0.99);
+ assert_eq!(alpha(&out.raster, 250, 150), 0.0);
+ }
+
+ #[test]
+ fn dab_count_follows_spacing() {
+ let brushes = BrushSet::presets();
+ let stroke = line("ink", 20.0, (10.0, 50.0), (410.0, 50.0), (1.0, 1.0));
+ let out = replay(512, 100, &[stroke.into()], &brushes).unwrap();
+ let expected = 400.0 / (20.0 * 0.04);
+ assert!((out.dabs as f32 - expected).abs() < 3.0, "dabs {}", out.dabs);
+ }
+
+ #[test]
+ fn single_sample_makes_a_dot() {
+ let brushes = BrushSet::presets();
+ let dot = Stroke::new(1, "ink", [1.0, 0.0, 0.0, 1.0], 10.0, 1).with_points(&[(64.0, 64.0, 1.0)], 0.0);
+ let out = replay(128, 128, &[dot.into()], &brushes).unwrap();
+ assert_eq!(out.dabs, 1);
+ assert!(alpha(&out.raster, 64, 64) > 0.99);
+ assert_eq!(alpha(&out.raster, 64, 80), 0.0);
+ }
+
+ #[test]
+ fn eraser_removes_paint() {
+ let brushes = BrushSet::presets();
+ let paint = line("ink", 30.0, (20.0, 64.0), (300.0, 64.0), (1.0, 1.0));
+ let mut erase = line("eraser", 40.0, (150.0, 10.0), (150.0, 120.0), (1.0, 1.0));
+ erase.id = 2;
+ let out = replay(320, 128, &[paint.into(), erase.into()], &brushes).unwrap();
+ assert!(alpha(&out.raster, 60, 64) > 0.99);
+ assert!(alpha(&out.raster, 150, 64) < 0.01);
+ }
+
+ #[test]
+ fn replay_is_deterministic() {
+ let brushes = BrushSet::presets();
+ let strokes = marks(Synth::canvas(512.0, 512.0).strokes(60, 4));
+ let a = replay(512, 512, &strokes, &brushes).unwrap();
+ let b = replay(512, 512, &strokes, &brushes).unwrap();
+ assert_eq!(a.raster.hash(), b.raster.hash());
+ assert_eq!(a.dabs, b.dabs);
+ let other = replay(512, 512, &marks(Synth::canvas(512.0, 512.0).strokes(60, 5)), &brushes).unwrap();
+ assert_ne!(a.raster.hash(), other.raster.hash());
+ }
+
+ #[test]
+ fn m1_brushes_as_data_paint_the_m1_pixels() {
+ let fixtures = [
+ ("pencil", 0xdcb685af511515ed_u64, 10166),
+ ("ink", 0x8a42ee6868d7dbf4, 11493),
+ ("soft", 0x1155c92abc144952, 9921),
+ ("chalk", 0x76b8675240bf4ea5, 9239),
+ ("eraser", 0xe01fb6ff82ad3584, 10880),
+ ];
+ let brushes = m1();
+ fixtures.iter().for_each(|&(name, hash, dabs)| {
+ let mut synth = Synth::canvas(512.0, 512.0);
+ synth.brushes = vec!["ink".into(), name.to_string()];
+ let out = replay(512, 512, &marks(synth.strokes(40, 77)), &brushes).unwrap();
+ assert_eq!((out.raster.hash(), out.dabs), (hash, dabs), "{name}");
+ });
+ }
+
+ #[test]
+ fn taper_thins_both_ends_by_length_whatever_the_pressure() {
+ let brushes = BrushSet::presets();
+ let flat = line("ink", 20.0, (20.0, 100.0), (480.0, 100.0), (1.0, 1.0));
+ let tapered = flat.clone().tapered([60.0, 120.0]);
+ let plain = replay(512, 200, &[flat.into()], &brushes).unwrap();
+ let out = replay(512, 200, &[tapered.into()], &brushes).unwrap();
+ let widths = [30, 50, 250, 400, 470].map(|x| width_at(&out.raster, x));
+ assert_eq!(width_at(&plain.raster, 30), width_at(&plain.raster, 250));
+ assert!(widths[0] < widths[1] && widths[1] < widths[2], "{widths:?}");
+ assert!(widths[4] < widths[3] && widths[3] < widths[2], "{widths:?}");
+ assert_eq!(widths[2], width_at(&plain.raster, 250));
+ assert!(alpha(&out.raster, 18, 100) < 0.05);
+ }
+
+ #[test]
+ fn a_tapered_tap_still_leaves_a_dot() {
+ let brushes = BrushSet::presets();
+ let dot = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 10.0, 1)
+ .with_points(&[(64.0, 64.0, 1.0), (64.0, 64.0, 1.0)], 4.0)
+ .tapered([10.0, 24.0]);
+ let out = replay(128, 128, &[dot.into()], &brushes).unwrap();
+ assert!(alpha(&out.raster, 64, 64) > 0.99);
+ }
+
+ #[test]
+ fn an_all_zero_pressure_stroke_draws_as_if_pressure_were_missing() {
+ let brushes = BrushSet::presets();
+ let zero = line("ink", 20.0, (20.0, 100.0), (480.0, 100.0), (0.0, 0.0));
+ let full = line("ink", 20.0, (20.0, 100.0), (480.0, 100.0), (1.0, 1.0));
+ let a = replay(512, 200, &[zero.into()], &brushes).unwrap();
+ let b = replay(512, 200, &[full.into()], &brushes).unwrap();
+ assert_eq!(a.raster.hash(), b.raster.hash());
+ let light = line("ink", 20.0, (20.0, 100.0), (480.0, 100.0), (0.0, 0.002));
+ let thin = replay(512, 200, &[light.into()], &brushes).unwrap();
+ assert!(width_at(&thin.raster, 250) < 3);
+ }
+
+ #[test]
+ fn live_painting_then_a_repaint_matches_replay() {
+ let brushes = BrushSet::presets();
+ let stroke = line("ink", 16.0, (20.0, 60.0), (300.0, 90.0), (0.2, 0.9)).tapered([10.0, 24.0]);
+ let brush = brushes.get("ink").unwrap();
+ let mut buffer = StrokeBuffer::new(320, 160);
+ let mut live = StrokePainter::live(brush, &stroke);
+ stroke.samples.iter().for_each(|s| live.push(s, &mut buffer));
+ assert!(needs_repaint(&stroke));
+ buffer.reset();
+ draw_stroke(&mut buffer, brush, &stroke);
+ let mut raster = Raster::new(320, 160);
+ commit(&mut raster, &mut buffer, stroke.color(), stroke.opacity, brush.blend);
+ let replayed = replay(320, 160, &[stroke.into()], &brushes).unwrap().raster;
+ assert_eq!(raster.hash(), replayed.hash());
+ let untapered = line("ink", 16.0, (20.0, 60.0), (300.0, 90.0), (0.2, 0.9));
+ assert!(!needs_repaint(&untapered));
+ }
+
+ #[test]
+ fn marker_strokes_cap_their_own_overlap_but_build_up_across_strokes() {
+ let brushes = BrushSet::presets();
+ let there = line("marker", 30.0, (20.0, 64.0), (300.0, 64.0), (1.0, 1.0));
+ let mut back = line("marker", 30.0, (300.0, 64.0), (20.0, 64.0), (1.0, 1.0));
+ back.id = 2;
+ let mut once = there.clone();
+ once.samples.extend(back.samples.iter().skip(1).copied());
+ let single = replay(320, 128, &[once.into()], &brushes).unwrap();
+ let double = replay(320, 128, &[there.into(), back.into()], &brushes).unwrap();
+ let (a, b) = (alpha(&single.raster, 160, 64), alpha(&double.raster, 160, 64));
+ assert!((a - 0.7).abs() < 0.02, "one stroke {a}");
+ assert!(b > a + 0.15, "two strokes {b}");
+ }
+
+ #[test]
+ fn strokes_off_canvas_are_clipped() {
+ let brushes = BrushSet::presets();
+ let stroke = line("soft", 80.0, (-200.0, -50.0), (900.0, 300.0), (1.0, 1.0));
+ let out = replay(256, 256, &[stroke.into()], &brushes).unwrap();
+ assert!(out.raster.count() > 0);
+ }
+
+ fn rgba(raster: &Raster, x: usize, y: usize) -> [f32; 4] {
+ raster
+ .get(x / TILE, y / TILE)
+ .map(|t| std::array::from_fn(|c| t[((y % TILE) * TILE + x % TILE) * 4 + c].to_f32()))
+ .unwrap_or([0.0; 4])
+ }
+
+ fn coloured(brush: &str, size: f32, from: (f32, f32), to: (f32, f32), colour: Rgba, seed: u32) -> Stroke {
+ let mut s = line(brush, size, from, to, (1.0, 1.0));
+ s.color = klad_core::color::to_u16(colour);
+ s.seed = seed;
+ s
+ }
+
+ #[test]
+ fn picture_tips_and_dual_tips_leave_their_marks() {
+ let brushes = BrushSet::presets();
+ let ink = replay(
+ 512,
+ 128,
+ &[line("ink", 40.0, (40.0, 64.0), (470.0, 64.0), (1.0, 1.0)).into()],
+ &brushes,
+ )
+ .unwrap()
+ .raster;
+ ["flat-bristle", "round-bristle", "sponge", "dry-brush"]
+ .iter()
+ .for_each(|name| {
+ let out = replay(
+ 512,
+ 128,
+ &[line(name, 40.0, (40.0, 64.0), (470.0, 64.0), (1.0, 1.0)).into()],
+ &brushes,
+ )
+ .unwrap()
+ .raster;
+ let covered = |r: &Raster| {
+ (40..470)
+ .flat_map(|x| (40..90).map(move |y| (x, y)))
+ .filter(|&(x, y)| alpha(r, x, y) > 0.5)
+ .count()
+ };
+ let (mine, solid) = (covered(&out), covered(&ink));
+ assert!(mine > solid / 10 && mine < solid, "{name}: {mine} of {solid}");
+ });
+ let mut plain = klad_core::brushes::library("dry-brush").unwrap();
+ plain.dual = None;
+ let mut set = BrushSet::presets();
+ set.insert("plain", plain);
+ let count = |name: &str| {
+ let r = replay(
+ 512,
+ 128,
+ &[line(name, 40.0, (40.0, 64.0), (470.0, 64.0), (1.0, 1.0)).into()],
+ &set,
+ )
+ .unwrap()
+ .raster;
+ (0..512)
+ .flat_map(|x| (0..128).map(move |y| (x, y)))
+ .filter(|&(x, y)| alpha(&r, x, y) > 0.3)
+ .count()
+ };
+ assert!(
+ count("dry-brush") < count("plain") * 9 / 10,
+ "the dual tip takes paint away"
+ );
+ }
+
+ #[test]
+ fn texture_stays_on_the_canvas_under_two_strokes() {
+ let mut def = klad_core::brushes::library("soft").unwrap();
+ def.grain = Some(klad_core::brushes::GrainDef {
+ paper: None,
+ image: Some("sponge".into()),
+ strength: 1.0,
+ scale: 1.0,
+ contrast: 2.0,
+ pressure: 0.0,
+ });
+ let mut set = BrushSet::presets();
+ set.insert("textured", def);
+ let a = coloured("textured", 60.0, (100.0, 64.0), (300.0, 64.0), [0.0, 0.0, 0.0, 1.0], 1);
+ let b = coloured("textured", 60.0, (300.0, 64.0), (100.0, 64.0), [0.0, 0.0, 0.0, 1.0], 99);
+ let ra = replay(400, 128, &[a.into()], &set).unwrap().raster;
+ let rb = replay(400, 128, &[b.into()], &set).unwrap().raster;
+ let holes = |r: &Raster| {
+ (150..250)
+ .flat_map(|x| (55..74).map(move |y| (x, y)))
+ .filter(|&(x, y)| alpha(r, x, y) < 0.05)
+ .collect::<Vec<_>>()
+ };
+ assert!(!holes(&ra).is_empty());
+ assert_eq!(holes(&ra), holes(&rb), "the texture's holes are where they were");
+ }
+
+ #[test]
+ fn colour_jitter_repeats_with_its_seed_and_two_tone_follows_pressure() {
+ let brushes = BrushSet::presets();
+ let leaves = |seed| coloured("leaves", 30.0, (40.0, 64.0), (470.0, 64.0), [0.2, 0.5, 0.2, 1.0], seed);
+ let a = replay(512, 128, &[leaves(4).into()], &brushes).unwrap().raster;
+ let b = replay(512, 128, &[leaves(4).into()], &brushes).unwrap().raster;
+ let c = replay(512, 128, &[leaves(5).into()], &brushes).unwrap().raster;
+ assert_eq!(a.hash(), b.hash());
+ assert_ne!(a.hash(), c.hash());
+ let greens: Vec<[f32; 4]> = (0..512)
+ .flat_map(|x| (0..128).map(move |y| (x, y)))
+ .map(|(x, y)| rgba(&a, x, y))
+ .filter(|p| p[3] > 0.95)
+ .collect();
+ assert!(greens.iter().any(|p| (p[1] - 0.5).abs() > 0.02), "the colour varies");
+ assert!(greens.iter().all(|p| p[1] > p[0] && p[1] > p[2]), "and stays green");
+ let tone = |pressure: f32| {
+ let mut s = line("two-tone", 20.0, (20.0, 32.0), (200.0, 32.0), (pressure, pressure));
+ s.color = klad_core::color::to_u16([1.0, 0.0, 0.0, 1.0]);
+ s.second = Some(klad_core::color::to_u16([0.0, 0.0, 1.0, 1.0]));
+ let r = replay(256, 64, &[s.into()], &brushes).unwrap().raster;
+ rgba(&r, 110, 32)
+ };
+ let (hard, light) = (tone(1.0), tone(0.1));
+ assert!(hard[0] > 0.95 && hard[2] < 0.05, "{hard:?}");
+ assert!(light[2] > 0.8 && light[0] < 0.2, "{light:?}");
+ }
+
+ fn base_and(brush: &str) -> Vec<Mark> {
+ let red = coloured("ink", 60.0, (40.0, 64.0), (220.0, 64.0), [1.0, 0.0, 0.0, 1.0], 1);
+ let mut over = coloured(brush, 24.0, (100.0, 64.0), (400.0, 64.0), [0.0, 0.0, 1.0, 1.0], 2);
+ over.id = 2;
+ vec![red.into(), over.into()]
+ }
+
+ #[test]
+ fn wet_paint_picks_up_what_it_crosses_and_smudge_and_blend_move_it() {
+ let brushes = BrushSet::presets();
+ let wet = replay(512, 128, &base_and("wet"), &brushes).unwrap().raster;
+ let (on_red, beyond) = (rgba(&wet, 200, 64), rgba(&wet, 330, 64));
+ assert!(on_red[0] > 0.15 && on_red[2] > 0.15, "mixed on the red: {on_red:?}");
+ assert!(beyond[0] > 0.05, "red carried past it: {beyond:?}");
+ let dry = replay(512, 128, &base_and("ink"), &brushes).unwrap().raster;
+ assert!(rgba(&dry, 330, 64)[0] < 0.01);
+ let smudged = replay(512, 128, &base_and("smudge"), &brushes).unwrap().raster;
+ assert_eq!(rgba(&dry, 262, 64)[0], 0.0, "the red ends before x 262");
+ let pulled = rgba(&smudged, 262, 64);
+ assert!(
+ pulled[0] > 0.05 && pulled[3] > 0.05,
+ "red pulled past its end: {pulled:?}"
+ );
+ assert!(pulled[2] < 0.01, "smudge lays no colour of its own");
+ let edge = |r: &Raster| (225..260).filter(|&x| (0.1..0.9).contains(&rgba(r, x, 64)[3])).count();
+ let blended = replay(512, 128, &base_and("blender"), &brushes).unwrap().raster;
+ assert!(edge(&blended) > edge(&dry), "the blender softens the red's end");
+ }
+
+ #[test]
+ fn an_edit_under_a_smudge_replays_the_smudge_correctly() {
+ let brushes = BrushSet::presets();
+ let marks = base_and("smudge");
+ let (mut cel, mut raster, _) = crate::replay::CelReplay::replay(512, 128, marks.clone(), &brushes).unwrap();
+ let mut edited = marks.clone();
+ if let Mark::Stroke(s) = &mut edited[0] {
+ s.color = klad_core::color::to_u16([0.0, 0.8, 0.0, 1.0]);
+ }
+ cel.update(&mut raster, edited.clone(), &brushes).unwrap();
+ let fresh = replay(512, 128, &edited, &brushes).unwrap().raster;
+ assert_eq!(raster.hash(), fresh.hash());
+ assert!(rgba(&raster, 262, 64)[1] > 0.05, "the smudge now pulls green");
+ }
+
+ #[test]
+ fn live_wet_painting_lands_as_its_replay() {
+ let brushes = BrushSet::presets();
+ let marks = base_and("wet");
+ let Mark::Stroke(wet) = &marks[1] else { panic!() };
+ let mut raster = replay(512, 128, &marks[..1], &brushes).unwrap().raster;
+ let brush = brushes.get("wet").unwrap();
+ let mut buffer = StrokeBuffer::new(512, 128);
+ let mut live = StrokePainter::new(brush, wet);
+ wet.samples
+ .iter()
+ .for_each(|s| live.push_on(s, &mut buffer, Some(&raster)));
+ commit(&mut raster, &mut buffer, wet.color(), wet.opacity, brush.blend);
+ assert_eq!(raster.hash(), replay(512, 128, &marks, &brushes).unwrap().raster.hash());
+ }
+}
+
+#[cfg(test)]
+mod timing {
+ use super::*;
+
+ #[test]
+ #[ignore]
+ fn painting_cost_per_sample_at_120_px() {
+ let brushes = BrushSet::presets();
+ ["ink", "dry-brush", "flat-bristle", "wet", "smudge", "blender"]
+ .iter()
+ .for_each(|name| {
+ let brush = brushes.get(name).unwrap();
+ let points: Vec<(f32, f32, f32)> = (0..300).map(|i| (100.0 + i as f32 * 2.0, 300.0, 0.8)).collect();
+ let stroke = Stroke::new(1, name, [0.3, 0.4, 0.5, 1.0], 120.0, 3).with_points(&points, 4.0);
+ let under = replay(
+ 1024,
+ 600,
+ &[Stroke::new(9, "ink", [0.8, 0.2, 0.1, 1.0], 200.0, 1)
+ .with_points(&[(100.0, 300.0, 1.0), (900.0, 300.0, 1.0)], 4.0)
+ .into()],
+ &brushes,
+ )
+ .unwrap()
+ .raster;
+ let mut buffer = StrokeBuffer::new(1024, 600);
+ let mut painter = StrokePainter::live(brush, &stroke);
+ let mut times: Vec<f64> = stroke
+ .samples
+ .iter()
+ .map(|s| {
+ let t = std::time::Instant::now();
+ painter.push_on(s, &mut buffer, Some(&under));
+ t.elapsed().as_secs_f64() * 1000.0
+ })
+ .collect();
+ times.sort_by(f64::total_cmp);
+ eprintln!(
+ "{name} at 120 px: per pen sample median {:.2} ms, p99 {:.2}, {} dabs",
+ times[times.len() / 2],
+ times[times.len() * 99 / 100],
+ painter.dabs()
+ );
+ });
+ }
+}
diff --git a/crates/brush/src/fill.rs b/crates/brush/src/fill.rs
new file mode 100644
index 0000000..58daae2
--- /dev/null
+++ b/crates/brush/src/fill.rs
@@ -0,0 +1,962 @@
+use crate::brush::StrokeBlend;
+use crate::engine::blend_coverage;
+use crate::tiles::{Raster, TILE, TILE_PX};
+use half::f16;
+use klad_core::fill::{Coverage, Fill, Seed};
+use rayon::prelude::*;
+
+const SUB: usize = 4;
+
+fn f16_floor_bits(v: f32) -> u16 {
+ if v <= 0.0 {
+ return 0;
+ }
+ let bits = f16::from_f32(v).to_bits();
+ if f16::from_bits(bits).to_f32() < v {
+ bits + 1
+ } else {
+ bits
+ }
+}
+
+fn f16_ceil_bits(v: f32) -> u16 {
+ let bits = f16::from_f32(v.min(65504.0)).to_bits();
+ if f16::from_bits(bits).to_f32() > v {
+ bits.saturating_sub(1)
+ } else {
+ bits
+ }
+}
+
+#[derive(Clone, Copy)]
+struct Accept {
+ lo: [u16; 4],
+ hi: [u16; 4],
+}
+
+impl Accept {
+ fn around(px: [f16; 4], tolerance: f32) -> Self {
+ let v = px.map(f16::to_f32);
+ Self {
+ lo: v.map(|c| f16_floor_bits(c - tolerance)),
+ hi: v.map(|c| f16_ceil_bits(c + tolerance)),
+ }
+ }
+
+ fn takes(&self, px: &[f16]) -> bool {
+ (0..4).all(|c| {
+ let bits = px[c].to_bits() & 0x7fff;
+ bits >= self.lo[c] && bits <= self.hi[c]
+ })
+ }
+}
+
+fn pixel(raster: &Raster, x: usize, y: usize) -> [f16; 4] {
+ match raster.get(x / TILE, y / TILE) {
+ Some(tile) => {
+ let at = ((y % TILE) * TILE + x % TILE) * 4;
+ [tile[at], tile[at + 1], tile[at + 2], tile[at + 3]]
+ }
+ None => [f16::ZERO; 4],
+ }
+}
+
+fn barrier(reference: &Raster, accept: &Accept) -> Vec<u8> {
+ let (w, h) = (reference.width as usize, reference.height as usize);
+ let empty = !accept.takes(&[f16::ZERO; 4]) as u8;
+ let mut out = vec![0u8; w * h];
+ out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
+ let ty = y / TILE;
+ (0..reference.cols).for_each(|tx| {
+ let x0 = tx * TILE;
+ let x1 = (x0 + TILE).min(w);
+ match reference.get(tx, ty) {
+ None => row[x0..x1].fill(empty),
+ Some(tile) => {
+ let line = &tile[(y % TILE) * TILE * 4..];
+ row[x0..x1].iter_mut().enumerate().for_each(|(i, b)| {
+ *b = !accept.takes(&line[i * 4..i * 4 + 4]) as u8;
+ });
+ }
+ }
+ });
+ });
+ out
+}
+
+pub fn distance_sq(mask: &[u8], w: usize, h: usize, reach: usize) -> Vec<u32> {
+ let cap = (reach + 1).min(u16::MAX as usize - 1) as u16;
+ let mut horizontal = vec![cap; w * h];
+ horizontal
+ .par_chunks_mut(w)
+ .zip(mask.par_chunks(w))
+ .for_each(|(dist, row)| {
+ let mut last: Option<usize> = None;
+ (0..w).for_each(|x| {
+ if row[x] != 0 {
+ last = Some(x);
+ }
+ if let Some(l) = last {
+ dist[x] = dist[x].min((x - l).min(cap as usize) as u16);
+ }
+ });
+ last = None;
+ (0..w).rev().for_each(|x| {
+ if row[x] != 0 {
+ last = Some(x);
+ }
+ if let Some(l) = last {
+ dist[x] = dist[x].min((l - x).min(cap as usize) as u16);
+ }
+ });
+ });
+ let far = (cap as u32) * (cap as u32);
+ let mut out = vec![far; w * h];
+ out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
+ let rows = y.saturating_sub(reach)..(y + reach + 1).min(h);
+ row.iter_mut().enumerate().for_each(|(x, o)| {
+ *o = rows.clone().fold(far, |best, yy| {
+ let dx = horizontal[yy * w + x] as u32;
+ let dy = yy.abs_diff(y) as u32;
+ best.min(dx * dx + dy * dy)
+ });
+ });
+ });
+ out
+}
+
+pub fn dilate(mask: &[u8], w: usize, h: usize, radius: f32) -> Vec<u8> {
+ if radius <= 0.0 {
+ return mask.to_vec();
+ }
+ let limit = (radius * radius).floor() as u32;
+ distance_sq(mask, w, h, radius.floor() as usize)
+ .par_iter()
+ .map(|&d| (d <= limit) as u8)
+ .collect()
+}
+
+fn spread(allowed: &[u8], region: &mut [u8], w: usize, h: usize, x: usize, y: usize) {
+ let open = |region: &[u8], x: usize, y: usize| allowed[y * w + x] != 0 && region[y * w + x] == 0;
+ if x >= w || y >= h || !open(region, x, y) {
+ return;
+ }
+ let mut stack = vec![(x, y)];
+ while let Some((x, y)) = stack.pop() {
+ if !open(region, x, y) {
+ continue;
+ }
+ let mut left = x;
+ while left > 0 && open(region, left - 1, y) {
+ left -= 1;
+ }
+ let mut right = x;
+ while right + 1 < w && open(region, right + 1, y) {
+ right += 1;
+ }
+ region[y * w + left..=y * w + right].fill(1);
+ [y.checked_sub(1), (y + 1 < h).then_some(y + 1)]
+ .into_iter()
+ .flatten()
+ .for_each(|ny| {
+ let mut inside = false;
+ (left..=right).for_each(|nx| {
+ let here = open(region, nx, ny);
+ if here && !inside {
+ stack.push((nx, ny));
+ }
+ inside = here;
+ });
+ });
+ }
+}
+
+pub fn flood_region(allowed: &[u8], w: usize, h: usize, x: usize, y: usize) -> Vec<u8> {
+ let mut region = vec![0u8; w * h];
+ spread(allowed, &mut region, w, h, x, y);
+ region
+}
+
+fn real_regions(free: &[u8], inner: &[u8], deep: &[u8], w: usize, h: usize) -> Vec<u8> {
+ let others = and(free, |i| inner[i] == 0);
+ let mut rivals = vec![0u8; w * h];
+ (0..w * h)
+ .filter(|&i| deep[i] == 0 && others[i] != 0)
+ .for_each(|i| spread(&others, &mut rivals, w, h, i % w, i / w));
+ (0..w * h)
+ .into_par_iter()
+ .map(|i| (inner[i] != 0 || rivals[i] != 0) as u8)
+ .collect()
+}
+
+const OWN: u8 = 1;
+const RIVAL: u8 = 2;
+
+fn neighbours(i: usize, w: usize, h: usize) -> impl Iterator<Item = (usize, u32)> {
+ let (x, y) = ((i % w) as isize, (i / w) as isize);
+ [
+ (-1, 0, 3),
+ (1, 0, 3),
+ (0, -1, 3),
+ (0, 1, 3),
+ (-1, -1, 4),
+ (1, -1, 4),
+ (-1, 1, 4),
+ (1, 1, 4),
+ ]
+ .into_iter()
+ .filter_map(move |(dx, dy, cost)| {
+ let (nx, ny) = (x + dx, y + dy);
+ (nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h).then(|| (ny as usize * w + nx as usize, cost))
+ })
+}
+
+fn nearest_free(open: &[u8], free: &[u8], w: usize, h: usize, from: usize, limit: usize) -> Option<usize> {
+ let mut seen = vec![false; w * h];
+ let mut ring = vec![from];
+ seen[from] = true;
+ (0..=limit).find_map(|_| {
+ if let Some(&hit) = ring.iter().find(|&&i| free[i] != 0) {
+ return Some(Some(hit));
+ }
+ let next: Vec<usize> = ring
+ .iter()
+ .flat_map(|&i| neighbours(i, w, h).map(|(n, _)| n))
+ .filter(|&n| open[n] != 0 && !std::mem::replace(&mut seen[n], true))
+ .collect();
+ if next.is_empty() {
+ return Some(None);
+ }
+ ring = next;
+ None
+ })?
+}
+
+fn claim(open: &[u8], free: &[u8], inner: &[u8], w: usize, h: usize) -> Vec<u8> {
+ let band = |i: usize| open[i] != 0 && free[i] == 0;
+ let sources: Vec<usize> = (0..h)
+ .into_par_iter()
+ .flat_map_iter(|y| (y * w..(y + 1) * w).filter(|&i| free[i] != 0 && neighbours(i, w, h).any(|(n, _)| band(n))))
+ .collect();
+ let mut dist = vec![u32::MAX; w * h];
+ let mut label = vec![0u8; w * h];
+ let mut buckets: Vec<Vec<usize>> = vec![Vec::new()];
+ sources.iter().for_each(|&i| {
+ dist[i] = 0;
+ label[i] = if inner[i] != 0 { OWN } else { RIVAL };
+ buckets[0].push(i);
+ });
+ let mut d = 0;
+ while d < buckets.len() {
+ let list = std::mem::take(&mut buckets[d]);
+ list.into_iter().for_each(|i| {
+ if dist[i] != d as u32 {
+ return;
+ }
+ neighbours(i, w, h).filter(|&(n, _)| band(n)).for_each(|(n, cost)| {
+ let nd = d as u32 + cost;
+ if nd < dist[n] || (nd == dist[n] && label[i] == OWN && label[n] == RIVAL) {
+ dist[n] = nd;
+ label[n] = label[i];
+ let at = nd as usize;
+ if buckets.len() <= at {
+ buckets.resize_with(at + 1, Vec::new);
+ }
+ buckets[at].push(n);
+ }
+ });
+ });
+ d += 1;
+ }
+ (0..w * h)
+ .into_par_iter()
+ .map(|i| (inner[i] != 0 || (band(i) && label[i] == OWN)) as u8)
+ .collect()
+}
+
+fn and(a: &[u8], b: impl Fn(usize) -> bool + Sync) -> Vec<u8> {
+ a.par_iter().enumerate().map(|(i, &v)| (v != 0 && b(i)) as u8).collect()
+}
+
+pub fn flood(reference: &Raster, seed: &Seed) -> Coverage {
+ let (w, h) = (reference.width as usize, reference.height as usize);
+ if seed.x < 0.0 || seed.y < 0.0 || seed.x >= w as f32 || seed.y >= h as f32 {
+ return Coverage::default();
+ }
+ let (sx, sy) = (seed.x as usize, seed.y as usize);
+ let accept = Accept::around(pixel(reference, sx, sy), seed.tolerance.clamp(0.0, 1.0));
+ let lines = barrier(reference, &accept);
+ let open: Vec<u8> = lines.par_iter().map(|&b| (b == 0) as u8).collect();
+ let radius = (seed.gap.max(0.0) + 1.0) / 2.0;
+ let region = if seed.gap > 0.0 {
+ let distance = distance_sq(&lines, w, h, (radius + 2.0).floor() as usize);
+ let (near, far) = (
+ (radius * radius).floor() as u32,
+ ((radius + 2.0) * (radius + 2.0)).floor() as u32,
+ );
+ let free: Vec<u8> = distance.par_iter().map(|&d| (d > near) as u8).collect();
+ let deep: Vec<u8> = distance.par_iter().map(|&d| (d <= far) as u8).collect();
+ match nearest_free(&open, &free, w, h, sy * w + sx, (radius * 2.0).ceil() as usize + 2) {
+ Some(start) => {
+ let inner = flood_region(&free, w, h, start % w, start / w);
+ let real = real_regions(&free, &inner, &deep, w, h);
+ claim(&open, &real, &inner, w, h)
+ }
+ None => flood_region(&open, w, h, sx, sy),
+ }
+ } else {
+ flood_region(&open, w, h, sx, sy)
+ };
+ let grown = if seed.expand > 0.0 {
+ let wide = dilate(&region, w, h, seed.expand);
+ and(&wide, |i| region[i] != 0 || lines[i] != 0)
+ } else {
+ region
+ };
+ let alpha: Vec<u8> = grown.par_iter().map(|&v| v * 255).collect();
+ Coverage::from_mask(reference.width, reference.height, &alpha)
+}
+
+pub fn polygon(points: &[[f32; 2]], width: u32, height: u32) -> Coverage {
+ let (w, h) = (width as usize, height as usize);
+ if points.len() < 3 || w == 0 || h == 0 {
+ return Coverage::default();
+ }
+ let (y_lo, y_hi) = points
+ .iter()
+ .fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p[1]), hi.max(p[1])));
+ let rows = (y_lo.floor().max(0.0) as usize)..(y_hi.ceil().clamp(0.0, h as f32) as usize);
+ let edges: Vec<([f32; 2], [f32; 2])> = points
+ .iter()
+ .zip(points.iter().cycle().skip(1))
+ .map(|(a, b)| (*a, *b))
+ .filter(|(a, b)| a[1] != b[1])
+ .collect();
+ let mut alpha = vec![0u8; w * h];
+ alpha
+ .par_chunks_mut(w)
+ .enumerate()
+ .filter(|(y, _)| rows.contains(y))
+ .for_each(|(y, row)| {
+ let mut counts = vec![0i32; w * SUB + 1];
+ (0..SUB).for_each(|k| {
+ let sy = y as f32 + (k as f32 + 0.5) / SUB as f32;
+ let mut crossings: Vec<(f32, i32)> = edges
+ .iter()
+ .filter_map(|(a, b)| {
+ let (lo, hi) = if a[1] < b[1] { (a, b) } else { (b, a) };
+ (sy >= lo[1] && sy < hi[1]).then(|| {
+ let t = (sy - a[1]) / (b[1] - a[1]);
+ (a[0] + (b[0] - a[0]) * t, if a[1] < b[1] { 1 } else { -1 })
+ })
+ })
+ .collect();
+ crossings.sort_by(|p, q| p.0.total_cmp(&q.0));
+ let mut winding = 0;
+ crossings.windows(2).for_each(|pair| {
+ winding += pair[0].1;
+ if winding != 0 {
+ let sub = |x: f32| ((x * SUB as f32 - 0.5).ceil().clamp(0.0, (w * SUB) as f32)) as usize;
+ let (from, to) = (sub(pair[0].0), sub(pair[1].0));
+ if from < to {
+ counts[from] += 1;
+ counts[to] -= 1;
+ }
+ }
+ });
+ });
+ let mut running = 0;
+ let per_sub: Vec<i32> = counts[..w * SUB]
+ .iter()
+ .map(|c| {
+ running += c;
+ running
+ })
+ .collect();
+ row.iter_mut().enumerate().for_each(|(x, a)| {
+ let hits: i32 = per_sub[x * SUB..(x + 1) * SUB].iter().sum();
+ *a = ((hits * 255 + (SUB * SUB) as i32 / 2) / (SUB * SUB) as i32) as u8;
+ });
+ });
+ Coverage::from_mask(width, height, &alpha)
+}
+
+pub fn fill_tiles(raster: &Raster, fill: &Fill) -> Vec<usize> {
+ let c = &fill.coverage;
+ let (w, h) = (raster.width as usize, raster.height as usize);
+ let (x0, y0) = (c.x as usize, c.y as usize);
+ let (x1, y1) = ((x0 + c.width as usize).min(w), (y0 + c.height as usize).min(h));
+ if c.is_empty() || x0 >= x1 || y0 >= y1 {
+ return Vec::new();
+ }
+ let mut seen = vec![false; raster.cols * raster.rows];
+ (y0..y1).for_each(|y| {
+ (x0..x1)
+ .filter(|&x| c.at(x as u32, y as u32) > 0)
+ .for_each(|x| seen[(y / TILE) * raster.cols + x / TILE] = true);
+ });
+ (y0 / TILE..=(y1 - 1) / TILE)
+ .flat_map(|ty| (x0 / TILE..=(x1 - 1) / TILE).map(move |tx| (tx, ty)))
+ .map(|(tx, ty)| raster.index(tx, ty))
+ .filter(|&i| seen[i])
+ .collect()
+}
+
+pub fn paint_fill(raster: &mut Raster, fill: &Fill) -> Vec<usize> {
+ paint_fill_where(raster, fill, |_| true)
+}
+
+pub fn paint_fill_where(raster: &mut Raster, fill: &Fill, allowed: impl Fn(usize) -> bool) -> Vec<usize> {
+ let c = &fill.coverage;
+ if c.is_empty() {
+ return Vec::new();
+ }
+ let (w, h) = (raster.width as usize, raster.height as usize);
+ let (x0, y0) = (c.x as usize, c.y as usize);
+ let (x1, y1) = ((x0 + c.width as usize).min(w), (y0 + c.height as usize).min(h));
+ if x0 >= x1 || y0 >= y1 {
+ return Vec::new();
+ }
+ let color = fill.color();
+ let tiles: Vec<usize> = (y0 / TILE..=(y1 - 1) / TILE)
+ .flat_map(|ty| (x0 / TILE..=(x1 - 1) / TILE).map(move |tx| (tx, ty)))
+ .map(|(tx, ty)| raster.index(tx, ty))
+ .collect();
+ tiles
+ .into_iter()
+ .filter(|&index| {
+ if !allowed(index) {
+ return false;
+ }
+ let (tx, ty) = (index % raster.cols, index / raster.cols);
+ let (ox, oy) = (tx * TILE, ty * TILE);
+ let mut buffer = vec![0.0f32; TILE_PX];
+ let mut any = false;
+ (y0.max(oy)..y1.min(oy + TILE)).for_each(|y| {
+ (x0.max(ox)..x1.min(ox + TILE)).for_each(|x| {
+ let a = c.at(x as u32, y as u32);
+ if a > 0 {
+ buffer[(y - oy) * TILE + x - ox] = a as f32 / 255.0;
+ any = true;
+ }
+ });
+ });
+ let mut paint = any;
+ if let Some(factor) = crate::cut::factor(&fill.cuts, (ox, oy)).filter(|_| any) {
+ buffer.iter_mut().zip(&factor).for_each(|(c, k)| *c *= k);
+ paint = buffer.iter().any(|c| *c > 0.0);
+ }
+ if paint {
+ let target = match fill.lock {
+ true => raster.at_mut(index),
+ false => Some(raster.ensure(index)),
+ };
+ let blend = if fill.lock {
+ StrokeBlend::Atop
+ } else {
+ StrokeBlend::Normal
+ };
+ if let Some(target) = target {
+ blend_coverage(target, &buffer, color, fill.opacity, blend);
+ }
+ }
+ any
+ })
+ .collect()
+}
+
+pub fn sample(raster: &Raster, x: f32, y: f32) -> [f32; 4] {
+ if x < 0.0 || y < 0.0 || x >= raster.width as f32 || y >= raster.height as f32 {
+ return [0.0; 4];
+ }
+ pixel(raster, x as usize, y as usize).map(f16::to_f32)
+}
+
+pub fn accepts(raster: &Raster, x: f32, y: f32, colour: [f32; 4], tolerance: f32) -> bool {
+ let px = sample(raster, x, y);
+ let accept = Accept::around(colour.map(f16::from_f32), tolerance.clamp(0.0, 1.0));
+ accept.takes(&px.map(f16::from_f32))
+}
+
+pub fn nearest_accepted(
+ raster: &Raster,
+ at: [f32; 2],
+ colour: [f32; 4],
+ tolerance: f32,
+ radius: u32,
+) -> Option<[f32; 2]> {
+ let (cx, cy) = (at[0].floor() as i64, at[1].floor() as i64);
+ let r = radius as i64;
+ (-r..=r)
+ .flat_map(|dy| (-r..=r).map(move |dx| (dx, dy)))
+ .filter(|(dx, dy)| dx * dx + dy * dy <= r * r)
+ .map(|(dx, dy)| (cx + dx, cy + dy, dx * dx + dy * dy))
+ .filter(|(x, y, _)| *x >= 0 && *y >= 0 && *x < raster.width as i64 && *y < raster.height as i64)
+ .filter(|(x, y, _)| accepts(raster, *x as f32 + 0.5, *y as f32 + 0.5, colour, tolerance))
+ .min_by_key(|(x, y, d)| (*d, *y, *x))
+ .map(|(x, y, _)| [x as f32 + 0.5, y as f32 + 0.5])
+}
+
+pub struct Regions {
+ pub width: usize,
+ pub height: usize,
+ pub labels: Vec<u32>,
+ pub sizes: Vec<usize>,
+ pub border: Vec<bool>,
+ pub bounds: Vec<[u32; 4]>,
+ pub centres: Vec<[f32; 2]>,
+}
+
+impl Regions {
+ pub fn count(&self) -> usize {
+ self.sizes.len()
+ }
+
+ pub fn at(&self, x: usize, y: usize) -> u32 {
+ if x >= self.width || y >= self.height {
+ return 0;
+ }
+ self.labels[y * self.width + x]
+ }
+}
+
+pub fn regions(reference: &Raster, colour: [f32; 4], tolerance: f32, gap: f32, margin: f32) -> Regions {
+ let (w, h) = (reference.width as usize, reference.height as usize);
+ let accept = Accept::around(colour.map(f16::from_f32), tolerance.clamp(0.0, 1.0));
+ let lines = barrier(reference, &accept);
+ let radius = if gap > 0.0 {
+ (gap + 1.0) / 2.0 + margin
+ } else {
+ margin.max(0.5)
+ };
+ let distance = distance_sq(&lines, w, h, radius.ceil() as usize + 1);
+ let limit = (radius * radius).floor() as u32;
+ let core: Vec<bool> = distance.par_iter().map(|&d| d > limit).collect();
+ let mut labels = vec![0u32; w * h];
+ let (mut sizes, mut border, mut bounds, mut centres) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ let mut stack = Vec::new();
+ (0..w * h).for_each(|start| {
+ if !core[start] || labels[start] != 0 {
+ return;
+ }
+ let label = sizes.len() as u32 + 1;
+ let (mut size, mut edge) = (0usize, false);
+ let mut b = [u32::MAX, u32::MAX, 0, 0];
+ let (mut sx, mut sy) = (0u64, 0u64);
+ labels[start] = label;
+ stack.push(start);
+ while let Some(i) = stack.pop() {
+ let (x, y) = (i % w, i / w);
+ size += 1;
+ sx += x as u64;
+ sy += y as u64;
+ edge |= x == 0 || y == 0 || x + 1 == w || y + 1 == h;
+ b = [
+ b[0].min(x as u32),
+ b[1].min(y as u32),
+ b[2].max(x as u32 + 1),
+ b[3].max(y as u32 + 1),
+ ];
+ [
+ (x > 0).then(|| i - 1),
+ (x + 1 < w).then(|| i + 1),
+ (y > 0).then(|| i - w),
+ (y + 1 < h).then(|| i + w),
+ ]
+ .into_iter()
+ .flatten()
+ .for_each(|n| {
+ if core[n] && labels[n] == 0 {
+ labels[n] = label;
+ stack.push(n);
+ }
+ });
+ }
+ sizes.push(size);
+ border.push(edge);
+ bounds.push(b);
+ centres.push([sx as f32 / size as f32 + 0.5, sy as f32 / size as f32 + 0.5]);
+ });
+ Regions {
+ width: w,
+ height: h,
+ labels,
+ sizes,
+ border,
+ bounds,
+ centres,
+ }
+}
+
+pub fn carry_seed(reference: &Raster, colour: [f32; 4], seed: &Seed, old: &Coverage) -> Option<[f32; 2]> {
+ let found = regions(reference, colour, seed.tolerance, seed.gap, 0.0);
+ let pixels: Vec<(u32, u32)> = (0..old.height)
+ .flat_map(|row| (0..old.width).map(move |col| (col, row)))
+ .filter(|&(col, row)| old.alpha[(row * old.width + col) as usize] > 0)
+ .map(|(col, row)| (old.x + col, old.y + row))
+ .collect();
+ if pixels.is_empty() {
+ return None;
+ }
+ let n = pixels.len() as f32;
+ let centre = pixels.iter().fold([0.0f32, 0.0], |[x, y], &(px, py)| {
+ [x + (px as f32 + 0.5) / n, y + (py as f32 + 0.5) / n]
+ });
+ let outside = old.x == 0
+ || old.y == 0
+ || (old.x + old.width) as usize >= found.width
+ || (old.y + old.height) as usize >= found.height;
+ let reach = (0.75 * n.sqrt()).max(24.0);
+ let score = |l: usize| -> Option<(f32, (i64, i64))> {
+ if found.border[l] && !outside {
+ return None;
+ }
+ let [cx, cy] = found.centres[l];
+ let distance = ((cx - centre[0]).powi(2) + (cy - centre[1]).powi(2)).sqrt();
+ if distance > reach * 3.0 {
+ return None;
+ }
+ let shift = ((cx - centre[0]).round() as i64, (cy - centre[1]).round() as i64);
+ let label = l as u32 + 1;
+ let inside = pixels
+ .iter()
+ .filter(|&&(x, y)| {
+ let (sx, sy) = (x as i64 + shift.0, y as i64 + shift.1);
+ sx >= 0 && sy >= 0 && found.at(sx as usize, sy as usize) == label
+ })
+ .count() as f32;
+ let union = n + found.sizes[l] as f32 - inside;
+ Some((inside / union.max(1.0) * libm::expf(-distance / reach), shift))
+ };
+ let (best, (_, shift)) = (0..found.count())
+ .filter_map(|l| score(l).map(|s| (l, s)))
+ .filter(|(_, (s, _))| *s > 0.0)
+ .max_by(|a, b| a.1.0.total_cmp(&b.1.0).then(b.0.cmp(&a.0)))?;
+ let [bx0, by0, bx1, by1] = found.bounds[best];
+ let label = best as u32 + 1;
+ let target = (seed.x + shift.0 as f32, seed.y + shift.1 as f32);
+ (by0..by1)
+ .flat_map(|y| (bx0..bx1).map(move |x| (x, y)))
+ .filter(|&(x, y)| found.at(x as usize, y as usize) == label)
+ .map(|(x, y)| {
+ let (dx, dy) = (x as f32 + 0.5 - target.0, y as f32 + 0.5 - target.1);
+ ((dx * dx + dy * dy) as u64, y, x)
+ })
+ .min()
+ .map(|(_, y, x)| [x as f32 + 0.5, y as f32 + 0.5])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{BrushSet, replay};
+ use klad_core::fill::{FillRef, FillSource};
+ use klad_core::stroke::{Mark, Stroke};
+ use std::time::Instant;
+
+ fn rings(eye: (f32, f32)) -> Raster {
+ let circle = |cx: f32, cy: f32, r: f32| -> Vec<(f32, f32, f32)> {
+ (0..=180)
+ .map(|i| {
+ let t = i as f32 / 180.0 * std::f32::consts::TAU;
+ (cx + r * libm::cosf(t), cy + r * libm::sinf(t), 1.0)
+ })
+ .collect()
+ };
+ let marks: Vec<Mark> = [circle(100.0, 100.0, 70.0), circle(eye.0, eye.1, 9.0)]
+ .iter()
+ .enumerate()
+ .map(|(i, pts)| {
+ Stroke::new(i as u32 + 1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1)
+ .with_points(pts, 4.0)
+ .into()
+ })
+ .collect();
+ replay(200, 200, &marks, &BrushSet::presets()).unwrap().raster
+ }
+
+ #[test]
+ fn regions_and_carried_seeds_follow_a_small_shape_past_its_own_size() {
+ let before = rings((80.0, 90.0));
+ let seed = Seed {
+ x: 80.0,
+ y: 90.0,
+ tolerance: 0.1,
+ gap: 2.0,
+ expand: 2.0,
+ };
+ let eye = flood(&before, &seed);
+ assert!((100..400).contains(&eye.pixels()), "{}", eye.pixels());
+ let found = regions(&before, [0.0; 4], 0.1, 2.0, 0.0);
+ assert_eq!(found.border.iter().filter(|b| **b).count(), 1);
+ assert!(found.count() >= 3);
+ let after = rings((86.0, 112.0));
+ let [x, y] = carry_seed(&after, [0.0; 4], &seed, &eye).unwrap();
+ assert!((x - 86.0).abs() < 6.0 && (y - 112.0).abs() < 6.0, "{x},{y}");
+ let moved = flood(&after, &Seed { x, y, ..seed });
+ assert!(
+ (moved.pixels() as i64 - eye.pixels() as i64).abs() < 40,
+ "{} vs {}",
+ moved.pixels(),
+ eye.pixels()
+ );
+ }
+
+ fn ink_ring(size: u32, gaps: &[(f32, f32)]) -> Raster {
+ let (cx, cy, r) = (size as f32 / 2.0, size as f32 / 2.0, size as f32 * 0.35);
+ let n = 720;
+ let points: Vec<(f32, f32, f32)> = (0..=n)
+ .map(|i| {
+ let t = i as f32 / n as f32 * std::f32::consts::TAU;
+ (cx + r * libm::cosf(t), cy + r * libm::sinf(t), 1.0)
+ })
+ .collect();
+ let arcs: Vec<Vec<(f32, f32, f32)>> = if gaps.is_empty() {
+ vec![points]
+ } else {
+ let mut cuts: Vec<(usize, usize)> = gaps
+ .iter()
+ .map(|&(at, width)| {
+ let mid = (at / 360.0 * n as f32) as usize;
+ let half = ((width + 4.0) / 2.0 / (r * std::f32::consts::TAU) * n as f32).round() as usize;
+ (mid - half, mid + half)
+ })
+ .collect();
+ cuts.sort();
+ let mut arcs = Vec::new();
+ let mut from = 0;
+ cuts.iter().for_each(|&(a, b)| {
+ arcs.push(points[from..=a].to_vec());
+ from = b;
+ });
+ arcs.push(points[from..].to_vec());
+ arcs
+ };
+ let marks: Vec<Mark> = arcs
+ .iter()
+ .enumerate()
+ .map(|(i, arc)| {
+ Mark::Stroke(Stroke::new(i as u32 + 1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 3).with_points(arc, 4.0))
+ })
+ .collect();
+ replay(size, size, &marks, &BrushSet::presets()).unwrap().raster
+ }
+
+ fn seed(x: f32, y: f32, gap: f32) -> Seed {
+ Seed {
+ x,
+ y,
+ tolerance: 0.1,
+ gap,
+ expand: 2.0,
+ }
+ }
+
+ #[test]
+ fn a_closed_ring_fills_inside_and_tucks_under_the_line() {
+ let lines = ink_ring(256, &[]);
+ let c = flood(&lines, &seed(128.0, 128.0, 0.0));
+ let r = 256.0 * 0.35;
+ assert_eq!(c.at(128, 128), 255);
+ assert_eq!(c.at(128 + r as u32 - 3, 128), 255);
+ assert_eq!(c.at(128 + r as u32 + 4, 128), 0);
+ assert_eq!(c.at(5, 5), 0);
+ let [x0, _, x1, _] = c.bounds().unwrap();
+ assert!((x1 - x0) > 2.0 * r - 4.0 && (x1 - x0) < 2.0 * r + 4.0, "{x0} {x1}");
+ let outside = flood(&lines, &seed(5.0, 5.0, 0.0));
+ assert_eq!((outside.at(5, 5), outside.at(128, 128)), (255, 0));
+ }
+
+ fn ink(r: &mut Raster, x: usize, y: usize) {
+ let at = ((y % TILE) * TILE + x % TILE) * 4;
+ let index = r.index(x / TILE, y / TILE);
+ r.ensure(index)[at..at + 4].copy_from_slice(&[f16::ZERO, f16::ZERO, f16::ZERO, f16::ONE]);
+ }
+
+ fn open_box(gaps: [usize; 3]) -> Raster {
+ let mut lines = Raster::new(256, 256);
+ (40..216).for_each(|i| {
+ (0..3).for_each(|t| {
+ let gap = |edge: usize| (128..128 + gaps[edge]).contains(&i);
+ [
+ (!gap(0)).then_some((i, 40 + t)),
+ (!gap(1)).then_some((213 + t, i)),
+ (!gap(2)).then_some((40 + t, i)),
+ Some((i, 213 + t)),
+ ]
+ .into_iter()
+ .flatten()
+ .for_each(|(x, y)| ink(&mut lines, x, y));
+ })
+ });
+ lines
+ }
+
+ #[test]
+ fn gaps_up_to_the_gap_width_do_not_leak() {
+ let lines = open_box([6, 4, 1]);
+ let leaky = flood(&lines, &seed(128.0, 128.0, 0.0));
+ assert_eq!(leaky.at(3, 3), 255, "without gap closing the fill leaks");
+ let c = flood(&lines, &seed(128.0, 128.0, 6.0));
+ assert_eq!((c.at(128, 128), c.at(43, 43), c.at(212, 212)), (255, 255, 255));
+ assert_eq!((c.at(3, 3), c.at(250, 128), c.at(128, 30)), (0, 0, 0));
+ let [x0, y0, x1, y1] = c.bounds().unwrap();
+ assert!(
+ x0 >= 36.0 && y0 >= 36.0 && x1 <= 220.0 && y1 <= 220.0,
+ "{:?}",
+ c.bounds()
+ );
+ let narrow = flood(&lines, &seed(128.0, 128.0, 4.0));
+ assert_eq!(narrow.at(3, 3), 255, "a 6 px gap is wider than gap 4");
+ let inked = ink_ring(256, &[(10.0, 5.0), (130.0, 3.0), (250.0, 1.0)]);
+ assert_eq!(flood(&inked, &seed(128.0, 128.0, 0.0)).at(3, 3), 255);
+ let ring = flood(&inked, &seed(128.0, 128.0, 6.0));
+ let r = 256.0 * 0.35;
+ assert_eq!((ring.at(128, 128), ring.at(3, 3), ring.at(250, 128)), (255, 0, 0));
+ assert_eq!(ring.at(128 - (r as u32 - 5), 128), 255);
+ let [x0, y0, x1, y1] = ring.bounds().unwrap();
+ let reach = r + 10.0;
+ assert!(
+ x0 > 128.0 - reach && y0 > 128.0 - reach && x1 < 128.0 + reach && y1 < 128.0 + reach,
+ "{:?}",
+ ring.bounds()
+ );
+ }
+
+ #[test]
+ fn corners_fill_right_up_to_the_lines_with_gap_closing() {
+ let mut lines = Raster::new(128, 128);
+ (20..100).for_each(|i| {
+ [(i, 20), (i, 99), (20, i), (99, i)]
+ .iter()
+ .for_each(|&(x, y)| ink(&mut lines, x, y));
+ });
+ let c = flood(&lines, &seed(60.0, 60.0, 8.0));
+ assert_eq!(c.at(21, 21), 255);
+ assert_eq!(c.at(98, 98), 255);
+ assert_eq!(c.at(20, 20), 255);
+ assert_eq!(c.at(10, 10), 0);
+ }
+
+ #[test]
+ fn two_fills_meet_on_a_straight_line_across_a_gap() {
+ let lines = open_box([12, 0, 0]);
+ let inside = flood(&lines, &seed(128.0, 128.0, 12.0));
+ let outside = flood(&lines, &seed(3.0, 3.0, 12.0));
+ assert_eq!((inside.at(3, 3), outside.at(128, 128)), (0, 0));
+ (128..140).for_each(|x| {
+ let column: Vec<(u8, u8)> = (34..50).map(|y| (inside.at(x, y), outside.at(x, y))).collect();
+ assert!(
+ column.iter().all(|(a, b)| *a > 0 || *b > 0),
+ "hole at x {x}: {column:?}"
+ );
+ let first_inside = column.iter().position(|(a, _)| *a > 0).unwrap();
+ let last_outside = column.iter().rposition(|(_, b)| *b > 0).unwrap();
+ assert!(last_outside <= first_inside + 1, "x {x}: {column:?}");
+ assert!(
+ (40..=44).contains(&(34 + first_inside)),
+ "x {x}: inside starts at {}",
+ 34 + first_inside
+ );
+ });
+ }
+
+ #[test]
+ fn sharp_points_fill_to_the_tip_and_clicks_near_a_line_still_close_gaps() {
+ let mut lines = Raster::new(256, 256);
+ let segment = |r: &mut Raster, a: (f32, f32), b: (f32, f32)| {
+ (0..=400).for_each(|k| {
+ let t = k as f32 / 400.0;
+ let (x, y) = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
+ (0..3).for_each(|d| ink(r, x as usize + d, y as usize));
+ })
+ };
+ segment(&mut lines, (40.0, 200.0), (128.0, 30.0));
+ segment(&mut lines, (128.0, 30.0), (216.0, 200.0));
+ segment(&mut lines, (40.0, 200.0), (120.0, 200.0));
+ segment(&mut lines, (128.0, 200.0), (216.0, 200.0));
+ let c = flood(&lines, &seed(128.0, 150.0, 10.0));
+ assert_eq!(c.at(3, 3), 0, "the 5 px gap at the bottom is closed");
+ assert_eq!(c.at(129, 44), 255, "the sharp top fills to near its tip");
+ let near = flood(&lines, &seed(128.0, 195.0, 10.0));
+ assert_eq!(near.at(3, 3), 0, "a click a few px from a line does not leak");
+ assert_eq!(near.at(128, 100), 255);
+ }
+
+ #[test]
+ fn dilation_is_a_round_disk() {
+ let (w, h) = (21, 21);
+ let mut mask = vec![0u8; w * h];
+ mask[10 * w + 10] = 1;
+ let disk = dilate(&mask, w, h, 5.0);
+ assert_eq!(disk.iter().filter(|&&v| v == 1).count(), 81);
+ assert_eq!(
+ (
+ disk[10 * w + 15],
+ disk[10 * w + 16],
+ disk[14 * w + 13],
+ disk[14 * w + 14]
+ ),
+ (1, 0, 1, 0)
+ );
+ }
+
+ #[test]
+ fn polygons_cover_their_area_with_soft_edges() {
+ let c = polygon(&[[10.0, 10.0], [50.0, 10.0], [50.0, 30.0], [10.0, 30.0]], 64, 64);
+ assert_eq!((c.x, c.y, c.width, c.height), (10, 10, 40, 20));
+ assert_eq!(c.pixels(), 800);
+ let half = polygon(&[[10.5, 10.0], [50.0, 10.0], [50.0, 30.0], [10.5, 30.0]], 64, 64);
+ assert_eq!(half.at(10, 20), 128);
+ let tri = polygon(&[[0.0, 0.0], [40.0, 0.0], [0.0, 40.0]], 64, 64);
+ let area: f32 = tri.alpha.iter().map(|&a| a as f32 / 255.0).sum();
+ assert!((area - 800.0).abs() < 8.0, "{area}");
+ let bow = polygon(&[[0.0, 0.0], [20.0, 20.0], [20.0, 0.0], [0.0, 20.0]], 32, 32);
+ assert!(bow.at(3, 10) > 200 && bow.at(10, 3) == 0);
+ }
+
+ #[test]
+ fn fills_replay_between_strokes_in_order() {
+ let brushes = BrushSet::presets();
+ let line = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 10.0, 1)
+ .with_points(&[(10.0, 32.0, 1.0), (120.0, 32.0, 1.0)], 5.0);
+ let mut mask = vec![0u8; 128 * 64];
+ mask.iter_mut().for_each(|a| *a = 255);
+ let fill = Fill::new(
+ 2,
+ [1.0, 0.0, 0.0, 1.0],
+ FillSource::Seed {
+ seed: seed(1.0, 1.0, 0.0),
+ reference: FillRef::This,
+ },
+ Coverage::from_mask(128, 64, &mask),
+ );
+ let after = replay(
+ 128,
+ 64,
+ &[Mark::Stroke(line.clone()), Mark::Fill(fill.clone())],
+ &brushes,
+ )
+ .unwrap();
+ let before = replay(128, 64, &[Mark::Fill(fill), Mark::Stroke(line)], &brushes).unwrap();
+ let red = |r: &Raster| pixel(r, 60, 32)[0].to_f32();
+ assert_eq!(red(&after.raster), 1.0);
+ assert_eq!(red(&before.raster), 0.0);
+ assert_eq!(pixel(&before.raster, 60, 5)[3].to_f32(), 1.0);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-brush fill_timing -- --ignored --nocapture"]
+ fn fill_timing() {
+ let lines = ink_ring(2048, &[(45.0, 6.0), (135.0, 3.0)]);
+ [0.0, 4.0, 8.0].iter().for_each(|&gap| {
+ let start = Instant::now();
+ let c = flood(&lines, &seed(1024.0, 1024.0, gap));
+ println!(
+ "2048 fill, gap {gap}: {:.0} ms, {} px",
+ start.elapsed().as_secs_f64() * 1000.0,
+ c.pixels()
+ );
+ });
+ }
+}
diff --git a/crates/brush/src/grain.rs b/crates/brush/src/grain.rs
new file mode 100644
index 0000000..915bf2f
--- /dev/null
+++ b/crates/brush/src/grain.rs
@@ -0,0 +1,81 @@
+use klad_core::rng::hash2_unit;
+
+pub const GRAIN_SIZE: usize = 512;
+
+#[derive(Clone, Debug)]
+pub struct Grain {
+ width: usize,
+ height: usize,
+ data: Vec<f32>,
+}
+
+fn smooth(t: f32) -> f32 {
+ t * t * (3.0 - 2.0 * t)
+}
+
+fn value_noise(x: usize, y: usize, period: usize, seed: u32) -> f32 {
+ let cell = GRAIN_SIZE / period;
+ let (gx, gy) = (x / cell, y / cell);
+ let (fx, fy) = (
+ smooth((x % cell) as f32 / cell as f32),
+ smooth((y % cell) as f32 / cell as f32),
+ );
+ let corner = |i: usize, j: usize| hash2_unit((i % period) as i32, (j % period) as i32, seed);
+ let top = corner(gx, gy) + (corner(gx + 1, gy) - corner(gx, gy)) * fx;
+ let bottom = corner(gx, gy + 1) + (corner(gx + 1, gy + 1) - corner(gx, gy + 1)) * fx;
+ top + (bottom - top) * fy
+}
+
+impl Grain {
+ pub fn paper(seed: u32, feature: usize) -> Self {
+ let octaves: Vec<(usize, f32)> = [8usize, 4, 2, 1]
+ .iter()
+ .zip([0.5f32, 0.25, 0.15, 0.1])
+ .map(|(m, a)| (GRAIN_SIZE / (feature * m).clamp(1, GRAIN_SIZE), a))
+ .collect();
+ let raw: Vec<f32> = (0..GRAIN_SIZE * GRAIN_SIZE)
+ .map(|i| {
+ let (x, y) = (i % GRAIN_SIZE, i / GRAIN_SIZE);
+ octaves
+ .iter()
+ .enumerate()
+ .map(|(k, &(period, amp))| value_noise(x, y, period, seed + k as u32) * amp)
+ .sum()
+ })
+ .collect();
+ let (lo, hi) = raw
+ .iter()
+ .fold((f32::MAX, f32::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));
+ Self {
+ width: GRAIN_SIZE,
+ height: GRAIN_SIZE,
+ data: raw.iter().map(|v| (v - lo) / (hi - lo)).collect(),
+ }
+ }
+
+ pub fn from_picture(picture: &crate::images::Picture) -> Self {
+ Self {
+ width: picture.width.max(1),
+ height: picture.height.max(1),
+ data: picture.data.clone(),
+ }
+ }
+
+ pub fn at(&self, x: usize, y: usize) -> f32 {
+ self.data[(y % self.height) * self.width + (x % self.width)]
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn grain_is_normalised_and_tiles() {
+ let grain = Grain::paper(5, 4);
+ assert!(grain.data.iter().all(|v| (0.0..=1.0).contains(v)));
+ assert_eq!(grain.at(3, 7), grain.at(3 + GRAIN_SIZE, 7 + GRAIN_SIZE));
+ let edge = (grain.at(GRAIN_SIZE - 1, 10) - grain.at(0, 10)).abs();
+ assert!(edge < 0.2);
+ }
+}
diff --git a/crates/brush/src/images.rs b/crates/brush/src/images.rs
new file mode 100644
index 0000000..889a46d
--- /dev/null
+++ b/crates/brush/src/images.rs
@@ -0,0 +1,260 @@
+use crate::brush::{TipMask, smoothstep};
+use anyhow::{Result, bail};
+use klad_core::bundle::Bundle;
+use klad_core::rng::{FNV_OFFSET, fnv, hash2_unit};
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+pub const TIP_SIZE: usize = 256;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Picture {
+ pub width: usize,
+ pub height: usize,
+ pub data: Vec<f32>,
+ pub hash: u64,
+}
+
+pub type Pictures = BTreeMap<String, Arc<Picture>>;
+
+pub fn decode(bytes: &[u8]) -> Result<Picture> {
+ let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
+ decoder.set_transformations(png::Transformations::normalize_to_color8());
+ let mut reader = decoder.read_info()?;
+ let Some(size) = reader.output_buffer_size() else {
+ bail!("the picture is too big");
+ };
+ let mut buf = vec![0u8; size];
+ let info = reader.next_frame(&mut buf)?;
+ let (width, height) = (info.width as usize, info.height as usize);
+ let channels = info.color_type.samples();
+ let pixels: Vec<&[u8]> = buf[..width * height * channels].chunks_exact(channels).collect();
+ let alpha = |px: &[u8]| -> Option<u8> {
+ match channels {
+ 2 => Some(px[1]),
+ 4 => Some(px[3]),
+ _ => None,
+ }
+ };
+ let see_through = pixels.iter().any(|px| alpha(px).is_some_and(|a| a < 255));
+ let luminance = |px: &[u8]| -> f32 {
+ match channels {
+ 1 | 2 => px[0] as f32 / 255.0,
+ _ => (0.2126 * px[0] as f32 + 0.7152 * px[1] as f32 + 0.0722 * px[2] as f32) / 255.0,
+ }
+ };
+ let data = pixels
+ .iter()
+ .map(|px| match see_through {
+ true => alpha(px).unwrap_or(255) as f32 / 255.0,
+ false => 1.0 - luminance(px),
+ })
+ .collect();
+ Ok(Picture {
+ width,
+ height,
+ data,
+ hash: fnv(FNV_OFFSET, bytes),
+ })
+}
+
+pub fn load(bundle: &Bundle) -> Result<Pictures> {
+ let dir = bundle.root.join("brushes").join("images");
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ return Ok(Pictures::new());
+ };
+ let mut files: Vec<std::path::PathBuf> = entries
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|e| e == "png"))
+ .collect();
+ files.sort();
+ files
+ .into_iter()
+ .map(|path| {
+ let name = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or_default()
+ .to_string();
+ let picture = decode(&std::fs::read(&path)?).map_err(|e| anyhow::anyhow!("{}: {e:#}", path.display()))?;
+ Ok((name, Arc::new(picture)))
+ })
+ .collect()
+}
+
+pub fn tip_from(picture: &Picture) -> TipMask {
+ let side = picture.width.max(picture.height) as f32;
+ let (ox, oy) = (
+ (side - picture.width as f32) / 2.0,
+ (side - picture.height as f32) / 2.0,
+ );
+ let data = (0..TIP_SIZE * TIP_SIZE)
+ .map(|i| {
+ let (x, y) = (i % TIP_SIZE, i / TIP_SIZE);
+ let sx = (x as f32 + 0.5) / TIP_SIZE as f32 * side - ox;
+ let sy = (y as f32 + 0.5) / TIP_SIZE as f32 * side - oy;
+ if sx < 0.0 || sy < 0.0 || sx >= picture.width as f32 || sy >= picture.height as f32 {
+ return 0.0;
+ }
+ picture.data[sy as usize * picture.width + sx as usize]
+ })
+ .collect();
+ TipMask { size: TIP_SIZE, data }
+}
+
+fn disc(u: f32, v: f32, soft: f32) -> f32 {
+ 1.0 - smoothstep(1.0 - soft, 1.0, libm::sqrtf(u * u + v * v))
+}
+
+fn bristles_flat(u: f32, v: f32) -> f32 {
+ let envelope = 1.0 - smoothstep(0.22, 0.45, u.abs());
+ let edge = 1.0 - smoothstep(0.88, 1.0, v.abs());
+ let lines = (0..18).fold(0.0f32, |most, k| {
+ let at = -0.9 + 1.8 * k as f32 / 17.0 + (hash2_unit(k, 1, 31) - 0.5) * 0.06;
+ let width = 0.025 + hash2_unit(k, 2, 31) * 0.035;
+ let strength = 0.55 + hash2_unit(k, 3, 31) * 0.45;
+ let d = (v - at).abs() / width;
+ most.max(strength * (1.0 - smoothstep(0.4, 1.0, d)))
+ });
+ envelope * edge * lines
+}
+
+fn bristles_round(u: f32, v: f32) -> f32 {
+ let body = disc(u, v, 0.25);
+ if body <= 0.0 {
+ return 0.0;
+ }
+ let spots = (0..70).fold(0.0f32, |most, k| {
+ let angle = hash2_unit(k, 1, 47) * std::f32::consts::TAU;
+ let r = libm::sqrtf(hash2_unit(k, 2, 47)) * 0.92;
+ let (cx, cy) = (r * libm::cosf(angle), r * libm::sinf(angle));
+ let size = 0.07 + hash2_unit(k, 3, 47) * 0.08;
+ let d = libm::sqrtf((u - cx) * (u - cx) + (v - cy) * (v - cy)) / size;
+ most.max(1.0 - smoothstep(0.5, 1.0, d))
+ });
+ body * (0.25 + 0.75 * spots)
+}
+
+fn sponge(u: f32, v: f32) -> f32 {
+ let body = disc(u, v, 0.3);
+ if body <= 0.0 {
+ return 0.0;
+ }
+ let cell = |scale: f32, seed: u32| {
+ let (x, y) = ((u + 1.0) * scale, (v + 1.0) * scale);
+ let (gx, gy) = (x.floor(), y.floor());
+ let (fx, fy) = (x - gx, y - gy);
+ let at = |dx: f32, dy: f32| hash2_unit((gx + dx) as i32, (gy + dy) as i32, seed);
+ let top = at(0.0, 0.0) + (at(1.0, 0.0) - at(0.0, 0.0)) * smoothstep(0.0, 1.0, fx);
+ let bottom = at(0.0, 1.0) + (at(1.0, 1.0) - at(0.0, 1.0)) * smoothstep(0.0, 1.0, fx);
+ top + (bottom - top) * smoothstep(0.0, 1.0, fy)
+ };
+ let noise = cell(9.0, 61) * 0.65 + cell(23.0, 62) * 0.35;
+ body * smoothstep(0.38, 0.62, noise)
+}
+
+fn leaf(u: f32, v: f32) -> f32 {
+ if u.abs() >= 1.0 {
+ return 0.0;
+ }
+ let half = 0.42 * libm::powf(1.0 - u * u, 0.8);
+ let body = 1.0 - smoothstep(half * 0.85, half, v.abs());
+ let rib = match u > -0.75 && u < 0.85 {
+ true => 1.0 - 0.6 * (1.0 - smoothstep(0.015, 0.035, v.abs())),
+ false => 1.0,
+ };
+ body * rib
+}
+
+fn grass(u: f32, v: f32) -> f32 {
+ let height = (1.0 - v) / 2.0;
+ (0..5).fold(0.0f32, |most, k| {
+ let foot = -0.6 + 0.3 * k as f32 + (hash2_unit(k, 1, 73) - 0.5) * 0.12;
+ let lean = (hash2_unit(k, 2, 73) - 0.5) * 0.7;
+ let tall = 0.7 + hash2_unit(k, 3, 73) * 0.3;
+ if height > tall {
+ return most;
+ }
+ let centre = foot + lean * height * height;
+ let width = 0.09 * (1.0 - height / tall) + 0.005;
+ most.max(1.0 - smoothstep(0.6, 1.0, (u - centre).abs() / width))
+ })
+}
+
+fn splatter(u: f32, v: f32) -> f32 {
+ (0..16).fold(0.0f32, |most, k| {
+ let angle = hash2_unit(k, 1, 89) * std::f32::consts::TAU;
+ let r = libm::sqrtf(hash2_unit(k, 2, 89)) * 0.85;
+ let (cx, cy) = (r * libm::cosf(angle), r * libm::sinf(angle));
+ let size = 0.03 + libm::powf(hash2_unit(k, 3, 89), 3.0) * 0.2;
+ let d = libm::sqrtf((u - cx) * (u - cx) + (v - cy) * (v - cy)) / size;
+ most.max(1.0 - smoothstep(0.7, 1.0, d))
+ })
+}
+
+pub fn library_tip(name: &str) -> Option<TipMask> {
+ let shape: fn(f32, f32) -> f32 = match name {
+ "bristle-flat" => bristles_flat,
+ "bristle-round" => bristles_round,
+ "sponge" => sponge,
+ "leaf" => leaf,
+ "grass" => grass,
+ "splatter" => splatter,
+ _ => return None,
+ };
+ let data = (0..TIP_SIZE * TIP_SIZE)
+ .map(|i| {
+ let (x, y) = (i % TIP_SIZE, i / TIP_SIZE);
+ let u = (x as f32 + 0.5) / TIP_SIZE as f32 * 2.0 - 1.0;
+ let v = (y as f32 + 0.5) / TIP_SIZE as f32 * 2.0 - 1.0;
+ shape(u, v).clamp(0.0, 1.0)
+ })
+ .collect();
+ Some(TipMask { size: TIP_SIZE, data })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn png(width: u32, height: u32, color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
+ let mut out = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut out, width, height);
+ encoder.set_color(color);
+ encoder.set_depth(png::BitDepth::Eight);
+ let mut writer = encoder.write_header().unwrap();
+ writer.write_image_data(pixels).unwrap();
+ }
+ out
+ }
+
+ #[test]
+ fn library_tips_have_body_and_air() {
+ klad_core::brushes::TIP_IMAGES.iter().for_each(|name| {
+ let tip = library_tip(name).unwrap();
+ let filled = tip.data.iter().filter(|v| **v > 0.5).count();
+ assert!(
+ filled > tip.data.len() / 200 && filled < tip.data.len() * 3 / 4,
+ "{name}: {filled} of {}",
+ tip.data.len()
+ );
+ assert_eq!(
+ tip.sample(0.999, 0.999),
+ library_tip(name).unwrap().sample(0.999, 0.999)
+ );
+ });
+ assert!(library_tip("nope").is_none());
+ }
+
+ #[test]
+ fn pictures_read_dark_as_paint_or_their_alpha() {
+ let grey = png(2, 1, png::ColorType::Grayscale, &[0, 255]);
+ assert_eq!(decode(&grey).unwrap().data, vec![1.0, 0.0]);
+ let alpha = png(2, 1, png::ColorType::Rgba, &[0, 0, 0, 255, 255, 255, 255, 51]);
+ assert_eq!(decode(&alpha).unwrap().data, vec![1.0, 0.2]);
+ let tip = tip_from(&decode(&png(2, 1, png::ColorType::Grayscale, &[0, 255])).unwrap());
+ assert!(tip.sample(-0.6, 0.0) > 0.9 && tip.sample(0.6, 0.0) < 0.1 && tip.sample(0.0, -0.9) == 0.0);
+ }
+}
diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs
new file mode 100644
index 0000000..9a52fc7
--- /dev/null
+++ b/crates/brush/src/lib.rs
@@ -0,0 +1,22 @@
+pub mod brush;
+pub mod cache;
+pub mod cut;
+pub mod engine;
+pub mod fill;
+pub mod grain;
+pub mod images;
+pub mod record;
+pub mod replay;
+pub mod tiles;
+
+pub const ENGINE_VERSION: u32 = 2;
+
+pub use brush::{Brush, BrushSet};
+pub use engine::{
+ StrokePainter, blend_coverage, commit, draw_stroke, draw_stroke_on, land_stroke, land_tile, mode_of, needs_repaint,
+ paint_mark, paint_stroke, replay, replay_onto, stroke_blend,
+};
+pub use fill::{Regions, accepts, carry_seed, flood, nearest_accepted, paint_fill, polygon, regions, sample};
+pub use record::{PressureCurve, Raw, Recorder};
+pub use replay::{CelReplay, Updated};
+pub use tiles::{Mode, Raster, StrokeBuffer, TILE};
diff --git a/crates/brush/src/record.rs b/crates/brush/src/record.rs
new file mode 100644
index 0000000..ff8332a
--- /dev/null
+++ b/crates/brush/src/record.rs
@@ -0,0 +1,185 @@
+use klad_core::stroke::{PRESSURE_STEPS, Sample};
+use serde::{Deserialize, Serialize};
+use std::collections::VecDeque;
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PressureCurve {
+ pub low: f32,
+ pub high: f32,
+ pub gamma: f32,
+}
+
+impl Default for PressureCurve {
+ fn default() -> Self {
+ Self {
+ low: 0.0,
+ high: 1.0,
+ gamma: 1.0,
+ }
+ }
+}
+
+impl PressureCurve {
+ pub fn apply(&self, raw: f32) -> f32 {
+ if raw <= 0.0 {
+ return 0.0;
+ }
+ let span = (self.high - self.low).max(0.01);
+ let t = ((raw - self.low) / span).clamp(0.0, 1.0);
+ libm::powf(t, self.gamma).max(1.0 / PRESSURE_STEPS)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Raw {
+ pub x: f32,
+ pub y: f32,
+ pub pressure: f32,
+ pub tilt: (f32, f32),
+ pub dt_ms: f32,
+}
+
+pub struct Recorder {
+ curve: PressureCurve,
+ window_ms: f32,
+ smoothing_ms: f32,
+ recent: VecDeque<(f32, Raw)>,
+ now: f32,
+ pressure: Option<f32>,
+}
+
+impl Recorder {
+ pub fn new(curve: PressureCurve, window_ms: f32, smoothing_ms: f32) -> Self {
+ Self {
+ curve,
+ window_ms: window_ms.max(0.0),
+ smoothing_ms: smoothing_ms.max(0.0),
+ recent: VecDeque::new(),
+ now: 0.0,
+ pressure: None,
+ }
+ }
+
+ pub fn push(&mut self, raw: Raw) -> Sample {
+ let dt = raw.dt_ms.max(0.0);
+ self.now += dt;
+ let target = self.curve.apply(raw.pressure);
+ let pressure = match self.pressure {
+ Some(prev) if self.smoothing_ms > 0.0 => {
+ prev + (target - prev) * (1.0 - libm::expf(-dt / self.smoothing_ms))
+ }
+ _ => target,
+ };
+ self.pressure = Some(pressure);
+ self.recent.push_back((self.now, raw));
+ while self.recent.len() > 1 && self.recent.front().is_some_and(|(t, _)| self.now - t > self.window_ms) {
+ self.recent.pop_front();
+ }
+ let (x, y) = self.centre();
+ Sample::quantize(x, y, pressure, raw.tilt, dt)
+ }
+
+ fn centre(&self) -> (f32, f32) {
+ let n = self.recent.len().max(1) as f32;
+ let (x, y) = self
+ .recent
+ .iter()
+ .fold((0.0f32, 0.0f32), |(x, y), (_, r)| (x + r.x, y + r.y));
+ (x / n, y / n)
+ }
+
+ pub fn finish(&mut self) -> Vec<Sample> {
+ let pressure = self.pressure.unwrap_or(0.0);
+ let tilt = self.recent.back().map_or((0.0, 0.0), |(_, r)| r.tilt);
+ let mut out = Vec::new();
+ while self.recent.len() > 1 {
+ self.recent.pop_front();
+ let (x, y) = self.centre();
+ out.push(Sample::quantize(x, y, pressure, tilt, 0.0));
+ }
+ out
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn raw(x: f32, y: f32, pressure: f32) -> Raw {
+ Raw {
+ x,
+ y,
+ pressure,
+ tilt: (0.0, 0.0),
+ dt_ms: 4.5,
+ }
+ }
+
+ #[test]
+ fn calibration_reaches_full_pressure_and_keeps_zero_for_no_reading() {
+ let heavy = PressureCurve {
+ low: 0.0,
+ high: 0.88,
+ gamma: 1.0,
+ };
+ assert_eq!(heavy.apply(0.88), 1.0);
+ assert_eq!(heavy.apply(0.95), 1.0);
+ assert!((heavy.apply(0.44) - 0.5).abs() < 1e-6);
+ assert_eq!(heavy.apply(0.0), 0.0);
+ let floor = PressureCurve {
+ low: 0.2,
+ high: 0.8,
+ gamma: 2.0,
+ };
+ let light = Sample::quantize(0.0, 0.0, floor.apply(0.05), (0.0, 0.0), 0.0);
+ assert_eq!(light.pressure, 1);
+ assert!(floor.apply(0.5) < 0.5 * floor.apply(0.8));
+ }
+
+ #[test]
+ fn without_filters_samples_pass_straight_through() {
+ let mut rec = Recorder::new(PressureCurve::default(), 0.0, 0.0);
+ let points = [raw(1.0, 2.0, 0.3), raw(5.5, 2.25, 0.6), raw(9.0, 4.0, 0.2)];
+ let out: Vec<Sample> = points.iter().map(|p| rec.push(*p)).collect();
+ let direct: Vec<Sample> = points
+ .iter()
+ .map(|p| Sample::quantize(p.x, p.y, p.pressure, p.tilt, p.dt_ms))
+ .collect();
+ assert_eq!(out, direct);
+ assert!(rec.finish().is_empty());
+ }
+
+ #[test]
+ fn the_stabiliser_irons_out_wobble_and_catches_up_on_pen_up() {
+ let wobbly: Vec<Raw> = (0..200)
+ .map(|i| raw(i as f32 * 2.0, 100.0 + if i % 2 == 0 { 3.0 } else { -3.0 }, 0.5))
+ .collect();
+ let mut rec = Recorder::new(PressureCurve::default(), 40.0, 0.0);
+ let mut out: Vec<Sample> = wobbly.iter().map(|r| rec.push(*r)).collect();
+ let lagging = out.last().unwrap().pos().0;
+ assert!(lagging < 398.0 - 5.0, "lags behind the pen: {lagging}");
+ out.extend(rec.finish());
+ let wobble = out[20..out.len() - 20]
+ .iter()
+ .map(|s| (s.pos().1 - 100.0).abs())
+ .fold(0.0f32, f32::max);
+ assert!(wobble < 0.6, "wobble {wobble}");
+ let end = out.last().unwrap().pos();
+ assert_eq!(end, (398.0, 97.0));
+ }
+
+ #[test]
+ fn pressure_smoothing_calms_jitter_without_losing_the_level() {
+ let jittery: Vec<Raw> = (0..120)
+ .map(|i| raw(i as f32, 0.0, if i % 2 == 0 { 0.4 } else { 0.6 }))
+ .collect();
+ let mut rec = Recorder::new(PressureCurve::default(), 0.0, 20.0);
+ let out: Vec<f32> = jittery.iter().map(|r| rec.push(*r).pressure()).collect();
+ let tail = &out[60..];
+ let (lo, hi) = tail
+ .iter()
+ .fold((1.0f32, 0.0f32), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ assert!(hi - lo < 0.05, "range {lo}..{hi}");
+ assert!((tail.iter().sum::<f32>() / tail.len() as f32 - 0.5).abs() < 0.02);
+ }
+}
diff --git a/crates/brush/src/replay.rs b/crates/brush/src/replay.rs
new file mode 100644
index 0000000..a8dee4e
--- /dev/null
+++ b/crates/brush/src/replay.rs
@@ -0,0 +1,677 @@
+use crate::brush::{BrushSet, StrokeBlend};
+use crate::engine::{commit, draw_stroke_on, land_stroke};
+use crate::fill::{fill_tiles, paint_fill_where};
+use crate::tiles::{Raster, StrokeBuffer, TILE_PX};
+use anyhow::Result;
+use half::f16;
+use klad_core::stroke::{Mark, Stroke, fingerprint};
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+pub const EVERY: usize = 128;
+pub const BUDGET: usize = 128 << 20;
+
+type Tile = Option<Arc<[f16]>>;
+
+#[derive(Clone)]
+struct Checkpoint {
+ at: usize,
+ tiles: Vec<Tile>,
+}
+
+#[derive(Clone)]
+pub struct CelReplay {
+ width: u32,
+ height: u32,
+ marks: Vec<Mark>,
+ keys: Vec<(u32, u64)>,
+ footprints: Vec<Vec<u32>>,
+ checkpoints: Vec<Checkpoint>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Updated {
+ pub tiles: Vec<usize>,
+ pub replayed: usize,
+ pub full: bool,
+}
+
+fn painted(
+ raster: &mut Raster,
+ buffer: &mut StrokeBuffer,
+ brushes: &BrushSet,
+ mark: &Mark,
+) -> Result<(Vec<usize>, usize)> {
+ Ok(match mark {
+ Mark::Stroke(stroke) => {
+ let brush = brushes.get(&stroke.brush)?;
+ let dabs = draw_stroke_on(buffer, brush, stroke, Some(raster));
+ (land_stroke(raster, buffer, stroke, brush), dabs)
+ }
+ Mark::Fill(fill) => (paint_fill_where(raster, fill, |i| buffer.allowed(i)), 0),
+ })
+}
+
+fn put(raster: &mut Raster, index: usize, tile: &Tile) {
+ match tile {
+ Some(data) => raster.put(index, Box::from(&data[..])),
+ None => raster.clear(index),
+ }
+}
+
+impl CelReplay {
+ pub fn new(width: u32, height: u32) -> Self {
+ let tiles = Raster::new(width, height);
+ Self {
+ width,
+ height,
+ marks: Vec::new(),
+ keys: Vec::new(),
+ footprints: Vec::new(),
+ checkpoints: vec![Checkpoint {
+ at: 0,
+ tiles: vec![None; tiles.cols * tiles.rows],
+ }],
+ }
+ }
+
+ pub fn replay(width: u32, height: u32, marks: Vec<Mark>, brushes: &BrushSet) -> Result<(Self, Raster, usize)> {
+ let mut cel = Self::new(width, height);
+ let mut raster = Raster::new(width, height);
+ let mut buffer = StrokeBuffer::new(width, height);
+ let dabs = marks.into_iter().try_fold(0usize, |dabs, mark| {
+ let (footprint, more) = painted(&mut raster, &mut buffer, brushes, &mark)?;
+ cel.record(&raster, mark, &footprint);
+ Ok::<_, anyhow::Error>(dabs + more)
+ })?;
+ Ok((cel, raster, dabs))
+ }
+
+ pub fn from_cache(width: u32, height: u32, keys: Vec<(u32, u64)>, footprints: Vec<Vec<u32>>) -> Self {
+ Self {
+ keys,
+ footprints,
+ ..Self::new(width, height)
+ }
+ }
+
+ pub fn with_marks(mut self, marks: Vec<Mark>) -> Option<Self> {
+ let same = marks.len() == self.keys.len()
+ && marks
+ .iter()
+ .zip(&self.keys)
+ .all(|(m, k)| (m.id(), fingerprint(m)) == *k)
+ && self.footprints.len() == self.keys.len();
+ same.then(|| {
+ self.marks = marks;
+ self
+ })
+ }
+
+ pub fn marks(&self) -> &[Mark] {
+ &self.marks
+ }
+
+ pub fn keys(&self) -> &[(u32, u64)] {
+ &self.keys
+ }
+
+ pub fn footprints(&self) -> &[Vec<u32>] {
+ &self.footprints
+ }
+
+ pub fn checkpoints(&self) -> Vec<usize> {
+ self.checkpoints.iter().map(|c| c.at).collect()
+ }
+
+ fn record(&mut self, raster: &Raster, mark: Mark, footprint: &[usize]) {
+ self.keys.push((mark.id(), fingerprint(&mark)));
+ self.footprints.push(footprint.iter().map(|&t| t as u32).collect());
+ self.marks.push(mark);
+ self.maybe_checkpoint(raster);
+ }
+
+ fn maybe_checkpoint(&mut self, raster: &Raster) {
+ let Some(last) = self.checkpoints.last() else {
+ return;
+ };
+ if self.keys.len() < last.at + EVERY {
+ return;
+ }
+ let changed: BTreeSet<u32> = self.footprints[last.at..].iter().flatten().copied().collect();
+ let mut tiles = last.tiles.clone();
+ changed
+ .iter()
+ .for_each(|&t| tiles[t as usize] = raster.at(t as usize).map(Arc::from));
+ self.checkpoints.push(Checkpoint {
+ at: self.keys.len(),
+ tiles,
+ });
+ while self.checkpoint_bytes() > BUDGET && self.checkpoints.len() > 2 {
+ let mut n = 0;
+ self.checkpoints.retain(|_| {
+ n += 1;
+ n == 1 || n % 2 == 0
+ });
+ }
+ }
+
+ pub fn drop_checkpoints(&mut self) {
+ self.checkpoints.truncate(1);
+ }
+
+ pub fn checkpoint_bytes(&self) -> usize {
+ let unique: BTreeSet<usize> = self
+ .checkpoints
+ .iter()
+ .flat_map(|c| c.tiles.iter().flatten())
+ .map(|t| Arc::as_ptr(t) as *const f16 as usize)
+ .collect();
+ unique.len() * TILE_PX * 4 * std::mem::size_of::<f16>()
+ }
+
+ pub fn commit_stroke(
+ &mut self,
+ raster: &mut Raster,
+ stroke: Stroke,
+ buffer: &mut StrokeBuffer,
+ blend: StrokeBlend,
+ ) -> Vec<usize> {
+ let touched = commit(raster, buffer, stroke.color(), stroke.opacity, blend);
+ self.record(raster, Mark::Stroke(stroke), &touched);
+ touched
+ }
+
+ pub fn paint(&mut self, raster: &mut Raster, mark: Mark, brushes: &BrushSet) -> Result<Vec<usize>> {
+ let mut buffer = StrokeBuffer::new(self.width, self.height);
+ let (footprint, _) = painted(raster, &mut buffer, brushes, &mark)?;
+ self.record(raster, mark, &footprint);
+ Ok(footprint)
+ }
+
+ fn rebuild(&mut self, raster: &mut Raster, next: Vec<Mark>, brushes: &BrushSet) -> Result<Updated> {
+ let before: BTreeSet<usize> = raster.occupied().map(|(i, _)| i).collect();
+ let replayed = next.len();
+ let (cel, fresh, _) = Self::replay(self.width, self.height, next, brushes)?;
+ let tiles = before
+ .into_iter()
+ .chain(fresh.occupied().map(|(i, _)| i))
+ .collect::<BTreeSet<_>>();
+ *self = cel;
+ *raster = fresh;
+ Ok(Updated {
+ tiles: tiles.into_iter().collect(),
+ replayed,
+ full: true,
+ })
+ }
+
+ pub fn update(&mut self, raster: &mut Raster, next: Vec<Mark>, brushes: &BrushSet) -> Result<Updated> {
+ let keys: Vec<(u32, u64)> = next.iter().map(|m| (m.id(), fingerprint(m))).collect();
+ let old: BTreeMap<(u32, u64), usize> = self.keys.iter().enumerate().map(|(i, k)| (*k, i)).collect();
+ let kept: Vec<Option<usize>> = keys.iter().map(|k| old.get(k).copied()).collect();
+ let unchanged = kept.iter().enumerate().take_while(|(i, k)| **k == Some(*i)).count();
+ let reads = next[unchanged..].iter().any(|m| match m {
+ Mark::Stroke(stroke) => brushes.def(&stroke.brush).is_some_and(|d| d.reads_pixels()),
+ Mark::Fill(_) => false,
+ });
+ if reads || !kept.iter().flatten().is_sorted_by(|a, b| a < b) || self.footprints.len() != self.keys.len() {
+ return self.rebuild(raster, next, brushes);
+ }
+ let mut kept_old = vec![false; self.keys.len()];
+ kept.iter().flatten().for_each(|&j| kept_old[j] = true);
+ let prefix = kept.iter().enumerate().take_while(|(i, k)| **k == Some(*i)).count();
+ let base = self.checkpoints.iter().rposition(|c| c.at <= prefix).unwrap_or(0);
+ let start = self.checkpoints[base].at;
+ let tiles = raster.cols * raster.rows;
+ let mut dirty = vec![false; tiles];
+ self.footprints
+ .iter()
+ .zip(&kept_old)
+ .filter(|(_, kept)| !**kept)
+ .flat_map(|(f, _)| f)
+ .for_each(|&t| dirty[t as usize] = true);
+ let origin = self.checkpoints[base].tiles.clone();
+ (0..tiles)
+ .filter(|&t| dirty[t])
+ .for_each(|t| put(raster, t, &origin[t]));
+ let positions: Vec<usize> = kept
+ .iter()
+ .enumerate()
+ .filter(|(_, k)| k.is_some())
+ .map(|(i, _)| i)
+ .collect();
+ let mut later = self.checkpoints[base + 1..]
+ .iter()
+ .map(|c| {
+ let before = kept_old[..c.at.min(kept_old.len())].iter().filter(|k| **k).count();
+ let at = if before == 0 { 0 } else { positions[before - 1] + 1 };
+ (at, c.tiles.clone())
+ })
+ .collect::<Vec<_>>()
+ .into_iter()
+ .peekable();
+ let mut snapshots: Vec<Checkpoint> = Vec::new();
+ let snapshot = |at: usize, old: Vec<Tile>, dirty: &[bool], raster: &Raster, out: &mut Vec<Checkpoint>| {
+ if out.last().is_some_and(|c| c.at == at) {
+ return;
+ }
+ let mut tiles = old;
+ (0..dirty.len())
+ .filter(|&t| dirty[t])
+ .for_each(|t| tiles[t] = raster.at(t).map(Arc::from));
+ out.push(Checkpoint { at, tiles });
+ };
+ let mut last_kept = vec![0usize; tiles];
+ kept.iter().enumerate().skip(start).for_each(|(i, k)| {
+ if let Some(j) = k {
+ self.footprints[*j].iter().for_each(|&t| last_kept[t as usize] = i);
+ }
+ });
+ let mut footprints: Vec<Vec<u32>> = self.footprints[..start].to_vec();
+ let mut buffer = StrokeBuffer::new(self.width, self.height);
+ let mut catchup = StrokeBuffer::new(self.width, self.height);
+ buffer.set_mask(Some(dirty.clone()));
+ let mut replayed = 0;
+ for (i, mark) in next.iter().enumerate().skip(start) {
+ while let Some((_, old)) = later.next_if(|(at, _)| *at == i) {
+ snapshot(i, old, &dirty, raster, &mut snapshots);
+ }
+ if let Some(j) = kept[i] {
+ let footprint = &self.footprints[j];
+ if footprint.iter().any(|&t| dirty[t as usize]) {
+ painted(raster, &mut buffer, brushes, mark)?;
+ replayed += 1;
+ }
+ footprints.push(footprint.clone());
+ continue;
+ }
+ buffer.set_mask(None);
+ let footprint: Vec<usize> = match mark {
+ Mark::Stroke(stroke) => {
+ draw_stroke_on(&mut buffer, brushes.get(&stroke.brush)?, stroke, Some(raster));
+ buffer.touched().to_vec()
+ }
+ Mark::Fill(fill) => fill_tiles(raster, fill),
+ };
+ let (fresh, settled): (Vec<usize>, Vec<usize>) = footprint
+ .iter()
+ .copied()
+ .filter(|&t| !dirty[t])
+ .partition(|&t| last_kept[t] > i);
+ settled.iter().for_each(|&t| dirty[t] = true);
+ if !fresh.is_empty() {
+ let mut only = vec![false; tiles];
+ fresh.iter().for_each(|&t| {
+ only[t] = true;
+ put(raster, t, &origin[t]);
+ });
+ catchup.set_mask(Some(only.clone()));
+ (start..i)
+ .filter(|&k| footprints[k].iter().any(|&t| only[t as usize]))
+ .try_for_each(|k| painted(raster, &mut catchup, brushes, &next[k]).map(|_| ()))?;
+ fresh.iter().for_each(|&t| dirty[t] = true);
+ }
+ buffer.set_mask(Some(dirty.clone()));
+ match mark {
+ Mark::Stroke(stroke) => {
+ land_stroke(raster, &mut buffer, stroke, brushes.get(&stroke.brush)?);
+ }
+ Mark::Fill(fill) => {
+ paint_fill_where(raster, fill, |t| dirty[t]);
+ }
+ }
+ footprints.push(footprint.iter().map(|&t| t as u32).collect());
+ replayed += 1;
+ }
+ later.for_each(|(at, old)| snapshot(at.min(next.len()), old, &dirty, raster, &mut snapshots));
+ self.checkpoints.truncate(base + 1);
+ self.checkpoints.extend(snapshots.into_iter().filter(|c| c.at > start));
+ self.marks = next;
+ self.keys = keys;
+ self.footprints = footprints;
+ self.maybe_checkpoint(raster);
+ Ok(Updated {
+ tiles: (0..tiles).filter(|&t| dirty[t]).collect(),
+ replayed,
+ full: false,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::replay;
+ use klad_core::fill::{Coverage, Fill, FillRef, FillSource, Seed};
+ use klad_core::markedit::{self, MarkChange, MarkTransform};
+ use klad_core::stroke::marks;
+ use klad_core::synth::Synth;
+ use serde_json::json;
+
+ const W: u32 = 1024;
+ const H: u32 = 768;
+
+ fn sample(n: usize) -> Vec<Mark> {
+ let mut synth = Synth::canvas(W as f32, H as f32);
+ synth.brushes = vec![
+ "ink".into(),
+ "pencil".into(),
+ "chalk".into(),
+ "eraser".into(),
+ "marker".into(),
+ ];
+ let mut all = marks(synth.strokes(n, 7));
+ let mut mask = vec![0u8; (W * H) as usize];
+ (300..420).for_each(|y| (200..700).for_each(|x| mask[y * W as usize + x] = 200));
+ let fill = Fill::new(
+ 0,
+ [0.2, 0.5, 0.9, 1.0],
+ FillSource::Seed {
+ seed: Seed {
+ x: 300.0,
+ y: 350.0,
+ tolerance: 0.1,
+ gap: 0.0,
+ expand: 2.0,
+ },
+ reference: FillRef::This,
+ },
+ Coverage::from_mask(W, H, &mask),
+ );
+ all.insert(n / 3, Mark::Fill(fill));
+ all.iter_mut().enumerate().for_each(|(i, m)| m.set_id(i as u32 + 1));
+ all
+ }
+
+ fn brushes() -> BrushSet {
+ BrushSet::presets()
+ }
+
+ fn edited(marks: &[Mark], changes: Vec<MarkChange>) -> Vec<Mark> {
+ let mut out = marks.to_vec();
+ changes
+ .into_iter()
+ .for_each(|mut c| markedit::apply(&mut out, &mut c, "c1").unwrap());
+ out
+ }
+
+ fn check(cel: &CelReplay, raster: &Raster, expected: &[Mark]) {
+ let full = replay(W, H, expected, &brushes()).unwrap().raster;
+ assert_eq!(raster.hash(), full.hash());
+ let fresh = CelReplay::replay(W, H, expected.to_vec(), &brushes()).unwrap().0;
+ assert_eq!(cel.footprints(), fresh.footprints());
+ assert_eq!(cel.keys(), fresh.keys());
+ }
+
+ fn set(id: u32, props: serde_json::Value) -> MarkChange {
+ MarkChange::Set {
+ id,
+ props: props.as_object().unwrap().clone(),
+ }
+ }
+
+ #[test]
+ fn edits_replay_from_the_nearest_checkpoint_to_the_same_pixels() {
+ let brushes = brushes();
+ let start = sample(400);
+ let (mut cel, mut raster, _) = CelReplay::replay(W, H, start.clone(), &brushes).unwrap();
+ assert_eq!(cel.checkpoints(), [0, 128, 256, 384]);
+ let steps: Vec<Vec<MarkChange>> = vec![
+ vec![set(390, json!({"color":"#ff0000"}))],
+ vec![set(395, json!({"color":"#00ffff"}))],
+ vec![set(5, json!({"color":"#00ff00","size":30}))],
+ vec![MarkChange::Remove { id: 200 }],
+ vec![
+ MarkChange::Remove { id: 150 },
+ set(300, json!({"brush":"chalk","size":40})),
+ ],
+ vec![set(151, json!({"opacity":0.3}))],
+ vec![MarkChange::Transform {
+ ids: vec![10, 11, 12, 140],
+ transform: MarkTransform {
+ x: 120.0,
+ y: -40.0,
+ rotate: 20.0,
+ ..Default::default()
+ },
+ }],
+ vec![MarkChange::Transform {
+ ids: vec![134],
+ transform: MarkTransform {
+ x: 31.0,
+ y: 7.0,
+ ..Default::default()
+ },
+ }],
+ vec![MarkChange::Add(sample(3)[..2].to_vec())],
+ ];
+ assert!(start[133].as_fill().is_some());
+ let late = edited(&start, vec![set(390, json!({"color":"#ff0000"}))]);
+ let mut probe = cel.clone();
+ let mut probe_raster = raster.clone();
+ let done = probe.update(&mut probe_raster, late, &brushes).unwrap();
+ assert!(done.replayed <= 401 - 384, "{}", done.replayed);
+ let mut current = start;
+ steps.into_iter().for_each(|changes| {
+ current = edited(&current, changes);
+ let done = cel.update(&mut raster, current.clone(), &brushes).unwrap();
+ assert!(!done.full);
+ check(&cel, &raster, &current);
+ });
+ assert_eq!(cel.marks(), &current[..]);
+ let back = sample(400);
+ let done = cel.update(&mut raster, back.clone(), &brushes).unwrap();
+ assert!(!done.full);
+ check(&cel, &raster, &back);
+ }
+
+ #[test]
+ fn checkpoints_survive_edits_and_reordered_marks_fall_back_to_a_full_replay() {
+ let brushes = brushes();
+ let start = sample(300);
+ let (mut cel, mut raster, _) = CelReplay::replay(W, H, start.clone(), &brushes).unwrap();
+ let fewer = edited(&start, vec![MarkChange::Remove { id: 3 }, MarkChange::Remove { id: 4 }]);
+ cel.update(&mut raster, fewer.clone(), &brushes).unwrap();
+ assert_eq!(cel.checkpoints(), [0, 126, 254]);
+ let late = edited(&fewer, vec![set(290, json!({"color":"#123456"}))]);
+ let done = cel.update(&mut raster, late.clone(), &brushes).unwrap();
+ assert!(done.replayed < 50, "{}", done.replayed);
+ check(&cel, &raster, &late);
+ let mut swapped = late.clone();
+ swapped.swap(10, 20);
+ let done = cel.update(&mut raster, swapped.clone(), &brushes).unwrap();
+ assert!(done.full);
+ check(&cel, &raster, &swapped);
+ }
+
+ #[test]
+ fn appending_paints_only_the_new_marks() {
+ let brushes = brushes();
+ let start = sample(300);
+ let (mut cel, mut raster, _) = CelReplay::replay(W, H, start[..290].to_vec(), &brushes).unwrap();
+ let done = cel.update(&mut raster, start.clone(), &brushes).unwrap();
+ assert_eq!(done.replayed, 11);
+ check(&cel, &raster, &start);
+ let mut inserted = start.clone();
+ let mut extra = sample(2)[1].clone();
+ extra.set_id(900);
+ inserted.insert(150, extra);
+ cel.update(&mut raster, inserted.clone(), &brushes).unwrap();
+ check(&cel, &raster, &inserted);
+ }
+
+ #[test]
+ fn a_cache_without_marks_or_checkpoints_still_updates_exactly() {
+ let brushes = brushes();
+ let start = sample(150);
+ let (cel, mut raster, _) = CelReplay::replay(W, H, start.clone(), &brushes).unwrap();
+ let mut restored = CelReplay::from_cache(W, H, cel.keys().to_vec(), cel.footprints().to_vec());
+ let next = edited(&start, vec![set(20, json!({"size":3})), MarkChange::Remove { id: 90 }]);
+ let done = restored.update(&mut raster, next.clone(), &brushes).unwrap();
+ assert!(!done.full && done.replayed < 150);
+ check(&restored, &raster, &next);
+ }
+
+ #[test]
+ fn appended_and_committed_strokes_extend_the_record() {
+ let brushes = brushes();
+ let start = sample(130);
+ let (mut cel, mut raster, _) = CelReplay::replay(W, H, start[..100].to_vec(), &brushes).unwrap();
+ start[100..]
+ .iter()
+ .for_each(|m| drop(cel.paint(&mut raster, m.clone(), &brushes).unwrap()));
+ check(&cel, &raster, &start);
+ assert_eq!(cel.checkpoints(), [0, 128]);
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-brush edit_timing -- --ignored --nocapture"]
+ fn edit_timing() {
+ let brushes = brushes();
+ let dense = std::env::var("DENSE").is_ok();
+ let side = if dense { 640.0 } else { 2048.0 };
+ let mut synth = Synth::canvas(side, side);
+ synth.brushes = vec!["ink".into(), "pencil".into(), "marker".into()];
+ let mut start = marks(synth.strokes(1000, 3));
+ start.iter_mut().enumerate().for_each(|(i, m)| m.set_id(i as u32 + 1));
+ let t = std::time::Instant::now();
+ let (cel, raster, _) = CelReplay::replay(2048, 2048, start.clone(), &brushes).unwrap();
+ println!(
+ "replay of 1000 strokes on 2048: {:.0} ms, checkpoints {:?}, {} MB",
+ t.elapsed().as_secs_f64() * 1000.0,
+ cel.checkpoints(),
+ cel.checkpoint_bytes() >> 20
+ );
+ [1u32, 250, 500, 750, 990, 1000].iter().for_each(|&id| {
+ let next = edited(&start, vec![set(id, json!({"color":"#ff0000"}))]);
+ let (mut c, mut r) = (cel.clone(), raster.clone());
+ let t = std::time::Instant::now();
+ let done = c.update(&mut r, next, &brushes).unwrap();
+ println!(
+ "recolour stroke {id}: {:.1} ms, {} marks replayed, {} tiles",
+ t.elapsed().as_secs_f64() * 1000.0,
+ done.replayed,
+ done.tiles.len()
+ );
+ });
+ let ids: Vec<u32> = (940..990).collect();
+ let next = edited(
+ &start,
+ vec![MarkChange::Transform {
+ ids,
+ transform: MarkTransform {
+ x: 40.0,
+ y: 25.0,
+ ..Default::default()
+ },
+ }],
+ );
+ let (mut c, mut r) = (cel.clone(), raster.clone());
+ let t = std::time::Instant::now();
+ let done = c.update(&mut r, next, &brushes).unwrap();
+ println!(
+ "move 50 strokes: {:.1} ms, {} replayed, {} tiles",
+ t.elapsed().as_secs_f64() * 1000.0,
+ done.replayed,
+ done.tiles.len()
+ );
+ }
+
+ fn px(raster: &Raster, x: usize, y: usize) -> [f32; 4] {
+ raster
+ .get(x / crate::TILE, y / crate::TILE)
+ .map(|t| {
+ let at = ((y % crate::TILE) * crate::TILE + x % crate::TILE) * 4;
+ [t[at], t[at + 1], t[at + 2], t[at + 3]].map(|v| v.to_f32())
+ })
+ .unwrap_or([0.0; 4])
+ }
+
+ #[test]
+ fn locked_strokes_only_land_where_the_layer_has_alpha() {
+ let mut mask = vec![0u8; (W * H) as usize];
+ (100..200).for_each(|y| (100..400).for_each(|x| mask[y * W as usize + x] = 255));
+ let flat = Fill::new(
+ 1,
+ [0.9, 0.8, 0.2, 1.0],
+ FillSource::Polygon(vec![[100.0, 100.0], [400.0, 100.0], [400.0, 200.0]]),
+ Coverage::from_mask(W, H, &mask),
+ );
+ let mut shade = klad_core::stroke::Stroke::new(2, "ink", [0.1, 0.1, 0.4, 1.0], 40.0, 3)
+ .with_points(&[(50.0, 150.0, 1.0), (450.0, 150.0, 1.0)], 4.0);
+ shade.lock = true;
+ let mut eraser = klad_core::stroke::Stroke::new(3, "eraser", [0.0, 0.0, 0.0, 1.0], 30.0, 3)
+ .with_points(&[(50.0, 120.0, 1.0), (450.0, 120.0, 1.0)], 4.0);
+ eraser.lock = true;
+ let marks = vec![Mark::Fill(flat), Mark::Stroke(shade), Mark::Stroke(eraser)];
+ let raster = replay(W, H, &marks, &brushes()).unwrap().raster;
+ let inside = px(&raster, 250, 150);
+ assert!(
+ (inside[3] - 1.0).abs() < 1e-3 && inside[2] > 0.35 && inside[0] < 0.15,
+ "{inside:?}"
+ );
+ assert_eq!(px(&raster, 60, 150), [0.0; 4]);
+ assert_eq!(px(&raster, 420, 150), [0.0; 4]);
+ assert!((px(&raster, 250, 120)[3] - 1.0).abs() < 1e-3);
+ let (cel, mut live, _) = CelReplay::replay(W, H, marks[..1].to_vec(), &brushes()).unwrap();
+ let mut cel = cel;
+ cel.update(&mut live, marks.clone(), &brushes()).unwrap();
+ assert_eq!(live.hash(), raster.hash());
+ }
+
+ #[test]
+ fn a_cut_and_moved_lasso_leaves_everything_outside_alone() {
+ let all = sample(60);
+ let polygon = vec![[300.0, 200.0], [620.0, 220.0], [600.0, 520.0], [280.0, 480.0]];
+ let before = replay(W, H, &all, &brushes()).unwrap().raster;
+ let mut split = all.clone();
+ let chosen = markedit::split(&mut split, &polygon, true);
+ assert!(chosen.len() > all.len() / 10, "{} chosen", chosen.len());
+ let unmoved = replay(W, H, &split, &brushes()).unwrap().raster;
+ let far = |x: usize, y: usize| !(270..=630).contains(&x) || !(190..=530).contains(&y);
+ let worst = (0..H as usize)
+ .step_by(3)
+ .flat_map(|y| (0..W as usize).step_by(3).map(move |x| (x, y)))
+ .map(|(x, y)| {
+ let (a, b) = (px(&before, x, y), px(&unmoved, x, y));
+ (0..4).map(|c| (a[c] - b[c]).abs()).fold(0.0f32, f32::max)
+ })
+ .fold(0.0f32, f32::max);
+ assert!(worst < 0.3, "splitting without moving changed a pixel by {worst}");
+ let moved = edited(
+ &all,
+ vec![MarkChange::Lasso {
+ polygon: polygon.clone(),
+ cut: true,
+ action: markedit::LassoAction::Transform(MarkTransform {
+ x: 300.0,
+ y: 150.0,
+ ..Default::default()
+ }),
+ chosen: Vec::new(),
+ }],
+ );
+ let after = replay(W, H, &moved, &brushes()).unwrap().raster;
+ let reference = replay(
+ W,
+ H,
+ &split
+ .iter()
+ .filter(|m| !chosen.contains(&m.id()))
+ .cloned()
+ .collect::<Vec<_>>(),
+ &brushes(),
+ )
+ .unwrap()
+ .raster;
+ (0..H as usize)
+ .step_by(2)
+ .flat_map(|y| (0..W as usize).step_by(2).map(move |x| (x, y)))
+ .filter(|&(x, y)| far(x, y) && (x < 570 || y < 340))
+ .for_each(|(x, y)| assert_eq!(px(&after, x, y), px(&reference, x, y), "({x},{y})"));
+ let (mut cel, mut raster, _) = CelReplay::replay(W, H, all.clone(), &brushes()).unwrap();
+ cel.update(&mut raster, moved.clone(), &brushes()).unwrap();
+ check(&cel, &raster, &moved);
+ }
+}
diff --git a/crates/brush/src/tiles.rs b/crates/brush/src/tiles.rs
new file mode 100644
index 0000000..ff95b37
--- /dev/null
+++ b/crates/brush/src/tiles.rs
@@ -0,0 +1,305 @@
+use anyhow::{Result, bail};
+use half::f16;
+use klad_core::rng::{FNV_OFFSET, fnv};
+use std::sync::Arc;
+
+pub const TILE: usize = 256;
+pub const TILE_PX: usize = TILE * TILE;
+
+#[derive(Clone)]
+pub struct TileGrid<T, const C: usize> {
+ pub width: u32,
+ pub height: u32,
+ pub cols: usize,
+ pub rows: usize,
+ tiles: Vec<Option<Arc<Box<[T]>>>>,
+}
+
+pub type Raster = TileGrid<f16, 4>;
+
+impl<T: Copy + Default, const C: usize> TileGrid<T, C> {
+ pub fn new(width: u32, height: u32) -> Self {
+ let cols = (width as usize).div_ceil(TILE);
+ let rows = (height as usize).div_ceil(TILE);
+ Self {
+ width,
+ height,
+ cols,
+ rows,
+ tiles: (0..cols * rows).map(|_| None).collect(),
+ }
+ }
+
+ pub fn index(&self, tx: usize, ty: usize) -> usize {
+ ty * self.cols + tx
+ }
+
+ pub fn at(&self, index: usize) -> Option<&[T]> {
+ self.tiles[index].as_deref().map(|t| &t[..])
+ }
+
+ pub fn at_mut(&mut self, index: usize) -> Option<&mut [T]> {
+ self.tiles[index].as_mut().map(|t| &mut Arc::make_mut(t)[..])
+ }
+
+ pub fn get(&self, tx: usize, ty: usize) -> Option<&[T]> {
+ self.at(self.index(tx, ty))
+ }
+
+ pub fn ensure(&mut self, index: usize) -> &mut [T] {
+ let tile =
+ self.tiles[index].get_or_insert_with(|| Arc::new(vec![T::default(); TILE_PX * C].into_boxed_slice()));
+ &mut Arc::make_mut(tile)[..]
+ }
+
+ pub fn clear(&mut self, index: usize) {
+ self.tiles[index] = None;
+ }
+
+ pub fn put(&mut self, index: usize, data: Box<[T]>) {
+ assert_eq!(data.len(), TILE_PX * C);
+ self.tiles[index] = Some(Arc::new(data));
+ }
+
+ pub fn occupied(&self) -> impl Iterator<Item = (usize, &[T])> {
+ self.tiles
+ .iter()
+ .enumerate()
+ .filter_map(|(i, t)| t.as_deref().map(|t| (i, &t[..])))
+ }
+
+ pub fn count(&self) -> usize {
+ self.tiles.iter().filter(|t| t.is_some()).count()
+ }
+
+ pub fn bytes(&self) -> usize {
+ self.count() * TILE_PX * C * std::mem::size_of::<T>()
+ }
+}
+
+const RASTER_MAGIC: &[u8; 4] = b"DART";
+
+impl Raster {
+ pub fn hash(&self) -> u64 {
+ self.occupied().fold(FNV_OFFSET, |h, (i, tile)| {
+ fnv(fnv(h, &(i as u64).to_le_bytes()), bytemuck::cast_slice(tile))
+ })
+ }
+
+ pub fn encode(&self) -> Vec<u8> {
+ let header = [self.width, self.height, self.count() as u32];
+ let mut out = Vec::with_capacity(16 + self.bytes() + self.count() * 4);
+ out.extend_from_slice(RASTER_MAGIC);
+ header.iter().for_each(|v| out.extend_from_slice(&v.to_le_bytes()));
+ self.occupied().for_each(|(i, tile)| {
+ out.extend_from_slice(&(i as u32).to_le_bytes());
+ out.extend_from_slice(bytemuck::cast_slice(tile));
+ });
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self> {
+ let word = |at: usize| -> Result<u32> {
+ match bytes.get(at..at + 4) {
+ Some(b) => Ok(u32::from_le_bytes(b.try_into()?)),
+ None => bail!("raster data ends early"),
+ }
+ };
+ if bytes.get(0..4) != Some(RASTER_MAGIC) {
+ bail!("not a raster file");
+ }
+ let mut raster = Raster::new(word(4)?, word(8)?);
+ let count = word(12)? as usize;
+ let tile_bytes = TILE_PX * 4 * 2;
+ (0..count).try_for_each(|n| {
+ let at = 16 + n * (4 + tile_bytes);
+ let index = word(at)? as usize;
+ let Some(data) = bytes.get(at + 4..at + 4 + tile_bytes) else {
+ bail!("raster tile {n} ends early");
+ };
+ if index >= raster.cols * raster.rows {
+ bail!("raster tile index {index} out of range");
+ }
+ let tile: Vec<f16> = bytemuck::pod_collect_to_vec(data);
+ raster.put(index, tile.into_boxed_slice());
+ Ok(())
+ })?;
+ Ok(raster)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Mode {
+ #[default]
+ Flat,
+ Colour,
+ Replace,
+}
+
+pub struct StrokeBuffer {
+ grid: TileGrid<f32, 1>,
+ paint: TileGrid<f32, 4>,
+ pub mode: Mode,
+ touched: Vec<usize>,
+ marked: Vec<bool>,
+ dirty: Vec<usize>,
+ dirty_marked: Vec<bool>,
+ mask: Option<Vec<bool>>,
+}
+
+impl StrokeBuffer {
+ pub fn new(width: u32, height: u32) -> Self {
+ let grid = TileGrid::new(width, height);
+ let marked = vec![false; grid.cols * grid.rows];
+ Self {
+ grid,
+ paint: TileGrid::new(width, height),
+ mode: Mode::Flat,
+ touched: Vec::new(),
+ dirty_marked: marked.clone(),
+ marked,
+ dirty: Vec::new(),
+ mask: None,
+ }
+ }
+
+ pub fn set_mask(&mut self, mask: Option<Vec<bool>>) {
+ self.mask = mask;
+ }
+
+ pub fn take_mask(&mut self) -> Option<Vec<bool>> {
+ self.mask.take()
+ }
+
+ pub fn allowed(&self, index: usize) -> bool {
+ self.mask.as_ref().is_none_or(|m| m[index])
+ }
+
+ pub fn skip(&mut self, index: usize) -> bool {
+ if self.allowed(index) {
+ return false;
+ }
+ if !self.marked[index] {
+ self.marked[index] = true;
+ self.touched.push(index);
+ }
+ true
+ }
+
+ pub fn grid(&self) -> &TileGrid<f32, 1> {
+ &self.grid
+ }
+
+ pub fn tile_mut(&mut self, index: usize) -> &mut [f32] {
+ if !self.marked[index] {
+ self.marked[index] = true;
+ self.touched.push(index);
+ }
+ if !self.dirty_marked[index] {
+ self.dirty_marked[index] = true;
+ self.dirty.push(index);
+ }
+ self.grid.ensure(index)
+ }
+
+ pub fn tiles_mut(&mut self, index: usize) -> (&mut [f32], Option<&mut [f32]>) {
+ self.tile_mut(index);
+ let paint = match self.mode {
+ Mode::Flat => None,
+ _ => Some(self.paint.ensure(index)),
+ };
+ (self.grid.ensure(index), paint)
+ }
+
+ pub fn paint(&self, index: usize) -> Option<&[f32]> {
+ match self.mode {
+ Mode::Flat => None,
+ _ => self.paint.at(index),
+ }
+ }
+
+ pub fn take_dirty(&mut self) -> Vec<usize> {
+ let dirty = std::mem::take(&mut self.dirty);
+ dirty.iter().for_each(|&i| self.dirty_marked[i] = false);
+ dirty
+ }
+
+ pub fn touched(&self) -> &[usize] {
+ &self.touched
+ }
+
+ pub fn coverage(&self, index: usize) -> Option<&[f32]> {
+ self.grid.at(index)
+ }
+
+ pub fn coverage_mut(&mut self, index: usize) -> Option<&mut [f32]> {
+ self.grid.at_mut(index)
+ }
+
+ pub fn reset(&mut self) {
+ let touched = std::mem::take(&mut self.touched);
+ touched.iter().for_each(|&i| {
+ self.marked[i] = false;
+ if let Some(tile) = self.grid.at_mut(i) {
+ tile.fill(0.0);
+ }
+ if let Some(tile) = self.paint.at_mut(i) {
+ tile.fill(0.0);
+ }
+ });
+ self.touched = touched;
+ self.touched.clear();
+ self.mode = Mode::Flat;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn grid_covers_partial_tiles() {
+ let grid: Raster = TileGrid::new(300, 513);
+ assert_eq!((grid.cols, grid.rows), (2, 3));
+ assert_eq!(grid.count(), 0);
+ }
+
+ #[test]
+ fn raster_encode_round_trip() {
+ let mut raster: Raster = TileGrid::new(600, 300);
+ raster.ensure(4)[17] = f16::from_f32(0.25);
+ raster.ensure(1)[3] = f16::from_f32(1.0);
+ let back = Raster::decode(&raster.encode()).unwrap();
+ assert_eq!(back.hash(), raster.hash());
+ assert_eq!((back.width, back.height, back.count()), (600, 300, 2));
+ assert!(Raster::decode(&raster.encode()[..40]).is_err());
+ }
+
+ #[test]
+ fn masked_tiles_count_as_touched_but_get_no_pixels() {
+ let mut buffer = StrokeBuffer::new(512, 512);
+ let mut mask = vec![false; 4];
+ mask[2] = true;
+ buffer.set_mask(Some(mask));
+ assert!(buffer.skip(1));
+ assert!(!buffer.skip(2));
+ buffer.tile_mut(2)[0] = 0.5;
+ assert_eq!(buffer.touched(), &[1, 2]);
+ assert!(buffer.coverage(1).is_none());
+ buffer.reset();
+ assert!(buffer.touched().is_empty());
+ }
+
+ #[test]
+ fn buffer_reset_clears_only_touched() {
+ let mut buffer = StrokeBuffer::new(512, 512);
+ buffer.tile_mut(3)[10] = 0.5;
+ buffer.tile_mut(3)[11] = 0.25;
+ assert_eq!(buffer.touched(), &[3]);
+ assert_eq!(buffer.take_dirty(), vec![3]);
+ assert!(buffer.take_dirty().is_empty());
+ buffer.reset();
+ assert!(buffer.touched().is_empty());
+ assert!(buffer.coverage(3).unwrap().iter().all(|&v| v == 0.0));
+ }
+}
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
new file mode 100644
index 0000000..498127c
--- /dev/null
+++ b/crates/cli/Cargo.toml
@@ -0,0 +1,28 @@
+[package]
+name = "klad-cli"
+version.workspace = true
+edition.workspace = true
+license-file.workspace = true
+publish.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+clap = { version = "4.6.7", features = ["derive"] }
+klad-brush = { version = "0.1.0", path = "../brush" }
+klad-core = { version = "0.1.0", path = "../core" }
+klad-render = { version = "0.1.0", path = "../render" }
+libm = "0.2.16"
+notify = "8"
+rayon = "1.12.0"
+serde_json = "1.0.154"
+zstd = "0.14.3"
+
+[[bin]]
+name = "klad"
+path = "src/main.rs"
+
+[target.'cfg(target_os = "macos")'.dependencies]
+klad-app = { version = "0.1.0", path = "../app" }
+
+[target."cfg(unix)".dependencies]
+libc = "0.2.191"
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
new file mode 100644
index 0000000..5e6a44f
--- /dev/null
+++ b/crates/cli/src/agent.rs
@@ -0,0 +1,935 @@
+use crate::layers;
+use anyhow::{Context, Result, anyhow, bail};
+use klad_brush::BrushSet;
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::doc::{Item, Kind, Layer, Node};
+use klad_core::markedit::{LassoAction, MarkChange, address, parse_address};
+use klad_core::ops::{Applied, Op, Place, parse_lines};
+use klad_core::stroke::Mark as PaintMark;
+use klad_render::onion::{self, Onion, Onions};
+use klad_render::overlay::{self, Mark, Overlay};
+use klad_render::{Frame, Rasters, View, compose_view, vector};
+use serde_json::{Map, Value, json};
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+pub const PREVIEW_SIDE: f32 = 1024.0;
+const STRING_KEYS: [&str; 4] = ["name", "d", "id", "link"];
+
+pub struct Output {
+ pub json: bool,
+ pub render: bool,
+ pub scale: Option<f32>,
+ pub frame: u32,
+ pub overlay: Option<String>,
+}
+
+pub struct Look {
+ pub kinds: Option<String>,
+ pub focus: Option<String>,
+ pub depth: usize,
+ pub onion: Onion,
+ pub onion_layers: Option<Vec<String>>,
+ pub tracks: Vec<String>,
+ pub references: bool,
+}
+
+impl Look {
+ pub fn plain(kinds: Option<String>) -> Self {
+ Self {
+ kinds,
+ focus: None,
+ depth: 1,
+ onion: Onion::default(),
+ onion_layers: None,
+ tracks: Vec::new(),
+ references: false,
+ }
+ }
+
+ pub fn kinds(&self) -> Result<Kinds> {
+ self.kinds
+ .as_deref()
+ .map(overlay_flags)
+ .transpose()
+ .map(Option::unwrap_or_default)
+ }
+
+ pub fn tracks(&self) -> Result<Vec<crate::arcs::Track>> {
+ self.tracks.iter().map(|t| crate::arcs::Track::parse(t)).collect()
+ }
+
+ pub fn wants_onion(&self) -> Result<bool> {
+ Ok(match &self.kinds {
+ Some(kinds) => overlay_flags(kinds)?.onion,
+ None => false,
+ })
+ }
+}
+
+pub fn parse_value(key: &str, text: &str) -> Value {
+ let last = key.rsplit('.').next().unwrap_or(key);
+ if STRING_KEYS.contains(&last) {
+ return Value::String(text.to_string());
+ }
+ serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_string()))
+}
+
+pub fn parse_props(pairs: &[String]) -> Result<Map<String, Value>> {
+ pairs
+ .iter()
+ .map(|pair| {
+ let (key, value) = pair
+ .split_once('=')
+ .ok_or_else(|| anyhow!("{pair:?} is not key=value"))?;
+ Ok((key.trim().to_string(), parse_value(key.trim(), value)))
+ })
+ .collect()
+}
+
+fn insert_path(target: &mut Value, path: &str, value: Value) {
+ let parts: Vec<&str> = path.split('.').collect();
+ let Some((last, parents)) = parts.split_last() else {
+ return;
+ };
+ let parent = parents.iter().fold(target, |node, part| {
+ if !node.is_object() {
+ *node = json!({});
+ }
+ let map = node.as_object_mut().expect("object");
+ let child = map.entry(part.to_string()).or_insert_with(|| json!({}));
+ if !child.is_object() {
+ *child = json!({});
+ }
+ child
+ });
+ if let Some(map) = parent.as_object_mut() {
+ map.insert(last.to_string(), value);
+ }
+}
+
+pub fn nest(props: Map<String, Value>) -> Value {
+ props.into_iter().fold(json!({}), |mut acc, (key, value)| {
+ insert_path(&mut acc, &key, value);
+ acc
+ })
+}
+
+pub fn add_op(what: &str, rest: &[String], place: Place) -> Result<Op> {
+ match what {
+ "layer" => {
+ let (kind, props) = match rest.split_first() {
+ Some((kind, props)) if !kind.contains('=') => (kind.clone(), props),
+ _ => bail!("say which kind: klad add <bundle> layer paint|vector|group|adjust|image [key=value ...]"),
+ };
+ let layer = match kind.as_str() {
+ "adjust" => crate::looks::adjust_layer(props)?,
+ _ => {
+ let mut layer = nest(parse_props(props)?);
+ layer["kind"] = Value::String(kind);
+ layer
+ }
+ };
+ Ok(Op::AddLayer { layer, place })
+ }
+ "cel" => {
+ let layer = place
+ .into
+ .clone()
+ .ok_or_else(|| anyhow!("add cel needs --in <layer>"))?;
+ let mut cel = nest(parse_props(rest)?);
+ if let Some(frame) = place.frame {
+ cel["frame"] = json!(frame);
+ }
+ Ok(Op::AddCel { cel, layer })
+ }
+ "rect" | "ellipse" | "path" | "group" | "rays" | "scatter" | "repeat" | "mirror" | "text" => {
+ let mut node = nest(parse_props(rest)?);
+ node["type"] = Value::String(what.to_string());
+ Ok(Op::AddNode { node, place })
+ }
+ "mask" => {
+ let layer = place
+ .into
+ .clone()
+ .ok_or_else(|| anyhow!("add mask needs --in <the layer it masks>"))?;
+ let mut mask = nest(parse_props(rest)?);
+ let hide = match mask.as_object_mut().and_then(|m| m.remove("hide")) {
+ None => false,
+ Some(Value::Bool(b)) => b,
+ Some(other) => bail!("hide takes true or false, not {other}"),
+ };
+ Ok(Op::AddMask { mask, layer, hide })
+ }
+ other => bail!(
+ "cannot add {other:?}: use layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text"
+ ),
+ }
+}
+
+fn preview_scale(bundle: &Bundle, scale: Option<f32>) -> f32 {
+ scale.unwrap_or_else(|| {
+ let longest = bundle.doc.canvas.width.max(bundle.doc.canvas.height) as f32;
+ (PREVIEW_SIDE / longest).min(1.0)
+ })
+}
+
+pub fn render_path(bundle: &Bundle, frame: u32, view: View, tag: &str) -> PathBuf {
+ let frame = if bundle.doc.timeline.frames > 1 {
+ format!("-f{frame}")
+ } else {
+ String::new()
+ };
+ let region = view
+ .region
+ .map_or(String::new(), |[x, y, w, h]| format!("-{x}_{y}_{w}x{h}"));
+ let scale = if (view.scale - 1.0).abs() < f32::EPSILON {
+ String::new()
+ } else {
+ format!("@{:.3}", view.scale)
+ };
+ bundle
+ .cache_dir()
+ .join("renders")
+ .join(format!("r{}{frame}{region}{scale}{tag}.png", bundle.doc.rev))
+}
+
+#[derive(Default)]
+pub struct Kinds {
+ pub ids: bool,
+ pub bbox: bool,
+ pub grid: bool,
+ pub onion: bool,
+ pub parts: bool,
+ pub arcs: bool,
+}
+
+pub fn overlay_flags(kinds: &str) -> Result<Kinds> {
+ kinds
+ .split(',')
+ .map(str::trim)
+ .filter(|k| !k.is_empty())
+ .try_fold(Kinds::default(), |acc, k| {
+ Ok(match k {
+ "ids" => Kinds { ids: true, ..acc },
+ "bbox" | "boxes" => Kinds { bbox: true, ..acc },
+ "grid" => Kinds { grid: true, ..acc },
+ "onion" => Kinds { onion: true, ..acc },
+ "parts" => Kinds { parts: true, ..acc },
+ "arcs" => Kinds { arcs: true, ..acc },
+ "all" => Kinds {
+ ids: true,
+ bbox: true,
+ grid: true,
+ ..acc
+ },
+ other => bail!("unknown overlay {other:?}: use ids, bbox, grid, onion, parts, arcs or all"),
+ })
+ })
+}
+
+pub fn arcs_of(bundle: &Bundle, look: &Look, frame: u32, wanted: bool) -> Result<Vec<overlay::Arc>> {
+ if !wanted {
+ return Ok(Vec::new());
+ }
+ let tracks = look.tracks()?;
+ if tracks.is_empty() {
+ bail!("--overlay arcs needs --track: a mark (c4:s12), a part (leaf) or a point (x,y)");
+ }
+ let span = crate::arcs::range(&bundle.doc, frame, None, None);
+ Ok(crate::arcs::arcs_overlay(&crate::arcs::track(bundle, &tracks, span)?))
+}
+
+pub fn onion_layers(bundle: &Bundle, look: &Look) -> Result<Vec<String>> {
+ match &look.onion_layers {
+ Some(keys) => keys
+ .iter()
+ .map(|k| bundle.doc.find_layer(k).map(|l| l.id.clone()))
+ .collect(),
+ None => Ok(onion::animated(&bundle.doc)),
+ }
+}
+
+pub fn onions(bundle: &Bundle, frame: u32, layers: &[String], look: &Look, brushes: &BrushSet) -> Result<Onions> {
+ let plan = onion::plan(&bundle.doc, frame, layers, &look.onion);
+ let ghosts = crate::layers::load_cels(bundle, brushes, &onion::needed(&bundle.doc, &plan))?;
+ Ok(onion::build(&bundle.doc, &plan, &ghosts))
+}
+
+fn paint_marks(bundle: &Bundle, layers: &[Layer], frame: u32, out: &mut Vec<Mark>) -> Result<()> {
+ layers
+ .iter()
+ .filter(|l| l.visible)
+ .try_for_each(|layer| match layer.kind() {
+ Kind::Paint => {
+ if let Some(cel) = layer.content_at(frame)
+ && let (_, Some(rect)) = paint_bounds(bundle, layer, &cel.id)?
+ {
+ out.push(Mark {
+ label: format!("{} {}", layer.id, layer.name),
+ rect,
+ });
+ }
+ Ok(())
+ }
+ Kind::Group => paint_marks(bundle, layer.children(), frame, out),
+ Kind::Vector | Kind::Adjust => Ok(()),
+ })
+}
+
+pub fn marks(bundle: &Bundle, frame: u32, focus: Option<&str>, depth: usize) -> Result<Vec<Mark>> {
+ let doc = &bundle.doc;
+ let mut out = match focus {
+ Some(id) => overlay::scoped_marks(doc, id, frame, depth)?,
+ None => overlay::vector_marks(doc, frame, depth)?,
+ };
+ let scope: Vec<Layer> = match focus.and_then(|id| doc.layer(id)) {
+ Some(layer) => vec![layer.clone()],
+ None if focus.is_some() => Vec::new(),
+ None => doc.layers.clone(),
+ };
+ paint_marks(bundle, &scope, frame, &mut out)?;
+ Ok(out)
+}
+
+fn layer_box(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Option<[f32; 4]>> {
+ Ok(match layer.kind() {
+ Kind::Paint => match layer.content_at(frame) {
+ Some(cel) => paint_bounds(bundle, layer, &cel.id)?.1,
+ None => None,
+ },
+ Kind::Vector => layer
+ .content_at(frame)
+ .map_or(Ok(None), |c| vector::nodes_box(&c.nodes))?,
+ Kind::Group => layer.children().iter().try_fold(None, |acc, c| {
+ Ok::<_, anyhow::Error>(union(acc, layer_box(bundle, c, frame)?))
+ })?,
+ Kind::Adjust => None,
+ })
+}
+
+pub fn find_mark(bundle: &Bundle, id: &str) -> Result<Option<(String, PaintMark)>> {
+ let Some((cel, mark)) = parse_address(id) else {
+ return Ok(None);
+ };
+ let (layer, cel) = match bundle.doc.item(cel) {
+ Some(Item::Cel(layer, c)) if layer.kind() == Kind::Paint => (layer.id.clone(), layer.content_of(c).id.clone()),
+ _ => bail!("no paint cel {cel}"),
+ };
+ let found = bundle
+ .read_marks(&layer, &cel)?
+ .into_iter()
+ .find(|m| m.id() == mark)
+ .ok_or_else(|| anyhow!("{id} does not exist (klad strokes lists the marks)"))?;
+ Ok(Some((cel, found)))
+}
+
+pub fn item_box(bundle: &Bundle, id: &str, frame: u32) -> Result<Option<[f32; 4]>> {
+ if let Some((_, mark)) = find_mark(bundle, id)? {
+ return Ok(mark.bounds().map(|[x0, y0, x1, y1]| [x0, y0, x1 - x0, y1 - y0]));
+ }
+ match bundle.doc.item(id).ok_or_else(|| anyhow!("no item {id}"))? {
+ Item::Layer(layer) => layer_box(bundle, layer, frame),
+ Item::Cel(layer, cel) => match layer.kind() {
+ Kind::Paint => Ok(paint_bounds(bundle, layer, &layer.content_of(cel).id)?.1),
+ _ => vector::nodes_box(&layer.content_of(cel).nodes),
+ },
+ Item::Node(..) => overlay::node_world_box(&bundle.doc, id),
+ }
+}
+
+pub fn focus_view(bundle: &Bundle, id: &str, frame: u32, scale: Option<f32>) -> Result<View> {
+ let [x, y, w, h] =
+ item_box(bundle, id, frame)?.ok_or_else(|| anyhow!("{id} has nothing to show at frame {frame}"))?;
+ let pad = w.max(h) * 0.08 + 16.0;
+ let (cw, ch) = (bundle.doc.canvas.width as f32, bundle.doc.canvas.height as f32);
+ let (x0, y0) = ((x - pad).max(0.0).floor(), (y - pad).max(0.0).floor());
+ let (x1, y1) = ((x + w + pad).min(cw).ceil(), (y + h + pad).min(ch).ceil());
+ if x1 <= x0 || y1 <= y0 {
+ bail!("{id} lies outside the canvas");
+ }
+ let (rw, rh) = (x1 - x0, y1 - y0);
+ Ok(View {
+ scale: scale.unwrap_or_else(|| PREVIEW_SIDE / rw.max(rh)),
+ region: Some([x0 as i32, y0 as i32, rw as i32, rh as i32]),
+ references: false,
+ })
+}
+
+pub struct Rendered {
+ pub path: PathBuf,
+ pub frame: Frame,
+ pub note: String,
+}
+
+pub fn render_look(
+ bundle: &Bundle,
+ frame: u32,
+ view: View,
+ look: &Look,
+ out: Option<PathBuf>,
+ use_cache: bool,
+) -> Result<Rendered> {
+ let view = View {
+ references: view.references || look.references,
+ ..view
+ };
+ let brushes = BrushSet::for_bundle(bundle)?;
+ let loaded = layers::load(bundle, frame, &brushes, use_cache)?;
+ let kinds = look.kinds()?;
+ let overlay = (kinds.ids || kinds.bbox || kinds.grid || kinds.parts || kinds.arcs)
+ .then(|| {
+ let mut found = if kinds.ids || kinds.bbox {
+ marks(bundle, frame, look.focus.as_deref(), look.depth)?
+ } else {
+ Vec::new()
+ };
+ if kinds.parts {
+ found.extend(crate::arcs::part_marks(bundle, frame)?);
+ }
+ Ok::<_, anyhow::Error>(Overlay {
+ marks: found,
+ boxes: kinds.bbox || kinds.parts,
+ ids: kinds.ids || kinds.parts,
+ grid: kinds.grid,
+ arcs: arcs_of(bundle, look, frame, kinds.arcs)?,
+ frame: Some(frame),
+ numbers: true,
+ })
+ })
+ .transpose()?;
+ let onions = kinds
+ .onion
+ .then(|| onions(bundle, frame, &onion_layers(bundle, look)?, look, &brushes))
+ .transpose()?;
+ let rasters: &Rasters = &loaded.rasters;
+ let mut image = compose_view(&bundle.doc, frame, rasters, view, overlay.as_ref(), onions.as_ref())?;
+ let tag = match (overlay.is_some(), onions.is_some()) {
+ (true, true) => "-overlay-onion",
+ (true, false) => "-overlay",
+ (false, true) => "-onion",
+ (false, false) => "",
+ };
+ let path = out.unwrap_or_else(|| render_path(bundle, frame, view, tag));
+ write_atomic(&path, &image.png()?)?;
+ let note = match loaded.updated {
+ 0 => format!(
+ "paint cels: {} replayed ({} strokes, {} dabs), {} cached",
+ loaded.replayed, loaded.strokes, loaded.dabs, loaded.cached
+ ),
+ updated => format!(
+ "paint cels: {updated} updated in place, {} replayed ({} marks redrawn), {} cached",
+ loaded.replayed, loaded.strokes, loaded.cached
+ ),
+ };
+ Ok(Rendered {
+ path,
+ frame: image,
+ note,
+ })
+}
+
+pub fn resolve_strokes(bundle: &Bundle, ops: &mut [Op]) -> Result<()> {
+ ops.iter_mut().try_for_each(|op| {
+ let Op::Stroke(spec) = op else {
+ return Ok(());
+ };
+ let Some(brush) = bundle.brush(&spec.brush)? else {
+ bail!(
+ "unknown brush {:?}: brushes are {}",
+ spec.brush,
+ bundle.brush_ids()?.join(", ")
+ );
+ };
+ spec.taper.get_or_insert(brush.taper);
+ Ok(())
+ })
+}
+
+fn report(bundle: &Bundle, applied: &Applied, render: Option<PathBuf>, out: &Output) {
+ let painted: Vec<Value> = applied
+ .marks
+ .iter()
+ .map(|p| {
+ let ids = |fill: bool| -> Vec<u32> {
+ p.added()
+ .filter(|m| m.as_fill().is_some() == fill)
+ .map(|m| m.id())
+ .collect()
+ };
+ let lassoed: Vec<u32> = p
+ .changes
+ .iter()
+ .filter(|c| matches!(c, MarkChange::Lasso { .. }))
+ .flat_map(MarkChange::ids)
+ .collect();
+ json!({ "layer": p.layer, "cel": p.cel, "ids": ids(false), "fills": ids(true), "lassoed": lassoed })
+ })
+ .filter(|v| v["ids"] != json!([]) || v["fills"] != json!([]) || v["lassoed"] != json!([]))
+ .collect();
+ let copied: Vec<(String, String)> = applied
+ .marks
+ .iter()
+ .flat_map(|p| p.changes.iter().map(move |c| (p, c)))
+ .flat_map(|(p, c)| match c {
+ MarkChange::Paste { made, .. } => made
+ .iter()
+ .map(|m| (address(&m.cel, m.from), address(&p.cel, m.to)))
+ .collect(),
+ _ => Vec::new(),
+ })
+ .collect();
+ if out.json {
+ let value = json!({
+ "rev": bundle.doc.rev,
+ "added": applied.added,
+ "changed": applied.changed,
+ "removed": applied.removed,
+ "strokes": painted,
+ "copied": copied.iter().map(|(from, to)| json!({"from": from, "to": to})).collect::<Vec<_>>(),
+ "notes": applied.notes,
+ "render": render.map(|p| p.display().to_string()),
+ });
+ println!("{value}");
+ return;
+ }
+ applied
+ .marks
+ .iter()
+ .filter(|p| p.added().next().is_some())
+ .for_each(|p| {
+ let (fills, strokes): (Vec<&PaintMark>, Vec<&PaintMark>) = p.added().partition(|m| m.as_fill().is_some());
+ let list = |marks: &[&PaintMark], what: &str| {
+ let ids: Vec<String> = marks.iter().map(|m| m.id().to_string()).collect();
+ (!ids.is_empty()).then(|| format!("{what} {}", ids.join(" ")))
+ };
+ let parts: Vec<String> = [list(&strokes, "strokes"), list(&fills, "fills")]
+ .into_iter()
+ .flatten()
+ .collect();
+ println!("painted on {} cel {}: {}", p.layer, p.cel, parts.join(", "));
+ });
+ applied
+ .marks
+ .iter()
+ .flat_map(|p| p.changes.iter().map(move |c| (p, c)))
+ .filter(|(_, c)| matches!(c, MarkChange::Lasso { .. }))
+ .for_each(|(p, c)| {
+ let ids: Vec<String> = c.ids().iter().map(|id| format!("{}:s{id}", p.cel)).collect();
+ let verb = match c {
+ MarkChange::Lasso {
+ action: LassoAction::Remove,
+ ..
+ } => "removed",
+ _ => "moved",
+ };
+ println!("lasso on {} {verb} {}", p.layer, ids.join(" "));
+ });
+ if !copied.is_empty() {
+ let pairs: Vec<String> = copied.iter().map(|(from, to)| format!("{from} -> {to}")).collect();
+ println!("copied {}", pairs.join(", "));
+ }
+ applied.notes.iter().for_each(|n| println!("{n}"));
+ applied.added.iter().for_each(|id| println!("added {id}"));
+ applied.changed.iter().for_each(|id| println!("changed {id}"));
+ applied.removed.iter().for_each(|id| println!("removed {id}"));
+ println!("rev {}", bundle.doc.rev);
+ if let Some(path) = render {
+ println!("{}", path.display());
+ }
+}
+
+pub fn preview(bundle: &Bundle, out: &Output) -> Result<Option<PathBuf>> {
+ if !out.render {
+ return Ok(None);
+ }
+ let view = View::scaled(preview_scale(bundle, out.scale));
+ let look = Look::plain(out.overlay.clone());
+ Ok(Some(render_look(bundle, out.frame, view, &look, None, true)?.path))
+}
+
+pub fn edit(path: &Path, ops: &[Op], out: &Output) -> Result<()> {
+ let mut bundle = Bundle::open(path)?;
+ let ops = crate::shapes::expand(&bundle, ops.to_vec())?;
+ let mut ops = vector::pinned(&bundle.doc, &ops)?;
+ resolve_strokes(&bundle, &mut ops)?;
+ let like = ops.iter().any(|op| matches!(op, Op::Fill(f) if f.like.is_some()));
+ let notes = crate::fills::resolve(&bundle, &mut ops)?;
+ notes.iter().for_each(|n| match like {
+ true => println!("{n}"),
+ false => eprintln!("{n}"),
+ });
+ let made = crate::inbetween::resolve(&bundle, &mut ops)?;
+ made.iter().for_each(|n| println!("{n}"));
+ if let Some(ms) = std::env::var("DRAW_TEST_WRITE_DELAY_MS")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ {
+ klad_core::bundle::write_atomic(&bundle.cache_dir().join("write-delay"), b"")?;
+ std::thread::sleep(std::time::Duration::from_millis(ms));
+ }
+ bundle.ensure_unchanged()?;
+ let applied = bundle.apply(&ops)?;
+ bundle.stamp("cli")?;
+ let render = preview(&bundle, out)?;
+ report(&bundle, &applied, render, out);
+ Ok(())
+}
+
+pub fn apply(path: &Path, file: Option<PathBuf>, out: &Output) -> Result<()> {
+ let text = match file {
+ Some(file) => std::fs::read_to_string(&file).with_context(|| format!("reading {}", file.display()))?,
+ None => {
+ let mut text = String::new();
+ std::io::stdin().read_to_string(&mut text)?;
+ text
+ }
+ };
+ let ops = parse_lines(&text)?;
+ if ops.is_empty() {
+ bail!("no ops: give JSON lines on stdin or with --file");
+ }
+ edit(path, &ops, out)
+}
+
+fn fmt_bounds(bounds: Option<[f32; 4]>) -> String {
+ bounds.map_or("empty".into(), |[x, y, w, h]| {
+ format!("{:.0},{:.0} {:.0}x{:.0}", x, y, w, h)
+ })
+}
+
+fn union(a: Option<[f32; 4]>, b: Option<[f32; 4]>) -> Option<[f32; 4]> {
+ match (a, b) {
+ (Some([ax, ay, aw, ah]), Some([bx, by, bw, bh])) => {
+ let (x, y) = (ax.min(bx), ay.min(by));
+ Some([x, y, (ax + aw).max(bx + bw) - x, (ay + ah).max(by + bh) - y])
+ }
+ (a, b) => a.or(b),
+ }
+}
+
+struct PaintCount {
+ strokes: usize,
+ fills: usize,
+}
+
+fn paint_bounds(bundle: &Bundle, layer: &Layer, cel: &str) -> Result<(PaintCount, Option<[f32; 4]>)> {
+ let marks = bundle.read_marks(&layer.id, cel)?;
+ let bounds = marks.iter().fold(None, |acc, m| {
+ union(acc, m.bounds().map(|[x0, y0, x1, y1]| [x0, y0, x1 - x0, y1 - y0]))
+ });
+ let fills = marks.iter().filter(|m| m.as_fill().is_some()).count();
+ Ok((
+ PaintCount {
+ strokes: marks.len() - fills,
+ fills,
+ },
+ bounds,
+ ))
+}
+
+fn put_counts(value: &mut Value, count: &PaintCount) {
+ value["strokes"] = json!(count.strokes);
+ if count.fills > 0 {
+ value["fills"] = json!(count.fills);
+ }
+}
+
+fn layer_summary(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Value> {
+ let cel = layer.cel_at(frame);
+ let content = layer.content_at(frame);
+ let mut value = json!({
+ "id": layer.id,
+ "kind": layer.kind().name(),
+ "name": layer.name,
+ "visible": layer.visible,
+ "opacity": layer.opacity,
+ "blend": layer.blend,
+ });
+ if let Some(cel) = cel {
+ value["cel"] = json!({ "id": cel.id, "frame": cel.frame, "hold": cel.hold, "link": cel.link });
+ }
+ if layer.clip {
+ value["clip"] = json!(true);
+ }
+ if layer.lock_alpha {
+ value["lockAlpha"] = json!(true);
+ }
+ if layer.locked {
+ value["locked"] = json!(true);
+ }
+ if let Some(mask) = &layer.mask {
+ let mut summary = layer_summary(bundle, mask, frame)?;
+ summary["role"] = json!("mask");
+ value["mask"] = summary;
+ }
+ let bounds = match layer.kind() {
+ Kind::Paint => match content {
+ Some(c) => {
+ let (count, bounds) = paint_bounds(bundle, layer, &c.id)?;
+ put_counts(&mut value, &count);
+ bounds
+ }
+ None => None,
+ },
+ Kind::Vector => {
+ let nodes = content.map_or(&[][..], |c| &c.nodes[..]);
+ value["nodes"] = Value::Array(nodes.iter().map(node_summary).collect::<Result<_>>()?);
+ vector::nodes_box(nodes)?
+ }
+ Kind::Group => {
+ let children = layer
+ .children()
+ .iter()
+ .map(|c| layer_summary(bundle, c, frame))
+ .collect::<Result<Vec<_>>>()?;
+ let bounds = children
+ .iter()
+ .filter_map(|c| serde_json::from_value::<[f32; 4]>(c["bounds"].clone()).ok())
+ .fold(None, |acc, b| union(acc, Some(b)));
+ value["children"] = Value::Array(children);
+ bounds
+ }
+ Kind::Adjust => {
+ if let Some(adjust) = layer.adjustment() {
+ value["adjust"] = serde_json::to_value(adjust)?;
+ }
+ None
+ }
+ };
+ if !layer.effects.is_empty() {
+ value["effects"] = serde_json::to_value(&layer.effects)?;
+ }
+ value["bounds"] = json!(bounds);
+ Ok(value)
+}
+
+fn node_summary(node: &Node) -> Result<Value> {
+ let bounds = vector::node_box(node)?;
+ let mut value = json!({ "id": node.id, "type": node.type_name(), "bounds": bounds });
+ if !node.name.is_empty() {
+ value["name"] = json!(node.name);
+ }
+ if !node.visible {
+ value["visible"] = json!(false);
+ }
+ if !node.children().is_empty() {
+ value["children"] = Value::Array(node.children().iter().map(node_summary).collect::<Result<_>>()?);
+ }
+ Ok(value)
+}
+
+const LIST_LIMIT: usize = 24;
+
+fn print_nodes(nodes: &[Value], depth: usize) {
+ let hidden = nodes.len().saturating_sub(LIST_LIMIT);
+ nodes.iter().rev().take(LIST_LIMIT).for_each(|n| {
+ let name = n["name"].as_str().unwrap_or("");
+ let hidden = if n["visible"] == json!(false) { " hidden" } else { "" };
+ let bounds = serde_json::from_value::<Option<[f32; 4]>>(n["bounds"].clone())
+ .ok()
+ .flatten();
+ println!(
+ "{:indent$}{:<6} {:<8} {:<16} {}{hidden}",
+ "",
+ n["id"].as_str().unwrap_or(""),
+ n["type"].as_str().unwrap_or(""),
+ name,
+ fmt_bounds(bounds),
+ indent = depth * 2
+ );
+ if let Some(children) = n["children"].as_array() {
+ print_nodes(children, depth + 1);
+ }
+ });
+ if hidden > 0 {
+ println!(
+ "{:indent$}... {hidden} more (klad show <group id> or ls --json)",
+ "",
+ indent = depth * 2
+ );
+ }
+}
+
+fn print_layer(v: &Value, depth: usize, frames: u32) {
+ let mut flags = Vec::new();
+ if v["visible"] == json!(false) {
+ flags.push("hidden".to_string());
+ }
+ if v["blend"] != json!("normal") {
+ flags.push(v["blend"].as_str().unwrap_or("").to_string());
+ }
+ if let Some(o) = v["opacity"].as_f64().filter(|o| *o < 1.0) {
+ flags.push(format!("{:.0}%", o * 100.0));
+ }
+ ["clip", "lockAlpha", "locked"]
+ .iter()
+ .filter(|k| v[**k] == json!(true))
+ .for_each(|k| flags.push(k.to_string()));
+ let content = match v["kind"].as_str() {
+ Some("paint") => match v["fills"].as_u64() {
+ Some(fills) => format!("{} strokes, {fills} fills", v["strokes"].as_u64().unwrap_or(0)),
+ None => format!("{} strokes", v["strokes"].as_u64().unwrap_or(0)),
+ },
+ Some("vector") => format!("{} nodes", v["nodes"].as_array().map_or(0, Vec::len)),
+ Some("adjust") => v["adjust"]
+ .as_object()
+ .and_then(|m| m.keys().next())
+ .map_or("adjust".into(), |k| klad_core::look::label_of(k).to_string()),
+ _ => format!("{} layers", v["children"].as_array().map_or(0, Vec::len)),
+ };
+ if let Some(list) = v["effects"].as_array() {
+ let names: Vec<&str> = list
+ .iter()
+ .filter_map(|e| e.as_object().and_then(|m| m.keys().next()).map(String::as_str))
+ .collect();
+ flags.push(format!("fx: {}", names.join(" ")));
+ }
+ let cel = if frames > 1 {
+ match v.get("cel") {
+ Some(c) => {
+ let link = c["link"].as_str().map_or(String::new(), |l| format!(" -> {l}"));
+ format!(" {} from {}{link}", c["id"].as_str().unwrap_or(""), c["frame"])
+ }
+ None if v["kind"] != json!("group") && v["kind"] != json!("adjust") => " no cel".into(),
+ None => String::new(),
+ }
+ } else {
+ String::new()
+ };
+ let bounds = serde_json::from_value::<Option<[f32; 4]>>(v["bounds"].clone())
+ .ok()
+ .flatten();
+ let kind = match v["kind"].as_str() {
+ Some("paint") if depth > 0 && v["role"] == json!("mask") => "mask",
+ other => other.unwrap_or(""),
+ };
+ println!(
+ "{:indent$}{:<6} {:<6} {:<16} {:<12} {}{}{}",
+ "",
+ v["id"].as_str().unwrap_or(""),
+ kind,
+ v["name"].as_str().unwrap_or(""),
+ content,
+ fmt_bounds(bounds),
+ if flags.is_empty() {
+ String::new()
+ } else {
+ format!(" {}", flags.join(" "))
+ },
+ cel,
+ indent = depth * 2
+ );
+ if v["mask"].is_object() {
+ print_layer(&v["mask"], depth + 1, frames);
+ }
+ if let Some(nodes) = v["nodes"].as_array() {
+ print_nodes(nodes, depth + 1);
+ }
+ if let Some(children) = v["children"].as_array() {
+ children.iter().rev().for_each(|c| print_layer(c, depth + 1, frames));
+ }
+}
+
+pub fn ls(path: &Path, frame: u32, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let layers = doc
+ .layers
+ .iter()
+ .map(|l| layer_summary(&bundle, l, frame))
+ .collect::<Result<Vec<_>>>()?;
+ if as_json {
+ let value = json!({
+ "canvas": doc.canvas,
+ "timeline": doc.timeline,
+ "rev": doc.rev,
+ "frame": frame,
+ "layers": layers,
+ });
+ println!("{}", serde_json::to_string_pretty(&value)?);
+ return Ok(());
+ }
+ let t = &doc.timeline;
+ let timing = if t.frames > 1 {
+ format!(" {} frames at {} fps, showing frame {frame}", t.frames, t.fps)
+ } else {
+ String::new()
+ };
+ let background = doc
+ .canvas
+ .background
+ .as_deref()
+ .map_or(String::new(), |b| format!(" background {b}"));
+ println!(
+ "{}x{} rev {}{timing}{background}",
+ doc.canvas.width, doc.canvas.height, doc.rev
+ );
+ layers.iter().rev().for_each(|l| print_layer(l, 0, t.frames));
+ Ok(())
+}
+
+pub fn show(path: &Path, id: &str) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ if let Some((cel, mark)) = find_mark(&bundle, id)? {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&crate::marks::mark_json(&cel, &mark))?
+ );
+ return Ok(());
+ }
+ let value = match bundle.doc.item(id).ok_or_else(|| anyhow!("no item {id}"))? {
+ Item::Layer(layer) => serde_json::to_value(layer)?,
+ Item::Cel(layer, cel) => {
+ let mut value = serde_json::to_value(cel)?;
+ if layer.kind() == Kind::Paint {
+ let content = layer.content_of(cel);
+ let (count, bounds) = paint_bounds(&bundle, layer, &content.id)?;
+ put_counts(&mut value, &count);
+ value["bounds"] = json!(bounds);
+ }
+ value
+ }
+ Item::Node(_, _, node) => {
+ let mut value = serde_json::to_value(node)?;
+ value["bounds"] = json!(vector::node_box(node)?);
+ value
+ }
+ };
+ println!("{}", serde_json::to_string_pretty(&value)?);
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn values_parse_as_json_or_strings() {
+ assert_eq!(parse_value("x", "12.5"), json!(12.5));
+ assert_eq!(parse_value("fill", "#336699"), json!("#336699"));
+ assert_eq!(parse_value("name", "42"), json!("42"));
+ assert_eq!(parse_value("pivot", "[1,2]"), json!([1, 2]));
+ assert_eq!(parse_value("visible", "false"), json!(false));
+ }
+
+ #[test]
+ fn dotted_props_nest() {
+ let props = parse_props(&["x=1".into(), "transform.rotate=15".into(), "stroke.width=2".into()]).unwrap();
+ assert_eq!(
+ nest(props),
+ json!({"x": 1, "transform": {"rotate": 15}, "stroke": {"width": 2}})
+ );
+ assert!(parse_props(&["oops".into()]).is_err());
+ }
+
+ #[test]
+ fn add_ops_carry_their_kind() {
+ let op = add_op("layer", &["vector".into(), "name=sky".into()], Place::default()).unwrap();
+ assert!(matches!(op, Op::AddLayer { ref layer, .. } if layer["kind"] == "vector" && layer["name"] == "sky"));
+ let node = add_op("rect", &["w=5".into()], Place::default()).unwrap();
+ assert!(matches!(node, Op::AddNode { ref node, .. } if node["type"] == "rect"));
+ assert!(add_op("layer", &["name=x".into()], Place::default()).is_err());
+ assert!(add_op("cel", &[], Place::default()).is_err());
+ }
+}
diff --git a/crates/cli/src/arcs.rs b/crates/cli/src/arcs.rs
new file mode 100644
index 0000000..6a19c9d
--- /dev/null
+++ b/crates/cli/src/arcs.rs
@@ -0,0 +1,676 @@
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Cel, Document, Kind, Layer, Loc};
+use klad_core::fill::FillSource;
+use klad_core::markedit::{bounds_of, parse_address};
+use klad_core::stroke::{Mark, Sample};
+use klad_core::tween;
+use klad_render::overlay;
+use serde_json::json;
+use std::collections::BTreeMap;
+
+pub const SLACK: f32 = 2.0;
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Track {
+ Mark { cel: String, id: u32 },
+ Part { layer: Option<String>, name: String },
+ Point { x: f32, y: f32 },
+}
+
+impl Track {
+ pub fn parse(text: &str) -> Result<Self> {
+ let text = text.trim();
+ if let Some((cel, id)) = parse_address(text) {
+ return Ok(Track::Mark {
+ cel: cel.to_string(),
+ id,
+ });
+ }
+ if let Some((x, y)) = text.split_once(',') {
+ let (x, y) = (x.trim().parse::<f32>(), y.trim().parse::<f32>());
+ return match (x, y) {
+ (Ok(x), Ok(y)) => Ok(Track::Point { x, y }),
+ _ => bail!("{text:?} is not a point x,y"),
+ };
+ }
+ if text.is_empty() {
+ bail!("a track is a mark (c4:s12), a part (leaf, or lines:leaf) or a point (x,y)");
+ }
+ Ok(match text.split_once(':') {
+ Some((layer, name)) => Track::Part {
+ layer: Some(layer.to_string()),
+ name: name.to_string(),
+ },
+ None => Track::Part {
+ layer: None,
+ name: text.to_string(),
+ },
+ })
+ }
+
+ pub fn label(&self) -> String {
+ match self {
+ Track::Mark { cel, id } => format!("{cel}:s{id}"),
+ Track::Part { layer: Some(l), name } => format!("{l}:{name}"),
+ Track::Part { layer: None, name } => name.clone(),
+ Track::Point { x, y } => format!("{x:.0},{y:.0}"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Spot {
+ pub centre: [f32; 2],
+ pub bottom: [f32; 2],
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Path {
+ pub label: String,
+ pub spots: Vec<(u32, Option<Spot>)>,
+}
+
+#[derive(Default)]
+struct Cache {
+ marks: BTreeMap<(String, String), Vec<Mark>>,
+}
+
+impl Cache {
+ fn marks(&mut self, bundle: &Bundle, layer: &str, cel: &str) -> Result<&Vec<Mark>> {
+ let key = (layer.to_string(), cel.to_string());
+ if !self.marks.contains_key(&key) {
+ let read = bundle.read_marks(layer, cel)?;
+ self.marks.insert(key.clone(), read);
+ }
+ Ok(&self.marks[&key])
+ }
+}
+
+fn points(mark: &Mark) -> Vec<[f32; 2]> {
+ match mark {
+ Mark::Stroke(s) => s.samples.iter().map(Sample::pos).map(|(x, y)| [x, y]).collect(),
+ Mark::Fill(f) => match &f.source {
+ FillSource::Polygon(p) => p.clone(),
+ FillSource::Seed { .. } => f
+ .bounds()
+ .map(|[x0, y0, x1, y1]| vec![[x0, y0], [x1, y1]])
+ .unwrap_or_default(),
+ },
+ }
+}
+
+fn spot_of(marks: &[Mark], ids: &[u32]) -> Option<Spot> {
+ let [x0, y0, x1, y1] = bounds_of(marks, ids)?;
+ let all: Vec<[f32; 2]> = marks
+ .iter()
+ .filter(|m| ids.contains(&m.id()))
+ .flat_map(points)
+ .collect();
+ let low = all.iter().map(|p| p[1]).fold(f32::MIN, f32::max);
+ let sole: Vec<f32> = all.iter().filter(|p| p[1] >= low - 1.0).map(|p| p[0]).collect();
+ (!sole.is_empty()).then(|| Spot {
+ centre: [(x0 + x1) / 2.0, (y0 + y1) / 2.0],
+ bottom: [sole.iter().sum::<f32>() / sole.len() as f32, low],
+ })
+}
+
+fn shown(layer: &Layer, frame: u32) -> Option<&Cel> {
+ let cel = layer.cel_at(frame)?;
+ match &cel.link {
+ Some(source) => layer.cels().iter().find(|c| &c.id == source),
+ None => Some(cel),
+ }
+}
+
+fn paint_layers(doc: &Document) -> Vec<&Layer> {
+ let mut all: Vec<&Layer> = doc
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Paint && l.visible)
+ .collect();
+ all.reverse();
+ all
+}
+
+fn owner_of<'a>(doc: &'a Document, cel: &str) -> Result<&'a Layer> {
+ match doc.locate(cel) {
+ Some(Loc::Cel(path, _)) => Ok(doc.layer_at(&path)),
+ _ => Err(anyhow!("no cel {cel}")),
+ }
+}
+
+fn nearest_mark(bundle: &Bundle, cache: &mut Cache, frame: u32, at: [f32; 2]) -> Result<Option<(String, u32)>> {
+ let mut best: Option<(f32, String, u32)> = None;
+ paint_layers(&bundle.doc).into_iter().try_for_each(|layer| {
+ let Some(cel) = shown(layer, frame) else {
+ return Ok::<_, anyhow::Error>(());
+ };
+ cache
+ .marks(bundle, &layer.id, &cel.id)?
+ .iter()
+ .filter_map(Mark::as_stroke)
+ .for_each(|s| {
+ let d = s
+ .samples
+ .iter()
+ .map(|q| {
+ let (x, y) = q.pos();
+ (x - at[0]).hypot(y - at[1])
+ })
+ .fold(f32::MAX, f32::min);
+ if best.as_ref().is_none_or(|b| d < b.0) {
+ best = Some((d, layer.id.clone(), s.id));
+ }
+ });
+ Ok(())
+ })?;
+ Ok(best.map(|(_, layer, id)| (layer, id)))
+}
+
+pub fn track(bundle: &Bundle, tracks: &[Track], (from, to): (u32, u32)) -> Result<Vec<Path>> {
+ let doc = &bundle.doc;
+ let mut cache = Cache::default();
+ tracks
+ .iter()
+ .map(|t| {
+ let spots = match t {
+ Track::Mark { cel, id } => {
+ let layer = owner_of(doc, cel)?;
+ (from..=to)
+ .map(|f| {
+ let spot = match shown(layer, f) {
+ Some(c) => spot_of(cache.marks(bundle, &layer.id, &c.id)?, &[*id]),
+ None => None,
+ };
+ Ok((f, spot))
+ })
+ .collect::<Result<Vec<_>>>()?
+ }
+ Track::Part { layer, name } => {
+ let candidates: Vec<&Layer> = match layer {
+ Some(key) => vec![doc.find_layer(key)?],
+ None => paint_layers(doc),
+ };
+ (from..=to)
+ .map(|f| {
+ let found = candidates
+ .iter()
+ .find_map(|l| shown(l, f).and_then(|c| c.parts.get(name).map(|ids| (l, c, ids))));
+ let spot = match found {
+ Some((l, c, ids)) => spot_of(cache.marks(bundle, &l.id, &c.id)?, ids),
+ None => None,
+ };
+ Ok((f, spot))
+ })
+ .collect::<Result<Vec<_>>>()?
+ }
+ Track::Point { x, y } => {
+ let Some((layer_id, id)) = nearest_mark(bundle, &mut cache, from, [*x, *y])? else {
+ bail!("frame {from} shows no strokes to carry the point {x},{y}");
+ };
+ let layer = doc.layer(&layer_id).ok_or_else(|| anyhow!("no layer {layer_id}"))?;
+ let line_at = |cache: &mut Cache, f: u32| -> Result<Option<Vec<(f32, f32)>>> {
+ Ok(match shown(layer, f) {
+ Some(c) => cache
+ .marks(bundle, &layer.id, &c.id)?
+ .iter()
+ .filter_map(Mark::as_stroke)
+ .find(|s| s.id == id)
+ .map(tween::line_of),
+ None => None,
+ })
+ };
+ let first = line_at(&mut cache, from)?.unwrap_or_default();
+ let anchor = tween::anchor(&[first], (*x, *y));
+ (from..=to)
+ .map(|f| {
+ let line = line_at(&mut cache, f)?;
+ let at =
+ anchor
+ .as_ref()
+ .zip(line)
+ .and_then(|(a, l)| tween::place(a, &[l]))
+ .map(|(x, y)| Spot {
+ centre: [x, y],
+ bottom: [x, y],
+ });
+ Ok((f, at))
+ })
+ .collect::<Result<Vec<_>>>()?
+ }
+ };
+ Ok(Path {
+ label: t.label(),
+ spots,
+ })
+ })
+ .collect()
+}
+
+fn moved(path: &Path) -> Vec<(u32, f32)> {
+ path.spots
+ .windows(2)
+ .filter_map(|w| match (w[0].1, w[1].1) {
+ (Some(a), Some(b)) => Some((w[1].0, (b.centre[0] - a.centre[0]).hypot(b.centre[1] - a.centre[1]))),
+ _ => None,
+ })
+ .collect()
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Ground {
+ pub under: Vec<(u32, f32)>,
+ pub slides: Vec<(u32, u32, f32)>,
+ pub touches: Vec<u32>,
+}
+
+pub fn ground(path: &Path, y: f32, travel: f32, slack: f32) -> Ground {
+ let touching = |s: &Spot| (s.bottom[1] - y).abs() <= slack;
+ let changes: Vec<(u32, Spot)> = path.spots.iter().filter_map(|(f, s)| s.map(|s| (*f, s))).fold(
+ Vec::new(),
+ |mut out: Vec<(u32, Spot)>, (f, s)| {
+ if out
+ .last()
+ .is_none_or(|(_, last)| last.bottom != s.bottom || last.centre != s.centre)
+ {
+ out.push((f, s));
+ }
+ out
+ },
+ );
+ Ground {
+ under: path
+ .spots
+ .iter()
+ .filter_map(|(f, s)| s.filter(|s| s.bottom[1] > y + slack).map(|s| (*f, s.bottom[1] - y)))
+ .collect(),
+ touches: path
+ .spots
+ .iter()
+ .filter(|(_, s)| s.as_ref().is_some_and(touching))
+ .map(|(f, _)| *f)
+ .collect(),
+ slides: changes
+ .windows(2)
+ .filter_map(|w| {
+ let ((fa, a), (fb, b)) = (w[0], w[1]);
+ let expected = -travel * (fb - fa) as f32;
+ let off = (b.bottom[0] - a.bottom[0] - expected).abs();
+ (touching(&a) && touching(&b) && off > slack).then_some((fa, fb, off))
+ })
+ .collect(),
+ }
+}
+
+pub fn swaps(paths: &[Path]) -> Vec<(usize, usize, u32, u32)> {
+ (0..paths.len())
+ .flat_map(|i| (i + 1..paths.len()).map(move |j| (i, j)))
+ .flat_map(|(i, j)| {
+ let side: Vec<(u32, f32)> = paths[i]
+ .spots
+ .iter()
+ .zip(&paths[j].spots)
+ .filter_map(|((f, a), (_, b))| match (a, b) {
+ (Some(a), Some(b)) if (a.bottom[0] - b.bottom[0]).abs() > SLACK => {
+ Some((*f, (a.bottom[0] - b.bottom[0]).signum()))
+ }
+ _ => None,
+ })
+ .collect();
+ side.windows(2)
+ .filter(|w| w[0].1 != w[1].1)
+ .map(|w| (i, j, w[0].0, w[1].0))
+ .collect::<Vec<_>>()
+ })
+ .collect()
+}
+
+pub fn range(doc: &Document, frame: u32, from: Option<u32>, to: Option<u32>) -> (u32, u32) {
+ let whole = doc
+ .timeline
+ .clip_at(frame)
+ .map_or((0, doc.timeline.frames.saturating_sub(1)), |c| (c.from, c.to));
+ (
+ from.unwrap_or(whole.0),
+ to.unwrap_or(whole.1).min(doc.timeline.frames.saturating_sub(1)),
+ )
+}
+
+pub fn arcs_overlay(paths: &[Path]) -> Vec<overlay::Arc> {
+ paths
+ .iter()
+ .map(|p| overlay::Arc {
+ label: p.label.clone(),
+ points: p.spots.iter().filter_map(|(f, s)| s.map(|s| (*f, s.centre))).collect(),
+ })
+ .collect()
+}
+
+pub fn part_marks(bundle: &Bundle, frame: u32) -> Result<Vec<overlay::Mark>> {
+ let mut cache = Cache::default();
+ let mut out = Vec::new();
+ paint_layers(&bundle.doc).into_iter().try_for_each(|layer| {
+ let Some(cel) = shown(layer, frame) else {
+ return Ok::<_, anyhow::Error>(());
+ };
+ let marks = cache.marks(bundle, &layer.id, &cel.id)?;
+ cel.parts.iter().for_each(|(name, ids)| {
+ if let Some([x0, y0, x1, y1]) = bounds_of(marks, ids) {
+ out.push(overlay::Mark {
+ label: format!("{name} ({})", layer.name),
+ rect: [x0, y0, x1 - x0, y1 - y0],
+ });
+ }
+ });
+ Ok(())
+ })?;
+ Ok(out)
+}
+
+pub struct Checks {
+ pub ground: Vec<f32>,
+ pub travel: f32,
+ pub slack: f32,
+ pub json: bool,
+ pub check: bool,
+}
+
+pub fn report(bundle: &Bundle, tracks: &[Track], span: (u32, u32), checks: &Checks) -> Result<()> {
+ let paths = track(bundle, tracks, span)?;
+ let lines: Vec<Option<f32>> = match checks.ground.len() {
+ 0 => vec![None; paths.len()],
+ 1 => vec![Some(checks.ground[0]); paths.len()],
+ n if n == paths.len() => checks.ground.iter().copied().map(Some).collect(),
+ n => bail!(
+ "{n} ground lines for {} tracks: give one for all, or one per track",
+ paths.len()
+ ),
+ };
+ let grounds: Vec<Option<Ground>> = paths
+ .iter()
+ .zip(&lines)
+ .map(|(p, y)| y.map(|y| ground(p, y, checks.travel, checks.slack)))
+ .collect();
+ let crossed = swaps(&paths);
+ let wrong: Vec<String> = grounds
+ .iter()
+ .zip(&paths)
+ .flat_map(|(g, p)| {
+ g.iter().flat_map(move |g| {
+ g.under
+ .iter()
+ .map(move |(f, d)| format!("{} under the ground at {f} by {d:.1} px", p.label))
+ .chain(
+ g.slides
+ .iter()
+ .map(move |(a, b, d)| format!("{} slides {d:.1} px from {a} to {b}", p.label)),
+ )
+ })
+ })
+ .chain(crossed.iter().map(|(i, j, a, b)| {
+ format!(
+ "{} and {} swap sides between {a} and {b}",
+ paths[*i].label, paths[*j].label
+ )
+ }))
+ .collect();
+ let as_json = checks.json;
+ if as_json {
+ let tracks: Vec<serde_json::Value> = paths
+ .iter()
+ .zip(&grounds)
+ .map(|(p, g)| {
+ let steps: BTreeMap<u32, f32> = moved(p).into_iter().collect();
+ json!({
+ "track": p.label,
+ "frames": p.spots.iter().map(|(f, s)| json!({
+ "frame": f,
+ "at": s.map(|s| s.centre),
+ "bottom": s.map(|s| s.bottom),
+ "moved": steps.get(f),
+ })).collect::<Vec<_>>(),
+ "under": g.as_ref().map(|g| g.under.iter().map(|(f, d)| json!({"frame": f, "by": d})).collect::<Vec<_>>()),
+ "slides": g.as_ref().map(|g| g.slides.iter().map(|(a, b, d)| json!({"from": a, "to": b, "by": d})).collect::<Vec<_>>()),
+ "touches": g.as_ref().map(|g| g.touches.clone()),
+ })
+ })
+ .collect();
+ let swaps: Vec<serde_json::Value> = crossed
+ .iter()
+ .map(|(i, j, a, b)| json!({"tracks": [paths[*i].label, paths[*j].label], "between": [a, b]}))
+ .collect();
+ println!(
+ "{}",
+ json!({"from": span.0, "to": span.1, "ground": checks.ground, "travel": checks.travel, "tracks": tracks, "swaps": swaps, "wrong": wrong})
+ );
+ } else {
+ print_paths(&paths, &grounds, &crossed);
+ }
+ if checks.check && !wrong.is_empty() {
+ bail!("the arcs show {}: {}", wrong.len(), wrong.join("; "));
+ }
+ Ok(())
+}
+
+fn print_paths(paths: &[Path], grounds: &[Option<Ground>], crossed: &[(usize, usize, u32, u32)]) {
+ paths.iter().zip(grounds).for_each(|(p, g)| {
+ println!("{}", p.label);
+ let steps: BTreeMap<u32, f32> = moved(p).into_iter().collect();
+ p.spots.iter().for_each(|(f, s)| match s {
+ Some(s) => println!(
+ " {f:>4} {:>7.1},{:>7.1} moved {:>6} bottom {:.0},{:.0}",
+ s.centre[0],
+ s.centre[1],
+ steps.get(f).map_or("-".to_string(), |d| format!("{d:.1}")),
+ s.bottom[0],
+ s.bottom[1]
+ ),
+ None => println!(" {f:>4} not shown"),
+ });
+ if let Some(g) = g {
+ let frames = |list: Vec<String>| {
+ if list.is_empty() {
+ "none".to_string()
+ } else {
+ list.join(", ")
+ }
+ };
+ println!(
+ " under the ground: {}",
+ frames(g.under.iter().map(|(f, d)| format!("{f} ({d:.1} px)")).collect())
+ );
+ println!(
+ " slides on the ground: {}",
+ frames(
+ g.slides
+ .iter()
+ .map(|(a, b, d)| format!("{a} to {b} ({d:.1} px)"))
+ .collect()
+ )
+ );
+ println!(
+ " on the ground: {}",
+ frames(g.touches.iter().map(u32::to_string).collect())
+ );
+ }
+ });
+ crossed.iter().for_each(|(i, j, a, b)| {
+ println!(
+ "{} and {} swap sides between frames {a} and {b}",
+ paths[*i].label, paths[*j].label
+ );
+ });
+ if crossed.is_empty() && paths.len() > 1 {
+ println!("no tracks swap sides");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn path(label: &str, at: &[(f32, f32)]) -> Path {
+ Path {
+ label: label.into(),
+ spots: at
+ .iter()
+ .enumerate()
+ .map(|(f, &(x, y))| {
+ (
+ f as u32,
+ Some(Spot {
+ centre: [x, y - 10.0],
+ bottom: [x, y],
+ }),
+ )
+ })
+ .collect(),
+ }
+ }
+
+ fn walk(name: &str) -> (std::path::PathBuf, Bundle) {
+ use klad_core::doc::{Document, Layer};
+ let dir = std::env::temp_dir().join(format!("draw-arcs-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(400, 300);
+ doc.timeline.frames = 4;
+ let mut lines = Layer::paint("lines", "lines", "k0");
+ lines.cels_mut().unwrap()[0].hold = Some(1);
+ doc.layers = vec![lines];
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let foot = |x: f32, bottom: f32, frame: u32, part: &str| {
+ format!(
+ r#"{{"op":"stroke","layer":"lines","frame":{frame},"size":4,"part":"{part}","path":"M{x} {} L{x} {bottom} L{} {bottom}"}}"#,
+ bottom - 60.0,
+ x + 20.0
+ )
+ };
+ let near = [(100.0, 250.0), (140.0, 250.0), (180.0, 256.0), (220.0, 250.0)];
+ let far = [(200.0, 250.0), (170.0, 250.0), (140.0, 230.0), (110.0, 230.0)];
+ let text: Vec<String> = (0..4u32)
+ .flat_map(|f| {
+ let new = (f > 0).then(|| format!(r#"{{"op":"cel","new":"lines","frame":{f},"hold":1,"id":"k{f}"}}"#));
+ new.into_iter().chain([
+ foot(near[f as usize].0, near[f as usize].1, f, "near foot"),
+ foot(far[f as usize].0, far[f as usize].1, f, "far foot"),
+ ])
+ })
+ .collect();
+ bundle
+ .apply(&klad_core::ops::parse_lines(&text.join("\n")).unwrap())
+ .unwrap();
+ (dir, bundle)
+ }
+
+ #[test]
+ fn a_walk_whose_feet_cross_is_caught_with_its_contacts_and_slides() {
+ let (dir, bundle) = walk("cross");
+ let tracks = [Track::parse("near foot").unwrap(), Track::parse("far foot").unwrap()];
+ let paths = track(&bundle, &tracks, (0, 3)).unwrap();
+ let sole = paths[0].spots[1].1.unwrap().bottom;
+ assert!(
+ (sole[0] - 150.0).abs() < 2.0 && (sole[1] - 250.0).abs() < 0.5,
+ "{sole:?}"
+ );
+ assert_eq!(swaps(&paths), [(0, 1, 1, 2)]);
+ let near = ground(&paths[0], 250.0, 0.0, SLACK);
+ assert_eq!(near.under.iter().map(|u| u.0).collect::<Vec<_>>(), [2]);
+ assert_eq!(near.touches, [0, 1, 3]);
+ assert_eq!(near.slides.iter().map(|s| (s.0, s.1)).collect::<Vec<_>>(), [(0, 1)]);
+ let far = ground(&paths[1], 250.0, 0.0, SLACK);
+ assert_eq!(far.touches, [0, 1]);
+ assert!(far.under.is_empty());
+ let mark = track(&bundle, &[Track::parse("k0:s1").unwrap()], (0, 3)).unwrap();
+ assert!(mark[0].spots.iter().all(|(_, s)| s.is_some()));
+ let point = track(&bundle, &[Track::parse("100,220").unwrap()], (0, 3)).unwrap();
+ let at = |f: usize| point[0].spots[f].1.unwrap().centre;
+ assert!(
+ (at(0)[0] - 100.0).abs() < 1.0 && (at(0)[1] - 220.0).abs() < 1.0,
+ "{:?}",
+ at(0)
+ );
+ assert!(
+ (at(1)[0] - 140.0).abs() < 1.0 && (at(1)[1] - 220.0).abs() < 1.0,
+ "{:?}",
+ at(1)
+ );
+ let parts = part_marks(&bundle, 2).unwrap();
+ assert_eq!(parts.len(), 2);
+ assert!(parts.iter().any(|m| m.label.starts_with("near foot")));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn tracks_parse_as_marks_parts_and_points() {
+ assert_eq!(
+ Track::parse("c4:s12").unwrap(),
+ Track::Mark {
+ cel: "c4".into(),
+ id: 12
+ }
+ );
+ assert_eq!(Track::parse("320,410").unwrap(), Track::Point { x: 320.0, y: 410.0 });
+ assert_eq!(
+ Track::parse("lines:near leg").unwrap(),
+ Track::Part {
+ layer: Some("lines".into()),
+ name: "near leg".into()
+ }
+ );
+ assert_eq!(
+ Track::parse("leaf").unwrap(),
+ Track::Part {
+ layer: None,
+ name: "leaf".into()
+ }
+ );
+ assert!(Track::parse("3,x").is_err());
+ }
+
+ #[test]
+ fn the_ground_check_finds_feet_under_it_and_sliding_on_it() {
+ let foot = path(
+ "foot",
+ &[
+ (100.0, 600.0),
+ (104.0, 600.0),
+ (104.5, 601.0),
+ (110.0, 590.0),
+ (112.0, 607.0),
+ ],
+ );
+ let g = ground(&foot, 600.0, 0.0, SLACK);
+ assert_eq!(g.touches, [0, 1, 2]);
+ assert_eq!(g.slides.len(), 1);
+ assert_eq!((g.slides[0].0, g.slides[0].1), (0, 1));
+ let walking = path(
+ "foot",
+ &[
+ (100.0, 600.0),
+ (100.0, 600.0),
+ (86.0, 600.0),
+ (79.0, 601.0),
+ (80.0, 600.0),
+ ],
+ );
+ let w = ground(&walking, 600.0, 7.0, SLACK);
+ assert_eq!(w.slides.iter().map(|s| (s.0, s.1)).collect::<Vec<_>>(), [(3, 4)]);
+ assert_eq!(g.under.len(), 1);
+ assert_eq!(g.under[0].0, 4);
+ assert!(moved(&foot)[0].1 > 3.9);
+ }
+
+ #[test]
+ fn crossing_feet_are_reported_once_per_crossing() {
+ let near = path(
+ "near",
+ &[(100.0, 600.0), (120.0, 600.0), (160.0, 600.0), (180.0, 600.0)],
+ );
+ let far = path("far", &[(170.0, 600.0), (150.0, 600.0), (130.0, 600.0), (110.0, 600.0)]);
+ assert_eq!(swaps(&[near.clone(), far]), [(0, 1, 1, 2)]);
+ let apart = path("far", &[(300.0, 600.0), (300.0, 600.0), (300.0, 600.0), (300.0, 600.0)]);
+ assert!(swaps(&[near, apart]).is_empty());
+ }
+}
diff --git a/crates/cli/src/bench.rs b/crates/cli/src/bench.rs
new file mode 100644
index 0000000..8b5c601
--- /dev/null
+++ b/crates/cli/src/bench.rs
@@ -0,0 +1,230 @@
+use crate::layers::compress_raster;
+use anyhow::Result;
+use klad_brush::{BrushSet, Raster, StrokeBuffer, draw_stroke, replay};
+use klad_core::doc::{Document, Layer, Node, Shape};
+use klad_core::rng::Rng;
+use klad_core::stroke::{Mark, Stroke, decode_cel, encode_cel, encode_raw, marks};
+use klad_core::synth::{Gesture, Synth};
+use klad_render::{View, compose};
+use rayon::prelude::*;
+use std::collections::BTreeMap;
+use std::time::Instant;
+
+fn ms(start: Instant) -> f64 {
+ start.elapsed().as_secs_f64() * 1000.0
+}
+
+fn mb(bytes: usize) -> String {
+ format!("{:.1} MB", bytes as f64 / 1_048_576.0)
+}
+
+pub fn run(count: usize, size: u32, seed: u64) -> Result<()> {
+ let brushes = BrushSet::presets();
+ let strokes = Synth::canvas(size as f32, size as f32).strokes(count, seed);
+ stroke_format(&strokes)?;
+ brush_speed(&brushes)?;
+ repaint_speed(&brushes)?;
+ replay_speed(&strokes, size, &brushes)?;
+ compose_speed(&brushes, seed)?;
+ Ok(())
+}
+
+fn stroke_format(strokes: &[Stroke]) -> Result<()> {
+ let samples: usize = strokes.iter().map(|s| s.samples.len()).sum();
+ let start = Instant::now();
+ let all = marks(strokes.iter().cloned());
+ let raw = encode_raw(&all);
+ let packed = encode_cel(&all)?;
+ let encode = ms(start);
+ let start = Instant::now();
+ let back = decode_cel(&packed)?;
+ let decode = ms(start);
+ assert_eq!(back.len(), strokes.len());
+ println!(
+ "stroke format {} strokes, {:.1} samples each at 200 Hz",
+ strokes.len(),
+ samples as f64 / strokes.len() as f64
+ );
+ println!(" plain f32 {} (24 B per sample)", mb(samples * 24));
+ println!(" delta varint {}", mb(raw.len()));
+ println!(
+ " zstd {} = {:.0} B per stroke, {:.2} B per sample",
+ mb(packed.len()),
+ packed.len() as f64 / strokes.len() as f64,
+ packed.len() as f64 / samples as f64
+ );
+ println!(" encode {encode:.1} ms, decode {decode:.1} ms");
+ Ok(())
+}
+
+fn brush_speed(brushes: &BrushSet) -> Result<()> {
+ println!("brush speed one 1000 px stroke at pressure 0.8");
+ ["pencil", "ink", "soft", "chalk"].iter().try_for_each(|name| {
+ [10.0f32, 60.0, 300.0].iter().try_for_each(|&size| {
+ let mut rng = Rng::new(3);
+ let gesture = Gesture {
+ start: (500.0, 1000.0),
+ heading: 0.0,
+ length: 1000.0,
+ speed: 1000.0,
+ curl: 1.0,
+ pressure: 0.8,
+ attack: 0.01,
+ release: 0.01,
+ tilt: (0.0, 0.0),
+ };
+ let mut stroke = Stroke::new(1, name, [0.2, 0.2, 0.2, 1.0], size, 5);
+ stroke.samples = gesture.samples(200.0, &mut rng);
+ let reps = if size >= 300.0 { 3 } else { 20 };
+ let start = Instant::now();
+ let dabs: usize = (0..reps)
+ .map(|_| replay(2048, 2048, &[Mark::Stroke(stroke.clone())], brushes).map(|r| r.dabs))
+ .sum::<Result<usize>>()?;
+ let per = ms(start) / reps as f64;
+ println!(
+ " {name:<7}{size:>4} px {per:>7.2} ms {:>5} dabs {:>7.0} dabs/s",
+ dabs / reps,
+ (dabs / reps) as f64 / (per / 1000.0)
+ );
+ Ok(())
+ })
+ })
+}
+
+fn repaint_speed(brushes: &BrushSet) -> Result<()> {
+ println!("pen-up repaint a tapered ink stroke is drawn again at pen up so its end can taper");
+ let ink = brushes.get("ink")?;
+ let mut buffer = StrokeBuffer::new(2048, 2048);
+ [(1000.0f32, 12.0f32), (1000.0, 60.0), (3000.0, 12.0), (3000.0, 400.0)]
+ .iter()
+ .for_each(|&(length, size)| {
+ let mut rng = Rng::new(4);
+ let gesture = Gesture {
+ start: (1024.0, 1024.0),
+ heading: 0.3,
+ length,
+ speed: 400.0,
+ curl: 4.0,
+ pressure: 0.8,
+ attack: 0.05,
+ release: 0.1,
+ tilt: (0.0, 0.0),
+ };
+ let mut stroke = Stroke::new(1, "ink", [0.1, 0.1, 0.1, 1.0], size, 5).tapered(ink.def.taper);
+ stroke.samples = gesture.samples(220.0, &mut rng);
+ let reps = 5;
+ let start = Instant::now();
+ (0..reps).for_each(|_| {
+ buffer.reset();
+ draw_stroke(&mut buffer, ink, &stroke);
+ });
+ println!(
+ " {length:>5.0} px line at {size:>4} px {:>7.2} ms ({} samples)",
+ ms(start) / reps as f64,
+ stroke.samples.len()
+ );
+ });
+ Ok(())
+}
+
+fn replay_layers(layers: &[Vec<Stroke>], size: u32, brushes: &BrushSet, threads: usize) -> Result<(Vec<Raster>, f64)> {
+ let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build()?;
+ let start = Instant::now();
+ let rasters = pool.install(|| {
+ layers
+ .par_iter()
+ .map(|l| replay(size, size, &marks(l.iter().cloned()), brushes).map(|r| r.raster))
+ .collect::<Result<Vec<_>>>()
+ })?;
+ Ok((rasters, ms(start)))
+}
+
+fn replay_speed(strokes: &[Stroke], size: u32, brushes: &BrushSet) -> Result<()> {
+ let start = Instant::now();
+ let single = replay(size, size, &marks(strokes.iter().cloned()), brushes)?;
+ let one_layer = ms(start);
+ println!(
+ "replay {} strokes on one {size}x{size} layer: {:.2} s, {} dabs, {} tiles, {}",
+ strokes.len(),
+ one_layer / 1000.0,
+ single.dabs,
+ single.raster.count(),
+ mb(single.raster.bytes())
+ );
+ let start = Instant::now();
+ let packed = compress_raster(&single.raster)?;
+ let write = ms(start);
+ let start = Instant::now();
+ let restored = Raster::decode(&zstd::decode_all(&packed[..])?)?;
+ let read = ms(start);
+ println!(
+ " tile cache {} compressed, write {write:.0} ms, read {read:.0} ms, intact {}",
+ mb(packed.len()),
+ restored.hash() == single.raster.hash()
+ );
+ let layers: Vec<Vec<Stroke>> = (0..8)
+ .map(|k| strokes.iter().skip(k).step_by(8).cloned().collect())
+ .collect();
+ let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
+ let (serial, serial_ms) = replay_layers(&layers, size, brushes, 1)?;
+ let (parallel, parallel_ms) = replay_layers(&layers, size, brushes, threads)?;
+ let same = serial.iter().zip(&parallel).all(|(a, b)| a.hash() == b.hash());
+ println!(
+ " as 8 layers 1 thread {:.2} s, {threads} threads {:.2} s, identical pixels {same}",
+ serial_ms / 1000.0,
+ parallel_ms / 1000.0
+ );
+ Ok(())
+}
+
+fn compose_speed(brushes: &BrushSet, seed: u64) -> Result<()> {
+ let size = 2048u32;
+ let synth = Synth::canvas(size as f32, size as f32);
+ let layers: Vec<Vec<Stroke>> = (0..8).map(|k| synth.strokes(1500, seed + 100 + k)).collect();
+ let (rasters, _) = replay_layers(&layers, size, brushes, 8)?;
+ let mut doc = Document::new(size, size);
+ let background = Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 2048.0,
+ h: 2048.0,
+ radius: 0.0,
+ };
+ doc.layers.push(Layer::vector(
+ "bg",
+ "bg",
+ "bgc",
+ vec![Node::new("n1", background).filled("#203040")],
+ ));
+ doc.layers
+ .extend((0..8).map(|k| Layer::paint(&format!("p{k}"), "paint", &format!("pc{k}"))));
+ let hill = Shape::Path {
+ d: "M0 2048 L0 1600 C 600 1400 1400 1800 2048 1500 L2048 2048 Z".into(),
+ };
+ doc.layers.push(Layer::vector(
+ "fg",
+ "fg",
+ "fgc",
+ vec![Node::new("n2", hill).filled("#101820")],
+ ));
+ let map: BTreeMap<String, Raster> = rasters
+ .into_iter()
+ .enumerate()
+ .map(|(k, r)| (format!("pc{k}"), r))
+ .collect();
+ [1.0f32, 0.375].iter().try_for_each(|&scale| {
+ let start = Instant::now();
+ let mut frame = compose(&doc, 0, &map, View::scaled(scale))?;
+ let composed = ms(start);
+ let start = Instant::now();
+ let png = frame.png()?;
+ println!(
+ "compose 10 layers {size}x{size} at {scale}: {composed:.0} ms, PNG {:.0} ms ({}), out {}x{}",
+ ms(start),
+ mb(png.len()),
+ frame.width,
+ frame.height
+ );
+ Ok(())
+ })
+}
diff --git a/crates/cli/src/brushes.rs b/crates/cli/src/brushes.rs
new file mode 100644
index 0000000..9a754f3
--- /dev/null
+++ b/crates/cli/src/brushes.rs
@@ -0,0 +1,174 @@
+use anyhow::{Result, anyhow};
+use klad_core::brushes::{self, BrushDef, Curve, TipDef};
+use klad_core::bundle::Bundle;
+use serde_json::json;
+use std::path::Path;
+
+struct Listed {
+ id: String,
+ source: &'static str,
+ def: BrushDef,
+}
+
+fn listed(bundle: Option<&Bundle>) -> Result<Vec<Listed>> {
+ let embedded = bundle.map(Bundle::brushes).transpose()?.unwrap_or_default();
+ let in_bundle = embedded.iter().map(|(id, def)| Listed {
+ id: id.clone(),
+ source: match brushes::library(id) {
+ Some(lib) if &lib == def => "bundle",
+ Some(_) => "bundle, differs from library",
+ None => "bundle only",
+ },
+ def: def.clone(),
+ });
+ let library = brushes::library_ids()
+ .into_iter()
+ .filter(|id| !embedded.contains_key(*id))
+ .filter_map(|id| {
+ brushes::library(id).map(|def| Listed {
+ id: id.to_string(),
+ source: "library",
+ def,
+ })
+ });
+ Ok(in_bundle.chain(library).collect())
+}
+
+fn curve(c: Option<Curve>) -> String {
+ c.map_or("-".into(), |c| {
+ let gamma = if c.gamma == 1.0 {
+ String::new()
+ } else {
+ format!(" ^{}", c.gamma)
+ };
+ format!("{}..{}{gamma}", c.min, c.max)
+ })
+}
+
+fn tip(def: &BrushDef) -> String {
+ let main = match &def.tip {
+ TipDef::Round { hardness } => format!("round {hardness}"),
+ TipDef::Chalk { seed } => format!("chalk {seed}"),
+ TipDef::Image { image } => image.clone(),
+ };
+ let extras: Vec<&str> = [
+ (def.dual.is_some(), "dual"),
+ (def.grain.is_some(), "texture"),
+ (def.color.is_some(), "colour"),
+ (matches!(def.paint, Some(brushes::PaintDef::Wet { .. })), "wet"),
+ (matches!(def.paint, Some(brushes::PaintDef::Smudge { .. })), "smudge"),
+ (matches!(def.paint, Some(brushes::PaintDef::Blend { .. })), "blend"),
+ ]
+ .iter()
+ .filter(|(on, _)| *on)
+ .map(|(_, word)| *word)
+ .collect();
+ match extras.is_empty() {
+ true => main,
+ false => format!("{main} +{}", extras.join("+")),
+ }
+}
+
+pub fn set(bundle: &Path, id: &str, file: &Path) -> Result<()> {
+ let bundle = Bundle::open(bundle)?;
+ let text = match file.to_str() {
+ Some("-") => std::io::read_to_string(std::io::stdin())?,
+ _ => std::fs::read_to_string(file)?,
+ };
+ let def = BrushDef::parse(&text)?;
+ let set = klad_brush::BrushSet::for_bundle(&bundle)?;
+ let missing: Vec<&str> = def
+ .images()
+ .into_iter()
+ .filter(|name| !set.pictures().contains_key(*name))
+ .collect();
+ if !missing.is_empty() {
+ anyhow::bail!(
+ "brush {id} uses pictures not in the bundle: {} (add them with klad brushes {} --picture <name> <file.png>)",
+ missing.join(", "),
+ bundle.root.display()
+ );
+ }
+ match bundle.brush(id)? {
+ Some(known) if known == def => println!("brush {id} is already in the bundle as given"),
+ Some(_) => anyhow::bail!(
+ "brush {id} is in use with other settings; strokes keep their brush, so give the new one another id"
+ ),
+ None => {
+ bundle.embed_brush(id, &def)?;
+ println!("brush {id} added to the bundle");
+ }
+ }
+ Ok(())
+}
+
+pub fn picture(bundle: &Path, name: &str, file: &Path) -> Result<()> {
+ let bundle = Bundle::open(bundle)?;
+ brushes::valid_image(name)?;
+ let bytes = std::fs::read(file)?;
+ let picture = klad_brush::images::decode(&bytes)?;
+ let path = bundle.root.join("brushes").join("images").join(format!("{name}.png"));
+ if path.exists() {
+ match std::fs::read(&path)? == bytes {
+ true => println!("picture {name} is already in the bundle"),
+ false => anyhow::bail!(
+ "picture {name} is in the bundle already with other pixels; brushes using it would change, so give it another name"
+ ),
+ }
+ return Ok(());
+ }
+ std::fs::create_dir_all(path.parent().expect("a folder"))?;
+ klad_core::bundle::write_atomic(&path, &bytes)?;
+ println!(
+ "picture {name} ({}x{}) added to the bundle's brushes/images",
+ picture.width, picture.height
+ );
+ Ok(())
+}
+
+pub fn list(bundle: Option<&Path>, show: Option<&str>, as_json: bool) -> Result<()> {
+ let opened = bundle.map(Bundle::open).transpose()?;
+ let all = listed(opened.as_ref())?;
+ if let Some(id) = show {
+ let found = all.iter().find(|l| l.id == id).ok_or_else(|| {
+ let ids: Vec<&str> = all.iter().map(|l| l.id.as_str()).collect();
+ anyhow!("no brush {id:?}: brushes are {}", ids.join(", "))
+ })?;
+ print!("{}", found.def.to_json()?);
+ return Ok(());
+ }
+ if as_json {
+ let list: Vec<serde_json::Value> = all
+ .iter()
+ .map(|l| json!({ "id": l.id, "source": l.source, "brush": l.def }))
+ .collect();
+ println!("{}", serde_json::Value::Array(list));
+ return Ok(());
+ }
+ println!(
+ "{:<16} {:<12} {:<11} {:>7} {:<16} {:>5} {:>8} {:>7} {:>8} source",
+ "id", "name", "tip", "spacing", "size by pressure", "flow", "taper", "stab ms", "smooth"
+ );
+ all.iter().for_each(|l| {
+ let d = &l.def;
+ let erase = if d.blend == brushes::BrushBlend::Erase {
+ " (erases)"
+ } else {
+ ""
+ };
+ println!(
+ "{:<16} {:<12} {:<11} {:>7} {:<16} {:>5} {:>8} {:>7} {:>8} {}{erase}",
+ l.id,
+ d.name,
+ tip(d),
+ d.spacing,
+ curve(d.dynamics.size.pressure),
+ d.flow,
+ format!("{},{}", d.taper[0], d.taper[1]),
+ d.stabilizer,
+ d.smoothing,
+ l.source
+ );
+ });
+ Ok(())
+}
diff --git a/crates/cli/src/colour.rs b/crates/cli/src/colour.rs
new file mode 100644
index 0000000..2cbe928
--- /dev/null
+++ b/crates/cli/src/colour.rs
@@ -0,0 +1,571 @@
+use crate::agent::Output;
+use crate::layers::{self, Vectors};
+use anyhow::{Result, anyhow, bail};
+use klad_brush::{BrushSet, Raster, carry_seed, flood, paint_fill, regions, replay, replay_onto, sample};
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Document, Kind};
+use klad_core::fill::{Fill, FillRef, FillSource};
+use klad_core::markedit::address;
+use klad_core::ops::FillSpec;
+use klad_core::stroke::{Author, Mark, next_id};
+use klad_render::{Rasters, View, compose, fill_reference};
+use rayon::prelude::*;
+use serde_json::json;
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+pub fn needs_vectors(doc: &Document, reference: Option<&FillRef>) -> bool {
+ match reference {
+ Some(FillRef::All) => true,
+ Some(FillRef::Layer(id)) => doc.layer(id).is_some_and(|l| l.kind() != Kind::Paint),
+ _ => false,
+ }
+}
+
+pub fn seed_colours(
+ bundle: &Bundle,
+ cel: &str,
+ frame: u32,
+ marks: &[Mark],
+ ids: &[u32],
+ brushes: &BrushSet,
+) -> Result<BTreeMap<u32, [f32; 4]>> {
+ let doc = &bundle.doc;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let mut rasters = layers::load(bundle, frame, brushes, true)?.rasters;
+ if marks
+ .iter()
+ .filter_map(Mark::as_fill)
+ .any(|f| ids.contains(&f.id) && needs_vectors(doc, f.reference()))
+ {
+ Vectors::default().add_to(doc, frame, &mut rasters)?;
+ }
+ let mut own = Raster::new(w, h);
+ let mut found = BTreeMap::new();
+ marks.iter().try_for_each(|mark| {
+ if let Mark::Fill(fill) = mark
+ && let FillSource::Seed { seed, reference } = &fill.source
+ && ids.contains(&fill.id)
+ {
+ rasters.insert(cel.to_string(), own.clone());
+ let image = fill_reference(doc, frame, &rasters, cel, reference)?;
+ found.insert(fill.id, sample(&image, seed.x, seed.y));
+ }
+ match mark {
+ Mark::Fill(fill) => {
+ paint_fill(&mut own, fill);
+ }
+ stroke => {
+ replay_onto(&mut own, std::slice::from_ref(stroke), brushes)?;
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ Ok(found)
+}
+
+fn drawing_frame(doc: &Document, layer: &str, cel: &str) -> Result<u32> {
+ let owner = doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let found = owner
+ .cels()
+ .iter()
+ .find(|c| c.id == cel)
+ .ok_or_else(|| anyhow!("{cel} is not a cel of {}", owner.name))?;
+ if let Some(source) = &found.link {
+ bail!("{cel} is a link to {source}; carry the fills of {source}");
+ }
+ Ok(found.frame)
+}
+
+pub fn like(bundle: &Bundle, spec: &mut FillSpec) -> Result<Vec<String>> {
+ let start = Instant::now();
+ let doc = &bundle.doc;
+ let owner = doc.find_layer(&spec.layer)?;
+ if owner.kind() != Kind::Paint {
+ bail!(
+ "{} is a {} layer; fills live on paint layers",
+ owner.id,
+ owner.kind().name()
+ );
+ }
+ let layer = owner.id.clone();
+ let source = spec.like.clone().unwrap_or_default();
+ let at = drawing_frame(doc, &layer, &source)?;
+ let (from, to) = klad_render::sheet::range(doc, spec.frames.as_deref().unwrap_or("all"))?;
+ let marks = bundle.read_marks(&layer, &source)?;
+ let floods: Vec<&Fill> = marks
+ .iter()
+ .filter_map(Mark::as_fill)
+ .filter(|f| matches!(f.source, FillSource::Seed { .. }))
+ .collect();
+ if floods.is_empty() {
+ bail!("{source} has no flood fills to carry (lasso fills stay where they are drawn)");
+ }
+ let brushes = BrushSet::for_bundle(bundle)?;
+ let ids: Vec<u32> = floods.iter().map(|f| f.id).collect();
+ let colours = seed_colours(bundle, &source, at, &marks, &ids, &brushes)?;
+ let mut targets: Vec<(String, u32)> = Vec::new();
+ (from..=to).for_each(|f| {
+ if let Some(cel) = owner.content_at(f)
+ && cel.id != source
+ && !targets.iter().any(|(c, _)| *c == cel.id)
+ {
+ targets.push((cel.id.clone(), f));
+ }
+ });
+ if targets.is_empty() {
+ bail!(
+ "{} shows no drawing other than {source} on frames {from} to {to}",
+ owner.name
+ );
+ }
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let results = targets
+ .par_iter()
+ .map(|(cel, frame)| {
+ let mut rasters: Rasters = layers::load(bundle, *frame, &brushes, true)?.rasters;
+ if floods.iter().any(|f| needs_vectors(doc, f.reference())) {
+ Vectors::default().add_to(doc, *frame, &mut rasters)?;
+ }
+ let mut out = bundle.read_marks(&layer, cel)?;
+ let mut failed = Vec::new();
+ let mut carried = 0;
+ floods.iter().try_for_each(|fill| {
+ let FillSource::Seed { seed, reference } = &fill.source else {
+ return Ok(());
+ };
+ let place = out.iter().position(|m| m.id() == fill.id && m.as_fill().is_some());
+ let before = place.unwrap_or(out.len());
+ let own = replay(w, h, &out[..before], &brushes)?.raster;
+ rasters.insert(cel.clone(), own);
+ let image = fill_reference(doc, *frame, &rasters, cel, reference)?;
+ let colour = colours.get(&fill.id).copied().unwrap_or([0.0; 4]);
+ let why = |text: &str| format!("{} on frame {frame}: {text}", address(&source, fill.id));
+ let Some([x, y]) = carry_seed(&image, colour, seed, &fill.coverage) else {
+ failed.push(why("no region there overlaps it"));
+ return Ok(());
+ };
+ let moved = klad_core::fill::Seed { x, y, ..*seed };
+ let coverage = flood(&image, &moved);
+ let (px, old) = (coverage.pixels(), fill.coverage.pixels());
+ if coverage.is_empty() {
+ failed.push(why("it covers no pixels"));
+ return Ok(());
+ }
+ if px as f32 > old as f32 * 2.5 + 256.0 {
+ failed.push(why(&format!("it leaked ({px} px where {source} has {old})")));
+ return Ok(());
+ }
+ let id = match place {
+ Some(_) => fill.id,
+ None if out.iter().any(|m| m.id() == fill.id) => next_id(&out),
+ None => fill.id,
+ };
+ let made = Mark::Fill(Fill {
+ id,
+ source: FillSource::Seed {
+ seed: moved,
+ reference: reference.clone(),
+ },
+ coverage,
+ author: Author::Agent,
+ ..(*fill).clone()
+ });
+ match place {
+ Some(i) => out[i] = made,
+ None => out.push(made),
+ }
+ carried += 1;
+ Ok::<_, anyhow::Error>(())
+ })?;
+ Ok((cel.clone(), *frame, out, carried, failed))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let mut notes = Vec::new();
+ let mut failed_all = Vec::new();
+ results.iter().for_each(|(cel, frame, _, carried, failed)| {
+ notes.push(format!(
+ "{cel} (frame {frame}): {carried} of {} fills carried",
+ floods.len()
+ ));
+ failed_all.extend(failed.iter().cloned());
+ });
+ if !failed_all.is_empty() {
+ notes.push(format!("no fill for: {}", failed_all.join("; ")));
+ }
+ notes.push(format!(
+ "carried the fills of {source} to {} drawings in {:.0} ms",
+ results.len(),
+ start.elapsed().as_secs_f64() * 1000.0
+ ));
+ spec.carried = Some(
+ results
+ .into_iter()
+ .filter(|(_, _, _, carried, _)| *carried > 0)
+ .map(|(cel, _, marks, _, _)| (cel, marks))
+ .collect(),
+ );
+ Ok(notes)
+}
+
+pub struct Pocket {
+ pub bounds: [u32; 4],
+ pub pixels: usize,
+}
+
+pub struct FrameGaps {
+ pub frame: u32,
+ pub cel: Option<String>,
+ pub pockets: Vec<Pocket>,
+ pub mask: Vec<bool>,
+}
+
+fn background(doc: &Document) -> [f32; 4] {
+ doc.canvas
+ .background
+ .as_deref()
+ .and_then(|b| parse_hex(b).ok())
+ .map_or([0.0; 4], |[r, g, b, a]| [r * a, g * a, b * a, a])
+}
+
+pub fn pockets(
+ bundle: &Bundle,
+ layer: &str,
+ frame: u32,
+ reference: &FillRef,
+ (tolerance, gap, min): (f32, f32, usize),
+ brushes: &BrushSet,
+) -> Result<FrameGaps> {
+ let doc = &bundle.doc;
+ let owner = doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let cel = owner.content_at(frame).map(|c| c.id.clone());
+ let mut rasters = layers::load(bundle, frame, brushes, true)?.rasters;
+ if needs_vectors(doc, Some(reference)) {
+ Vectors::default().add_to(doc, frame, &mut rasters)?;
+ }
+ let marks = match &cel {
+ Some(c) => bundle.read_marks(layer, c)?,
+ None => Vec::new(),
+ };
+ let image = fill_reference(doc, frame, &rasters, cel.as_deref().unwrap_or(""), reference)?;
+ let open = match reference {
+ FillRef::All => background(doc),
+ _ => [0.0; 4],
+ };
+ let found = regions(&image, open, tolerance, gap, 1.0);
+ let (w, h) = (found.width, found.height);
+ let mut covered = vec![false; w * h];
+ marks.iter().filter_map(Mark::as_fill).for_each(|f| {
+ let c = &f.coverage;
+ (0..c.height).for_each(|row| {
+ (0..c.width).for_each(|col| {
+ let (x, y) = ((c.x + col) as usize, (c.y + row) as usize);
+ if x < w && y < h && c.alpha[(row * c.width + col) as usize] > 0 {
+ covered[y * w + x] = true;
+ }
+ });
+ });
+ });
+ let mut bare: BTreeMap<u32, (usize, [u32; 4])> = BTreeMap::new();
+ let mut mask = vec![false; w * h];
+ (0..w * h).for_each(|i| {
+ let label = found.labels[i];
+ if label == 0 || covered[i] || found.border[label as usize - 1] {
+ return;
+ }
+ mask[i] = true;
+ let (x, y) = ((i % w) as u32, (i / w) as u32);
+ let entry = bare.entry(label).or_insert((0, [u32::MAX, u32::MAX, 0, 0]));
+ entry.0 += 1;
+ let b = &mut entry.1;
+ *b = [b[0].min(x), b[1].min(y), b[2].max(x + 1), b[3].max(y + 1)];
+ });
+ let pockets: Vec<Pocket> = bare
+ .into_values()
+ .filter(|(n, _)| *n >= min)
+ .map(|(pixels, [x0, y0, x1, y1])| Pocket {
+ bounds: [x0, y0, x1 - x0, y1 - y0],
+ pixels,
+ })
+ .collect();
+ Ok(FrameGaps {
+ frame,
+ cel,
+ pockets,
+ mask,
+ })
+}
+
+fn gap_render(bundle: &Bundle, found: &FrameGaps, rasters_from: &BrushSet) -> Result<PathBuf> {
+ let doc = &bundle.doc;
+ let loaded = layers::load(bundle, found.frame, rasters_from, true)?;
+ let mut image = compose(doc, found.frame, &loaded.rasters, View::scaled(1.0))?;
+ let w = image.width as usize;
+ found.mask.iter().enumerate().filter(|(_, m)| **m).for_each(|(i, _)| {
+ let at = i * 4;
+ let px = &mut image.rgba[at..at + 4];
+ px[0] = ((px[0] as u32 + 255 * 3) / 4) as u8;
+ px[1] = (px[1] as u32 / 4) as u8;
+ px[2] = ((px[2] as u32 + 255 * 3) / 4) as u8;
+ px[3] = 255;
+ });
+ found.pockets.iter().for_each(|p| {
+ let [x, y, bw, bh] = p.bounds;
+ let (x0, y0) = (x.saturating_sub(3) as usize, y.saturating_sub(3) as usize);
+ let (x1, y1) = (
+ ((x + bw + 3) as usize).min(w - 1),
+ ((y + bh + 3) as usize).min(image.height as usize - 1),
+ );
+ let mut put = |x: usize, y: usize| {
+ let at = (y * w + x) * 4;
+ image.rgba[at..at + 4].copy_from_slice(&[230, 20, 160, 255]);
+ };
+ (x0..=x1).for_each(|x| {
+ put(x, y0);
+ put(x, y1);
+ });
+ (y0..=y1).for_each(|y| {
+ put(x0, y);
+ put(x1, y);
+ });
+ });
+ let path = bundle
+ .cache_dir()
+ .join("renders")
+ .join(format!("r{}-gaps-f{}.png", doc.rev, found.frame));
+ write_atomic(&path, &image.png()?)?;
+ Ok(path)
+}
+
+pub struct GapAsk {
+ pub layer: String,
+ pub frames: String,
+ pub reference: Option<String>,
+ pub gap: Option<f32>,
+ pub tolerance: Option<f32>,
+ pub min: usize,
+}
+
+fn settle(bundle: &Bundle, layer: &str, frames: (u32, u32), ask: &GapAsk) -> Result<(FillRef, f32, f32)> {
+ let doc = &bundle.doc;
+ let owner = doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let mut seen: Vec<(FillRef, f32, f32)> = Vec::new();
+ (frames.0..=frames.1)
+ .filter_map(|f| owner.content_at(f).map(|c| c.id.clone()))
+ .collect::<std::collections::BTreeSet<_>>()
+ .iter()
+ .try_for_each(|cel| {
+ bundle
+ .read_marks(layer, cel)?
+ .iter()
+ .filter_map(Mark::as_fill)
+ .for_each(|f| {
+ if let FillSource::Seed { seed, reference } = &f.source {
+ seen.push((reference.clone(), seed.gap, seed.tolerance));
+ }
+ });
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let reference = match &ask.reference {
+ Some(key) => {
+ let spec = FillSpec {
+ reference: Some(key.clone()),
+ ..FillSpec::seeded(layer, [0.0, 0.0])
+ };
+ spec.reference(doc)?
+ }
+ None => {
+ let mut counts: BTreeMap<String, (usize, FillRef)> = BTreeMap::new();
+ seen.iter().for_each(|(r, _, _)| {
+ counts.entry(r.name().to_string()).or_insert((0, r.clone())).0 += 1;
+ });
+ counts
+ .into_values()
+ .max_by_key(|(n, _)| *n)
+ .map(|(_, r)| r)
+ .ok_or_else(|| {
+ anyhow!(
+ "{} has no flood fills on those frames to take the lines from; give --ref (this, all or a layer)",
+ owner.name
+ )
+ })?
+ }
+ };
+ let gap = ask
+ .gap
+ .unwrap_or_else(|| seen.iter().map(|(_, g, _)| *g).fold(0.0, f32::max));
+ let tolerance = ask
+ .tolerance
+ .unwrap_or_else(|| seen.first().map_or(klad_core::fill::TOLERANCE, |(_, _, t)| *t));
+ Ok((reference, gap, tolerance))
+}
+
+pub fn gaps(path: &Path, ask: &GapAsk, out: &Output) -> Result<()> {
+ let start = Instant::now();
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let owner = doc.find_layer(&ask.layer)?;
+ if owner.kind() != Kind::Paint {
+ bail!(
+ "{} is a {} layer; fills live on paint layers",
+ owner.id,
+ owner.kind().name()
+ );
+ }
+ let layer = owner.id.clone();
+ let span = klad_render::sheet::range(doc, &ask.frames)?;
+ let (reference, gap, tolerance) = settle(&bundle, &layer, span, ask)?;
+ let brushes = BrushSet::for_bundle(&bundle)?;
+ let found = (span.0..=span.1)
+ .into_par_iter()
+ .map(|f| pockets(&bundle, &layer, f, &reference, (tolerance, gap, ask.min), &brushes))
+ .collect::<Result<Vec<_>>>()?;
+ let with: Vec<&FrameGaps> = found.iter().filter(|f| !f.pockets.is_empty()).collect();
+ let shown: Vec<&FrameGaps> = match out.render {
+ true => found.iter().collect(),
+ false => with.clone(),
+ };
+ let renders: Vec<(u32, PathBuf)> = shown
+ .par_iter()
+ .map(|f| Ok((f.frame, gap_render(&bundle, f, &brushes)?)))
+ .collect::<Result<Vec<_>>>()?;
+ if out.json {
+ let frames: Vec<serde_json::Value> = found
+ .iter()
+ .map(|f| {
+ json!({
+ "frame": f.frame,
+ "cel": f.cel,
+ "pockets": f.pockets.iter().map(|p| json!({"bounds": p.bounds, "pixels": p.pixels})).collect::<Vec<_>>(),
+ "render": renders.iter().find(|(fr, _)| *fr == f.frame).map(|(_, p)| p.display().to_string()),
+ })
+ })
+ .collect();
+ println!(
+ "{}",
+ json!({"layer": layer, "ref": reference.name(), "gap": gap, "frames": frames})
+ );
+ return Ok(());
+ }
+ println!(
+ "{} against {} (gap {gap}, tolerance {tolerance}), frames {} to {}:",
+ owner.name,
+ reference.name(),
+ span.0,
+ span.1
+ );
+ found.iter().for_each(|f| {
+ let cel = f.cel.as_deref().unwrap_or("nothing");
+ match f.pockets.len() {
+ 0 => println!(" frame {} ({cel}): no pockets", f.frame),
+ n => {
+ let list: Vec<String> = f
+ .pockets
+ .iter()
+ .map(|p| {
+ let [x, y, w, h] = p.bounds;
+ format!("{x},{y} {w}x{h} ({} px)", p.pixels)
+ })
+ .collect();
+ println!(
+ " frame {} ({cel}): {n} pocket{} no fill covers: {}",
+ f.frame,
+ if n == 1 { "" } else { "s" },
+ list.join(", ")
+ );
+ }
+ }
+ if let Some((_, path)) = renders.iter().find(|(fr, _)| *fr == f.frame) {
+ println!(" {}", path.display());
+ }
+ });
+ let total: usize = with.iter().map(|f| f.pockets.len()).sum();
+ println!(
+ "{} in {:.0} ms",
+ match total {
+ 0 => "nothing left uncovered".to_string(),
+ n => format!("{n} pockets on {} frames", with.len()),
+ },
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::ops::{Op, parse_lines};
+ use std::fs;
+
+ fn ask(frames: &str) -> GapAsk {
+ GapAsk {
+ layer: "colour".into(),
+ frames: frames.into(),
+ reference: Some("lines".into()),
+ gap: None,
+ tolerance: None,
+ min: 12,
+ }
+ }
+
+ fn found(dir: &Path, frames: (u32, u32)) -> Vec<usize> {
+ let bundle = Bundle::open(dir).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let reference = FillRef::Layer("lines".into());
+ (frames.0..=frames.1)
+ .map(|f| {
+ pockets(&bundle, "colour", f, &reference, (0.1, 3.0, 12), &brushes)
+ .unwrap()
+ .pockets
+ .len()
+ })
+ .collect()
+ }
+
+ #[test]
+ fn gaps_find_uncoloured_pockets_and_like_carries_the_flats_into_them() {
+ let dir = crate::inbetween::tests::swing("like");
+ let mut bundle = Bundle::open(&dir).unwrap();
+ let turn_back = parse_lines(
+ r#"{"op":"transform","ids":["ln6:s1","ln6:s2","ln6:s3","ln6:s4","ln6:s5"],"rotate":-52,"pivot":[80,100]}
+{"op":"rm","ids":["col6:s1","col6:s2"]}"#,
+ )
+ .unwrap();
+ bundle.apply(&turn_back).unwrap();
+ assert_eq!(found(&dir, (5, 7)), [0, 2, 2]);
+ let out = Output {
+ json: false,
+ render: false,
+ scale: None,
+ frame: 0,
+ overlay: None,
+ };
+ gaps(&dir, &ask("all"), &out).unwrap();
+ let spec = FillSpec {
+ at: None,
+ like: Some("col0".into()),
+ frames: Some("1-7".into()),
+ ..FillSpec::seeded("colour", [0.0, 0.0])
+ };
+ crate::agent::edit(&dir, &[Op::Fill(spec)], &out).unwrap();
+ assert_eq!(found(&dir, (0, 7)), [0; 8]);
+ let bundle = Bundle::open(&dir).unwrap();
+ let carried = bundle.read_marks("colour", "col6").unwrap();
+ assert_eq!(carried.iter().map(Mark::id).collect::<Vec<_>>(), [1, 2]);
+ assert!(carried.iter().all(|m| m.author() == Author::Agent));
+ let again = FillSpec {
+ at: None,
+ like: Some("col0".into()),
+ frames: Some("6-6".into()),
+ ..FillSpec::seeded("colour", [0.0, 0.0])
+ };
+ crate::agent::edit(&dir, &[Op::Fill(again)], &out).unwrap();
+ assert_eq!(
+ Bundle::open(&dir).unwrap().read_marks("colour", "col6").unwrap().len(),
+ 2
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/demo.rs b/crates/cli/src/demo.rs
new file mode 100644
index 0000000..a69ab0d
--- /dev/null
+++ b/crates/cli/src/demo.rs
@@ -0,0 +1,278 @@
+use anyhow::Result;
+use klad_core::bundle::Bundle;
+use klad_core::color::parse_hex;
+use klad_core::doc::{Blend, Document, Layer, Linear, Node, Paint, Radial, Shape, Stop};
+use klad_core::rng::Rng;
+use klad_core::stroke::{Stroke, marks};
+use libm::{cosf, sinf};
+use std::f32::consts::{PI, TAU};
+use std::path::Path;
+
+struct Scene {
+ w: f32,
+ h: f32,
+ k: f32,
+}
+
+impl Scene {
+ fn far(&self, x: f32) -> f32 {
+ let t = x / self.w * TAU;
+ self.h * (0.58 + 0.04 * sinf(t * 1.3 + 0.5) + 0.02 * sinf(t * 3.1))
+ }
+
+ fn near(&self, x: f32) -> f32 {
+ let t = x / self.w * TAU;
+ self.h * (0.74 + 0.05 * sinf(t * 0.8 + 2.0) + 0.015 * sinf(t * 5.0))
+ }
+
+ fn ridge(&self, profile: impl Fn(f32) -> f32) -> String {
+ let steps = (self.w / 16.0) as usize;
+ let ridge: String = (0..=steps)
+ .map(|i| {
+ let x = self.w * i as f32 / steps as f32;
+ format!(" L{x:.1} {:.1}", profile(x))
+ })
+ .collect();
+ format!("M0 {h}{ridge} L{w} {h} Z", w = self.w, h = self.h)
+ }
+}
+
+fn stroke(id: usize, brush: &str, hex: &str, size: f32, rng: &mut Rng, points: Vec<(f32, f32, f32)>) -> Result<Stroke> {
+ Ok(Stroke::new(id as u32, brush, parse_hex(hex)?, size, rng.next_u64() as u32).with_points(&points, 5.0))
+}
+
+fn glow_strokes(s: &Scene, rng: &mut Rng) -> Result<Vec<Stroke>> {
+ let (cx, cy) = (s.w * 0.72, s.h * 0.24);
+ [(0.3, 0.7), (0.18, 0.85), (0.1, 1.0)]
+ .iter()
+ .enumerate()
+ .map(|(i, &(size, p))| {
+ let r = 0.035 * s.w;
+ let points = (0..=48)
+ .map(|j| {
+ let a = j as f32 / 48.0 * TAU;
+ (cx + cosf(a) * r, cy + sinf(a) * r, p)
+ })
+ .collect();
+ stroke(i + 1, "soft", "#f6e3b4", s.w * size, rng, points)
+ })
+ .collect()
+}
+
+fn cloud_strokes(s: &Scene, rng: &mut Rng) -> Result<Vec<Stroke>> {
+ let mut strokes: Vec<Stroke> = (0..18)
+ .map(|i| {
+ let band = s.h * (0.16 + 0.05 * (i % 5) as f32) + rng.signed() * 12.0 * s.k;
+ let x0 = rng.range(-0.1, 0.8) * s.w;
+ let length = rng.range(0.18, 0.4) * s.w;
+ let wave = rng.range(4.0, 12.0) * s.k;
+ let phase = rng.range(0.0, TAU);
+ let peak = rng.range(0.55, 0.9);
+ let points = (0..=60)
+ .map(|j| {
+ let t = j as f32 / 60.0;
+ let taper = (t / 0.2).min(1.0) * ((1.0 - t) / 0.3).min(1.0);
+ (
+ x0 + length * t,
+ band + sinf(t * 7.0 + phase) * wave,
+ peak * (0.25 + 0.75 * taper),
+ )
+ })
+ .collect();
+ let size = rng.range(0.018, 0.03) * s.w;
+ stroke(i + 1, "chalk", "#9fb0c8", size, rng, points)
+ })
+ .collect::<Result<_>>()?;
+ let cuts = (0..2)
+ .map(|i| {
+ let x = s.w * (0.25 + 0.3 * i as f32);
+ let points = (0..=20)
+ .map(|j| {
+ let t = j as f32 / 20.0;
+ (x + t * 0.04 * s.w, s.h * (0.14 + 0.08 * t), 0.4 + 0.6 * sinf(t * PI))
+ })
+ .collect();
+ stroke(100 + i, "eraser", "#000000", 0.012 * s.w, rng, points)
+ })
+ .collect::<Result<Vec<_>>>()?;
+ strokes.extend(cuts);
+ Ok(strokes)
+}
+
+fn haze(s: &Scene, rng: &mut Rng) -> Result<Vec<Stroke>> {
+ [(0.5, 0.22, 0.8), (0.53, 0.14, 0.6), (0.44, 0.3, 0.5)]
+ .iter()
+ .enumerate()
+ .map(|(i, &(y, size, p))| {
+ let points = (0..=40)
+ .map(|j| {
+ let t = j as f32 / 40.0;
+ (
+ -0.1 * s.w + 1.2 * s.w * t,
+ s.h * y + sinf(t * 5.0 + i as f32) * 20.0 * s.k,
+ p,
+ )
+ })
+ .collect();
+ stroke(i + 1, "soft", "#3f5f80", size * s.w, rng, points)
+ })
+ .collect()
+}
+
+fn hatching(s: &Scene, rng: &mut Rng) -> Result<Vec<Stroke>> {
+ let gap = 7.0 * s.k;
+ let columns = (s.w / gap) as usize;
+ let hatches: Vec<(f32, f32, f32, f32)> = (0..columns * 3)
+ .filter_map(|i| {
+ let x = (i % columns) as f32 * gap + rng.signed() * 2.0 * s.k;
+ let top = s.far(x) + 0.012 * s.h;
+ let bottom = top + 0.35 * (s.near(x) - top).max(1.0);
+ let y = rng.range(top, bottom);
+ let length = rng.range(0.012, 0.03) * s.w;
+ let (ex, ey) = (x + length * 0.5, y - length * 0.86);
+ (ey > s.far(ex) + 0.01 * s.h).then_some((x, y, ex, ey))
+ })
+ .collect();
+ hatches
+ .into_iter()
+ .enumerate()
+ .map(|(i, (x, y, ex, ey))| {
+ let p = rng.range(0.35, 0.8);
+ let points = (0..=10)
+ .map(|j| {
+ let t = j as f32 / 10.0;
+ (x + (ex - x) * t, y + (ey - y) * t, p * (0.6 + 0.4 * sinf(t * PI)))
+ })
+ .collect();
+ stroke(i + 1, "pencil", "#7d93ab", 5.0 * s.k, rng, points)
+ })
+ .collect()
+}
+
+fn grass(s: &Scene, rng: &mut Rng) -> Result<Vec<Stroke>> {
+ (0..(700.0 * s.k) as usize)
+ .map(|i| {
+ let x = rng.range(0.0, s.w);
+ let base = s.near(x) + 0.006 * s.h;
+ let height = rng.range(0.015, 0.055) * s.h;
+ let lean = rng.range(-0.35, 0.35);
+ let bend = rng.range(-0.25, 0.25);
+ let points = (0..=12)
+ .map(|j| {
+ let t = j as f32 / 12.0;
+ (
+ x + (lean * t + bend * t * t) * height,
+ base - t * height,
+ 1.0 - 0.95 * t,
+ )
+ })
+ .collect();
+ stroke(i + 1, "ink", "#0b1219", rng.range(0.004, 0.007) * s.w, rng, points)
+ })
+ .collect()
+}
+
+fn vertical(top: f32, bottom: f32, stops: &[(f32, &str)]) -> Paint {
+ Paint::Linear {
+ linear: Linear {
+ from: [0.0, top],
+ to: [0.0, bottom],
+ stops: stops.iter().map(|(at, c)| Stop(*at, c.to_string())).collect(),
+ },
+ }
+}
+
+fn shape(id: &str, name: &str, shape: Shape, fill: Paint) -> Node {
+ let mut node = Node::new(id, shape);
+ node.name = name.to_string();
+ node.fill = Some(fill);
+ node
+}
+
+pub fn write(path: &Path, size: u32, seed: u64) -> Result<Bundle> {
+ let s = Scene {
+ w: size as f32,
+ h: size as f32,
+ k: size as f32 / 2048.0,
+ };
+ let mut rng = Rng::new(seed);
+ let mut doc = Document::new(size, size);
+ let sky = vec![
+ shape(
+ "n1",
+ "sky",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: s.w,
+ h: s.h,
+ radius: 0.0,
+ },
+ vertical(0.0, s.h * 0.62, &[(0.0, "#121d31"), (0.6, "#24395a"), (1.0, "#4a6a8c")]),
+ ),
+ shape(
+ "n2",
+ "moon",
+ Shape::Ellipse {
+ cx: s.w * 0.72,
+ cy: s.h * 0.24,
+ rx: s.w * 0.05,
+ ry: s.w * 0.05,
+ },
+ Paint::Radial {
+ radial: Radial {
+ center: [s.w * 0.70, s.h * 0.225],
+ radius: s.w * 0.06,
+ stops: vec![Stop(0.0, "#fffbea".into()), Stop(1.0, "#e9d9ae".into())],
+ },
+ },
+ ),
+ ];
+ let mut glow = Layer::paint("glow", "moon glow", "c3");
+ glow.blend = Blend::Screen;
+ glow.opacity = 0.9;
+ let mut clouds = Layer::paint("clouds", "clouds", "c4");
+ clouds.opacity = 0.85;
+ let mut hatch = Layer::paint("hatch", "hill hatching", "c6");
+ hatch.opacity = 0.45;
+ let far = shape(
+ "n3",
+ "far ridge",
+ Shape::Path {
+ d: s.ridge(|x| s.far(x)),
+ },
+ vertical(s.h * 0.52, s.h, &[(0.0, "#2c4560"), (1.0, "#1c2b3d")]),
+ );
+ let near = shape(
+ "n4",
+ "near ridge",
+ Shape::Path {
+ d: s.ridge(|x| s.near(x)),
+ },
+ vertical(s.h * 0.68, s.h, &[(0.0, "#152230"), (1.0, "#0b121a")]),
+ );
+ doc.layers = vec![
+ Layer::vector("sky", "sky", "c1", sky),
+ Layer::paint("haze", "horizon haze", "c2"),
+ glow,
+ clouds,
+ Layer::vector("far", "far hills", "c5", vec![far]),
+ hatch,
+ Layer::group(
+ "front",
+ "foreground",
+ vec![
+ Layer::vector("near", "near hills", "c7", vec![near]),
+ Layer::paint("grass", "grass", "c8"),
+ ],
+ ),
+ ];
+ doc.next_id = 8;
+ let bundle = Bundle::create(path, doc)?;
+ bundle.write_marks("haze", "c2", &marks(haze(&s, &mut rng)?))?;
+ bundle.write_marks("glow", "c3", &marks(glow_strokes(&s, &mut rng)?))?;
+ bundle.write_marks("clouds", "c4", &marks(cloud_strokes(&s, &mut rng)?))?;
+ bundle.write_marks("hatch", "c6", &marks(hatching(&s, &mut rng)?))?;
+ bundle.write_marks("grass", "c8", &marks(grass(&s, &mut rng)?))?;
+ Ok(bundle)
+}
diff --git a/crates/cli/src/edit.rs b/crates/cli/src/edit.rs
new file mode 100644
index 0000000..597a3a7
--- /dev/null
+++ b/crates/cli/src/edit.rs
@@ -0,0 +1,188 @@
+use anyhow::{Context, Result, bail};
+use klad_core::bundle::{Blank, Bundle, now_ms};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Cel, Kind};
+use klad_core::stroke::{Mark, marks, next_id};
+use klad_core::synth::Synth;
+use notify::{Config, PollWatcher, RecursiveMode, Watcher};
+use std::path::Path;
+use std::sync::mpsc::channel;
+use std::time::{Duration, Instant};
+
+pub fn new(path: &Path, blank: &Blank) -> Result<Bundle> {
+ Bundle::blank(path, blank, "cli")
+}
+
+pub fn stress(
+ path: &Path,
+ size: u32,
+ layers: usize,
+ strokes: usize,
+ seed: u64,
+ (frames, every): (u32, u32),
+) -> Result<()> {
+ if every == 0 {
+ bail!("--every must be at least 1");
+ }
+ let mut bundle = new(
+ path,
+ &Blank {
+ width: size,
+ height: size,
+ layers,
+ background: Some("#f4efe6".into()),
+ frames,
+ ..Blank::default()
+ },
+ )?;
+ let doc = &mut bundle.doc;
+ let paths: Vec<usize> = (0..doc.layers.len()).collect();
+ paths.iter().for_each(|&i| {
+ let starts: Vec<u32> = (0..frames).step_by(every as usize).collect();
+ let ids: Vec<String> = starts.iter().skip(1).map(|_| doc.alloc_id('c')).collect();
+ if let Some(cels) = doc.layers[i].cels_mut() {
+ cels.extend(ids.iter().zip(&starts[1..]).map(|(id, f)| Cel::at(id, *f)));
+ }
+ });
+ bundle.save()?;
+ let synth = Synth::canvas(size as f32, size as f32);
+ bundle
+ .doc
+ .paint_cels()
+ .iter()
+ .enumerate()
+ .try_for_each(|(i, (layer, cel))| {
+ bundle
+ .write_marks(&layer.id, &cel.id, &marks(synth.strokes(strokes, seed + i as u64)))
+ .map(|_| ())
+ })
+}
+
+fn top_paint_layer(bundle: &Bundle) -> Result<String> {
+ bundle
+ .doc
+ .all_layers()
+ .into_iter()
+ .rev()
+ .find(|l| l.kind() == Kind::Paint)
+ .map(|l| l.id.clone())
+ .context("the bundle has no paint layer")
+}
+
+pub struct Scribble {
+ pub layer: Option<String>,
+ pub frame: u32,
+ pub count: usize,
+ pub seed: Option<u64>,
+ pub size: Option<f32>,
+ pub color: String,
+}
+
+pub fn scribble(path: &Path, opts: Scribble) -> Result<()> {
+ let Scribble {
+ layer,
+ frame,
+ count,
+ seed,
+ size,
+ color,
+ } = opts;
+ let start = Instant::now();
+ let mut bundle = Bundle::open(path)?;
+ let layer = match layer {
+ Some(id) => id,
+ None => top_paint_layer(&bundle)?,
+ };
+ let owner = bundle.doc.layer(&layer).with_context(|| format!("no layer {layer}"))?;
+ if owner.kind() != Kind::Paint {
+ bail!("{layer} is not a paint layer");
+ }
+ let cel = owner
+ .content_at(frame)
+ .with_context(|| format!("layer {layer} has no cel at frame {frame}"))?
+ .id
+ .clone();
+ let mut strokes = bundle.read_marks(&layer, &cel)?;
+ let next = next_id(&strokes);
+ let (w, h) = (bundle.doc.canvas.width as f32, bundle.doc.canvas.height as f32);
+ let mut synth = Synth::canvas(w, h);
+ synth.brushes = vec!["ink".into()];
+ synth.palette = vec![parse_hex(&color)?];
+ synth.min_len = synth.max_len * 0.5;
+ let added = synth
+ .strokes(count, seed.unwrap_or_else(now_ms))
+ .into_iter()
+ .enumerate()
+ .map(|(i, mut s)| {
+ s.id = next + i as u32;
+ if let Some(size) = size {
+ s.size = size;
+ }
+ Mark::Stroke(s)
+ });
+ strokes.extend(added);
+ klad_core::history::checkpoint(
+ &bundle,
+ &bundle.doc,
+ "cli",
+ &format!("scribble on {layer}"),
+ &[bundle.strokes_path(&layer, &cel)],
+ )?;
+ bundle.write_marks(&layer, &cel, &strokes)?;
+ bundle.save()?;
+ let stamp = bundle.stamp("cli")?;
+ println!(
+ "rev {} on {layer}: {} marks, written in {:.0} ms",
+ stamp.rev,
+ strokes.len(),
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+pub fn watch(path: &Path, poll: bool, seconds: u64) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let (tx, rx) = channel();
+ let handler = move |res: notify::Result<notify::Event>| {
+ if let Ok(event) = res
+ && event.paths.iter().any(|p| p.ends_with("sync.json"))
+ {
+ let _ = tx.send(now_ms());
+ }
+ };
+ let mut watcher: Box<dyn Watcher> = if poll {
+ Box::new(PollWatcher::new(
+ handler,
+ Config::default().with_poll_interval(Duration::from_millis(20)),
+ )?)
+ } else {
+ Box::new(notify::recommended_watcher(handler)?)
+ };
+ watcher.watch(&bundle.cache_dir(), RecursiveMode::NonRecursive)?;
+ println!(
+ "watching {} for {seconds} s ({})",
+ bundle.stamp_path().display(),
+ if poll { "polling every 20 ms" } else { "native events" }
+ );
+ let until = Instant::now() + Duration::from_secs(seconds);
+ let mut last = bundle.read_stamp().map_or(0, |s| s.rev);
+ while let Some(left) = until.checked_duration_since(Instant::now()) {
+ let Ok(seen) = rx.recv_timeout(left) else {
+ break;
+ };
+ match bundle.read_stamp() {
+ Some(stamp) if stamp.rev != last && stamp.author != "cli" => {
+ last = stamp.rev;
+ println!(
+ "rev {} by {}: seen after {} ms",
+ stamp.rev,
+ stamp.author,
+ seen as i64 - stamp.at_ms as i64
+ );
+ }
+ Some(stamp) => last = stamp.rev,
+ None => {}
+ }
+ }
+ Ok(())
+}
diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rs
new file mode 100644
index 0000000..c4530f0
--- /dev/null
+++ b/crates/cli/src/export.rs
@@ -0,0 +1,132 @@
+use crate::layers;
+use anyhow::{Result, bail};
+use klad_brush::BrushSet;
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_render::export::{Options, Target, png8, png16, render};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+pub struct Export {
+ pub layer: Option<String>,
+ pub frame: u32,
+ pub scale: f32,
+ pub depth: u8,
+ pub background: bool,
+ pub references: bool,
+ pub out: Option<PathBuf>,
+}
+
+pub(crate) fn scale_tag(scale: f32) -> String {
+ if (scale - 1.0).abs() < f32::EPSILON {
+ return String::new();
+ }
+ let text = format!("{scale:.3}");
+ format!("@{}x", text.trim_end_matches('0').trim_end_matches('.'))
+}
+
+pub fn default_path(bundle: &Bundle, layer: Option<&str>, frame: u32, scale: f32) -> PathBuf {
+ let root = bundle.root.components().collect::<PathBuf>();
+ let stem = root
+ .file_stem()
+ .map_or("export".into(), |s| s.to_string_lossy().to_string());
+ let layer = layer.map_or(String::new(), |l| format!("-{l}"));
+ let frame = if bundle.doc.timeline.frames > 1 {
+ format!("-f{frame}")
+ } else {
+ String::new()
+ };
+ root.parent()
+ .unwrap_or(Path::new("."))
+ .join(format!("{stem}{layer}{frame}{}.png", scale_tag(scale)))
+}
+
+pub fn run(path: &Path, opts: Export) -> Result<()> {
+ let start = Instant::now();
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ if opts.frame >= doc.timeline.frames {
+ bail!(
+ "frame {} is past the last frame {}",
+ opts.frame,
+ doc.timeline.frames - 1
+ );
+ }
+ let layer = opts.layer.as_deref().map(|key| doc.find_layer(key)).transpose()?;
+ let rasters = layers::load(&bundle, opts.frame, &BrushSet::for_bundle(&bundle)?, true)?.rasters;
+ let target = match layer {
+ Some(l) => Target::Layer(l),
+ None => Target::Frame,
+ };
+ let options = Options {
+ scale: opts.scale,
+ background: opts.background,
+ references: opts.references,
+ };
+ let image = render(doc, opts.frame, &rasters, &target, options)?;
+ let rendered = start.elapsed().as_secs_f64() * 1000.0;
+ let bytes = match opts.depth {
+ 8 => png8(&image)?,
+ 16 => png16(&image)?,
+ other => bail!("--depth takes 8 or 16, not {other}"),
+ };
+ let name = layer.map(|l| {
+ if l.name.is_empty() {
+ l.id.as_str()
+ } else {
+ l.name.as_str()
+ }
+ });
+ let out = opts
+ .out
+ .unwrap_or_else(|| default_path(&bundle, name, opts.frame, opts.scale));
+ write_atomic(&out, &bytes)?;
+ println!("{}", out.display());
+ eprintln!(
+ "{}x{} {}-bit{} {} KB rendered {rendered:.0} ms, {:.0} ms in all",
+ image.width(),
+ image.height(),
+ opts.depth,
+ if opts.depth == 8 { " dithered" } else { "" },
+ bytes.len() / 1024,
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Document, Layer};
+
+ #[test]
+ fn exports_land_next_to_the_bundle_with_layer_frame_and_scale_in_the_name() {
+ let dir = std::env::temp_dir().join(format!("draw-export-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(64, 32);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let bundle = Bundle::create(dir.join("art.draw/"), doc).unwrap();
+ assert_eq!(default_path(&bundle, None, 0, 1.0), dir.join("art.png"));
+ assert_eq!(default_path(&bundle, Some("ink"), 0, 2.0), dir.join("[email protected]"));
+ assert_eq!(default_path(&bundle, None, 0, 0.5), dir.join("[email protected]"));
+ let out = dir.join("out/ink.png");
+ run(
+ &dir.join("art.draw"),
+ Export {
+ layer: Some("ink".into()),
+ frame: 0,
+ scale: 4.0,
+ depth: 16,
+ background: false,
+ references: false,
+ out: Some(out.clone()),
+ },
+ )
+ .unwrap();
+ let png = std::fs::read(&out).unwrap();
+ assert_eq!(
+ (png[24], u32::from_be_bytes(png[16..20].try_into().unwrap())),
+ (16, 256)
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/fills.rs b/crates/cli/src/fills.rs
new file mode 100644
index 0000000..1e557c9
--- /dev/null
+++ b/crates/cli/src/fills.rs
@@ -0,0 +1,384 @@
+use crate::agent::{Output, preview};
+use crate::layers::{self, Vectors};
+use anyhow::{Context, Result, anyhow, bail};
+use klad_brush::{BrushSet, Raster, flood, paint_fill, polygon, replay, replay_onto};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Document, Kind};
+use klad_core::fill::{Coverage, FillRef, FillSource};
+use klad_core::ops::{Applied, Op, apply};
+use klad_core::stroke::Mark;
+use klad_render::{Rasters, fill_reference};
+use std::collections::BTreeMap;
+use std::path::Path;
+use std::time::Instant;
+
+fn needs_vectors(doc: &Document, reference: &FillRef) -> bool {
+ match reference {
+ FillRef::This => false,
+ FillRef::All => true,
+ FillRef::Layer(id) => doc.layer(id).is_some_and(|l| l.kind() != Kind::Paint),
+ }
+}
+
+pub struct Computed {
+ pub coverage: Coverage,
+ pub reference_ms: f64,
+ pub fill_ms: f64,
+}
+
+pub fn compute(doc: &Document, frame: u32, rasters: &Rasters, cel: &str, source: &FillSource) -> Result<Computed> {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let start = Instant::now();
+ match source {
+ FillSource::Seed { seed, reference } => {
+ let image = fill_reference(doc, frame, rasters, cel, reference)?;
+ let reference_ms = ms(start);
+ let start = Instant::now();
+ let coverage = flood(&image, seed);
+ Ok(Computed {
+ coverage,
+ reference_ms,
+ fill_ms: ms(start),
+ })
+ }
+ FillSource::Polygon(points) => Ok(Computed {
+ coverage: polygon(points, w, h),
+ reference_ms: 0.0,
+ fill_ms: ms(start),
+ }),
+ }
+}
+
+fn ms(start: Instant) -> f64 {
+ start.elapsed().as_secs_f64() * 1000.0
+}
+
+struct Running<'a> {
+ bundle: &'a Bundle,
+ brushes: BrushSet,
+ rasters: Rasters,
+ stored: BTreeMap<String, Vec<Mark>>,
+ painted: BTreeMap<String, Vec<Mark>>,
+ vectors: Vectors,
+}
+
+impl Running<'_> {
+ fn ensure(&mut self, layer: &str, cel: &str) -> Result<()> {
+ if !self.rasters.contains_key(cel) {
+ let raster = layers::load_one(self.bundle, &self.brushes, layer, cel)?;
+ self.rasters.insert(cel.to_string(), raster);
+ }
+ Ok(())
+ }
+
+ fn catch_up(&mut self, doc: &Document, applied: &Applied, frame: u32) -> Result<()> {
+ doc.paint_content_at(frame)
+ .iter()
+ .try_for_each(|(layer, cel)| self.ensure(&layer.id, &cel.id))?;
+ applied.marks.iter().try_for_each(|pending| {
+ self.ensure(&pending.layer, &pending.cel)?;
+ if !self.stored.contains_key(&pending.cel) {
+ let marks = self.bundle.read_marks(&pending.layer, &pending.cel)?;
+ self.stored.insert(pending.cel.clone(), marks);
+ }
+ let stored = self.stored[&pending.cel].clone();
+ let mut marks = stored.clone();
+ pending
+ .changes
+ .clone()
+ .iter_mut()
+ .try_for_each(|c| self.bundle.apply_change(&applied.marks, &mut marks, c, &pending.cel))?;
+ let before = self.painted.get(&pending.cel).cloned().unwrap_or(stored);
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let raster = self
+ .rasters
+ .get_mut(&pending.cel)
+ .ok_or_else(|| anyhow!("cel {} has no pixels", pending.cel))?;
+ if marks.len() >= before.len() && marks[..before.len()] == before[..] {
+ replay_onto(raster, &marks[before.len()..], &self.brushes)?;
+ } else {
+ *raster = replay(w, h, &marks, &self.brushes)?.raster;
+ }
+ self.painted.insert(pending.cel.clone(), marks);
+ Ok(())
+ })
+ }
+}
+
+pub fn resolve(bundle: &Bundle, ops: &mut [Op]) -> Result<Vec<String>> {
+ if ops.iter().any(|op| matches!(op, Op::Fill(f) if f.like.is_some())) {
+ if ops.len() > 1 {
+ bail!(
+ "a fill like another drawing's needs a batch of its own: it reads the drawings from the bundle as they are"
+ );
+ }
+ let Op::Fill(spec) = &mut ops[0] else {
+ unreachable!("checked above");
+ };
+ return crate::colour::like(bundle, spec);
+ }
+ if !ops.iter().any(|op| matches!(op, Op::Fill(_))) {
+ return Ok(Vec::new());
+ }
+ let mut running = Running {
+ bundle,
+ brushes: BrushSet::for_bundle(bundle)?,
+ rasters: Rasters::new(),
+ stored: BTreeMap::new(),
+ painted: BTreeMap::new(),
+ vectors: Vectors::default(),
+ };
+ let mut doc = bundle.doc.clone();
+ let mut applied = Applied::default();
+ let mut notes = Vec::new();
+ ops.iter_mut().enumerate().try_for_each(|(i, op)| {
+ if let Op::Fill(spec) = op {
+ let source = spec.source(&doc).with_context(|| format!("op {}", i + 1))?;
+ if matches!(source, FillSource::Seed { .. }) {
+ running.catch_up(&doc, &applied, spec.frame)?;
+ }
+ let mut rasters = running.rasters.clone();
+ if let FillSource::Seed { reference, .. } = &source
+ && needs_vectors(&doc, reference)
+ {
+ running.vectors.add_to(&doc, spec.frame, &mut rasters)?;
+ }
+ let cel = doc
+ .layer(&spec.layer)
+ .and_then(|l| l.content_at(spec.frame))
+ .map(|c| c.id.clone())
+ .unwrap_or_default();
+ let done = compute(&doc, spec.frame, &rasters, &cel, &source)?;
+ if done.coverage.is_empty() {
+ bail!(
+ "op {}: the fill on {} covers no pixels (outside the canvas, or a polygon with no area)",
+ i + 1,
+ spec.layer
+ );
+ }
+ notes.push(format!(
+ "fill on {}: {} px, reference {:.0} ms, fill {:.0} ms",
+ spec.layer,
+ done.coverage.pixels(),
+ done.reference_ms,
+ done.fill_ms
+ ));
+ spec.coverage = Some(done.coverage);
+ }
+ apply(&mut doc, op, &mut applied).with_context(|| format!("op {}", i + 1))
+ })?;
+ match notes.len() {
+ 0..=4 => Ok(notes),
+ n => Ok(vec![format!("{n} fills computed")]),
+ }
+}
+
+pub fn refill(path: &Path, layer: &str, frame: u32, only: Option<u32>, out: &Output) -> Result<()> {
+ let start = Instant::now();
+ let mut bundle = Bundle::open(path)?;
+ let doc = bundle.doc.clone();
+ let owner = doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ if owner.kind() != Kind::Paint {
+ bail!("{layer} is a {} layer; fills live on paint layers", owner.kind().name());
+ }
+ let cel = owner
+ .content_at(frame)
+ .ok_or_else(|| anyhow!("layer {layer} has no cel at frame {frame}"))?
+ .id
+ .clone();
+ let brushes = BrushSet::for_bundle(&bundle)?;
+ let mut rasters = layers::load(&bundle, frame, &brushes, true)?.rasters;
+ let mut marks = bundle.read_marks(layer, &cel)?;
+ if let Some(id) = only
+ && !marks.iter().any(|m| m.id() == id && m.as_fill().is_some())
+ {
+ bail!("cel {cel} has no fill {id}");
+ }
+ let mut vectors = Vectors::default();
+ let mut own = Raster::new(doc.canvas.width, doc.canvas.height);
+ let mut changes = Vec::new();
+ marks.iter_mut().try_for_each(|mark| {
+ let redo = match mark {
+ Mark::Fill(fill) if only.is_none_or(|id| id == fill.id) => match &fill.source {
+ FillSource::Seed { reference, .. } => Some(reference.clone()),
+ FillSource::Polygon(_) => None,
+ },
+ _ => None,
+ };
+ if let (Some(reference), Mark::Fill(fill)) = (redo, &mut *mark) {
+ rasters.insert(cel.clone(), own.clone());
+ if needs_vectors(&doc, &reference) {
+ vectors.add_to(&doc, frame, &mut rasters)?;
+ }
+ let done = compute(&doc, frame, &rasters, &cel, &fill.source)?;
+ changes.push((fill.id, fill.coverage.pixels(), done.coverage.pixels()));
+ fill.coverage = done.coverage;
+ }
+ match mark {
+ Mark::Fill(fill) => {
+ paint_fill(&mut own, fill);
+ }
+ stroke => {
+ replay_onto(&mut own, std::slice::from_ref(stroke), &brushes)?;
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ if changes.is_empty() {
+ println!("no flood fills to recompute on {layer} cel {cel}");
+ return Ok(());
+ }
+ bundle.replace_marks(layer, &cel, &marks, "cli", &format!("refill on {layer}"))?;
+ bundle.stamp("cli")?;
+ changes.iter().for_each(|(id, before, after)| {
+ println!("fill {id}: {before} px -> {after} px");
+ });
+ println!(
+ "refilled {} on {layer} cel {cel} in {:.0} ms\nrev {}",
+ changes.len(),
+ ms(start),
+ bundle.doc.rev
+ );
+ if let Some(p) = preview(&bundle, out)? {
+ println!("{}", p.display());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Layer;
+ use klad_core::ops::parse_lines;
+ use std::fs;
+
+ fn scratch(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-fills-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ fn ring(layer: &str, cx: f32) -> String {
+ let points: Vec<String> = (0..=240)
+ .map(|i| {
+ let t = i as f32 / 240.0 * std::f32::consts::TAU;
+ format!("[{},{},1]", cx + 60.0 * libm::cosf(t), 128.0 + 60.0 * libm::sinf(t))
+ })
+ .collect();
+ format!(
+ r#"{{"op":"stroke","layer":"{layer}","brush":"ink","size":4,"taper":[0,0],"points":[{}]}}"#,
+ points.join(",")
+ )
+ }
+
+ #[test]
+ fn agents_ink_and_fill_in_one_batch_and_refill_after_the_lines_change() {
+ let dir = scratch("batch");
+ let mut doc = Document::new(512, 256);
+ doc.layers = vec![
+ Layer::paint("fills", "fills", "c1"),
+ Layer::paint("lines", "lines", "c2"),
+ ];
+ doc.next_id = 2;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let text = [
+ ring("lines", 128.0),
+ r##"{"op":"palette","add":"#d04030","name":"red"}"##.to_string(),
+ r##"{"op":"fill","layer":"fills","at":[128,128],"ref":"lines","color":"red"}"##.to_string(),
+ r##"{"op":"fill","layer":"fills","at":[10,10],"ref":"lines","color":"#204060"}"##.to_string(),
+ r##"{"op":"fill","layer":"lines","at":[10,10],"color":"#ffffff"}"##.to_string(),
+ ]
+ .join("\n");
+ let mut ops = parse_lines(&text).unwrap();
+ let notes = resolve(&bundle, &mut ops).unwrap();
+ assert_eq!(notes.len(), 3);
+ bundle.apply(&ops).unwrap();
+ let fills = bundle.read_marks("fills", "c1").unwrap();
+ let inner = fills[0].as_fill().unwrap();
+ assert_eq!(inner.reference(), Some(&FillRef::Layer("lines".into())));
+ assert_eq!(
+ inner.color(),
+ klad_core::color::parse_hex("#d04030")
+ .unwrap()
+ .map(|c| (c * 65535.0).round() / 65535.0)
+ );
+ assert_eq!((inner.coverage.at(128, 128), inner.coverage.at(5, 5)), (255, 0));
+ let inside = inner.coverage.pixels();
+ assert!((10_000..12_500).contains(&inside), "{inside}");
+ assert_eq!(fills[1].as_fill().unwrap().coverage.at(384, 128), 255);
+ let lines = bundle.read_marks("lines", "c2").unwrap();
+ assert_eq!(lines.len(), 2);
+ let outside = lines[1].as_fill().unwrap();
+ assert_eq!((outside.coverage.at(10, 10), outside.coverage.at(128, 128)), (255, 0));
+ let mut more = parse_lines(&ring("lines", 384.0)).unwrap();
+ resolve(&bundle, &mut more).unwrap();
+ bundle.apply(&more).unwrap();
+ let output = Output {
+ json: false,
+ render: false,
+ scale: None,
+ frame: 0,
+ overlay: None,
+ };
+ refill(&dir, "fills", 0, None, &output).unwrap();
+ let fills = Bundle::open(&dir).unwrap().read_marks("fills", "c1").unwrap();
+ assert_eq!(fills[0].as_fill().unwrap().coverage.pixels(), inside);
+ let background = fills[1].as_fill().unwrap();
+ assert_eq!(
+ (background.coverage.at(10, 10), background.coverage.at(384, 128)),
+ (255, 0)
+ );
+ refill(&dir, "lines", 0, None, &output).unwrap();
+ let after = Bundle::open(&dir).unwrap().read_marks("lines", "c2").unwrap();
+ assert_eq!(after.len(), 3);
+ let own = after[1].as_fill().unwrap();
+ assert_eq!(
+ own.coverage.at(384, 128),
+ 255,
+ "a fill only sees the marks drawn before it"
+ );
+ assert!(refill(&dir, "lines", 0, Some(1), &output).is_err());
+ let mut outside = parse_lines(r#"{"op":"fill","layer":"fills","at":[900,10]}"#).unwrap();
+ let err = resolve(&Bundle::open(&dir).unwrap(), &mut outside)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("covers no pixels"), "{err}");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-cli fill_command_timing -- --ignored --nocapture"]
+ fn fill_command_timing() {
+ let dir = scratch("timing");
+ let mut doc = Document::new(2048, 2048);
+ doc.canvas.background = Some("#f4efe6".into());
+ doc.layers = vec![
+ Layer::paint("fills", "fills", "c1"),
+ Layer::paint("lines", "lines", "c2"),
+ ];
+ doc.next_id = 2;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let lines: String = (0..12)
+ .map(|i| {
+ let (x, y) = (200.0 + (i % 4) as f32 * 450.0, 300.0 + (i / 4) as f32 * 600.0);
+ format!(
+ r#"{{"op":"stroke","layer":"lines","size":6,"path":"M{x} {y} L{} {y} L{} {} L{x} {} Z"}}"#,
+ x + 380.0,
+ x + 380.0,
+ y + 500.0,
+ y + 500.0
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ bundle.apply(&parse_lines(&lines).unwrap()).unwrap();
+ ["lines", "all"].iter().for_each(|reference| {
+ let line = format!(r##"{{"op":"fill","layer":"fills","at":[1000,1000],"ref":"{reference}","gap":4}}"##);
+ let mut ops = parse_lines(&line).unwrap();
+ let start = Instant::now();
+ let notes = resolve(&bundle, &mut ops).unwrap();
+ println!("{reference}: {} ({:.0} ms in all)", notes[0], ms(start));
+ });
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/frames.rs b/crates/cli/src/frames.rs
new file mode 100644
index 0000000..d833547
--- /dev/null
+++ b/crates/cli/src/frames.rs
@@ -0,0 +1,237 @@
+use anyhow::{Result, bail};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Clip, Document, Timeline};
+use klad_core::timing::{Cell, cells, ends, sheet_layers};
+use serde_json::{Value, json};
+use std::path::Path;
+
+fn labels(layer: &klad_core::doc::Layer, to: u32) -> Vec<String> {
+ let tweens: Vec<&str> = layer
+ .cels()
+ .iter()
+ .filter(|c| c.tween.is_some())
+ .map(|c| c.id.as_str())
+ .collect();
+ cells(layer, to + 1)
+ .iter()
+ .map(|cell| match cell {
+ Cell::Drawing { cel, start: true } if tweens.contains(&cel.as_str()) => format!("{cel}*"),
+ other => label(other),
+ })
+ .collect()
+}
+
+fn label(cell: &Cell) -> String {
+ match cell {
+ Cell::Drawing { cel, start: true } => cel.clone(),
+ Cell::Link {
+ cel,
+ source,
+ start: true,
+ } => format!("{cel}->{source}"),
+ Cell::Drawing { .. } | Cell::Link { .. } => "|".into(),
+ Cell::Blank => ".".into(),
+ }
+}
+
+fn clip_marks(doc: &Document, frame: u32) -> String {
+ doc.timeline
+ .clips
+ .iter()
+ .filter(|c| c.from <= frame && frame <= c.to)
+ .map(|c| {
+ let open = if c.from == frame { "[" } else { "" };
+ let close = if c.to == frame { "]" } else { "" };
+ format!("{open}{}{close}", c.name)
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+fn short(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((at, _)) => format!("{}~", &text[..at.saturating_sub(1)]),
+ None => text.to_string(),
+ }
+}
+
+pub fn sheet_json(doc: &Document, from: u32, to: u32) -> Value {
+ let layers: Vec<Value> = sheet_layers(doc)
+ .iter()
+ .map(|layer| {
+ let mask_of = doc
+ .all_layers()
+ .iter()
+ .find(|l| l.mask.as_deref().is_some_and(|m| m.id == layer.id))
+ .map(|l| l.id.clone());
+ let ends = ends(layer.cels());
+ let cels: Vec<Value> = layer
+ .cels()
+ .iter()
+ .zip(ends)
+ .map(|(c, end)| {
+ json!({
+ "id": c.id,
+ "frame": c.frame,
+ "hold": c.hold,
+ "link": c.link,
+ "tween": c.tween,
+ "end": (end != klad_core::timing::OPEN).then_some(end),
+ })
+ })
+ .collect();
+ let all: Vec<String> = labels(layer, to);
+ json!({
+ "id": layer.id,
+ "name": layer.name,
+ "kind": layer.kind().name(),
+ "maskOf": mask_of,
+ "cels": cels,
+ "cells": all[from as usize..].to_vec(),
+ })
+ })
+ .collect();
+ json!({
+ "fps": doc.timeline.fps,
+ "frames": doc.timeline.frames,
+ "clips": doc.timeline.clips,
+ "from": from,
+ "to": to,
+ "layers": layers,
+ })
+}
+
+pub fn sheet(path: &Path, from: Option<u32>, to: Option<u32>, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let last = doc.timeline.frames - 1;
+ let (from, to) = (from.unwrap_or(0), to.unwrap_or(last).min(last));
+ if from > to {
+ bail!("--from {from} is past --to {to} (the last frame is {last})");
+ }
+ if as_json {
+ println!("{}", serde_json::to_string_pretty(&sheet_json(doc, from, to))?);
+ return Ok(());
+ }
+ let layers = sheet_layers(doc);
+ let columns: Vec<Vec<String>> = layers.iter().map(|l| labels(l, to)[from as usize..].to_vec()).collect();
+ let heads: Vec<(String, String)> = layers
+ .iter()
+ .map(|l| {
+ let mask = if doc.is_mask(&l.id) { " (mask)" } else { "" };
+ (l.id.clone(), short(&format!("{}{mask}", l.name), 14))
+ })
+ .collect();
+ let widths: Vec<usize> = heads
+ .iter()
+ .zip(&columns)
+ .map(|((id, name), cells)| {
+ cells
+ .iter()
+ .map(String::len)
+ .chain([id.len(), name.chars().count()])
+ .max()
+ .unwrap_or(1)
+ + 2
+ })
+ .collect();
+ let row = |first: String, items: Vec<String>, tail: String| {
+ let body: String = items
+ .iter()
+ .zip(&widths)
+ .map(|(item, w)| format!("{item:<w$}", w = *w))
+ .collect();
+ println!("{}", format!("{first:>5} {body}{tail}").trim_end());
+ };
+ println!(
+ "{} frames at {} fps{}",
+ doc.timeline.frames,
+ doc.timeline.fps,
+ if from > 0 || to < last {
+ format!(", frames {from} to {to}")
+ } else {
+ String::new()
+ }
+ );
+ let clips = !doc.timeline.clips.is_empty();
+ row(
+ "frame".into(),
+ heads.iter().map(|(id, _)| id.clone()).collect(),
+ if clips { "clips".into() } else { String::new() },
+ );
+ row(
+ String::new(),
+ heads.iter().map(|(_, n)| n.clone()).collect(),
+ String::new(),
+ );
+ (from..=to).for_each(|f| {
+ let items = columns.iter().map(|c| c[(f - from) as usize].clone()).collect();
+ row(f.to_string(), items, clip_marks(doc, f));
+ });
+ if columns.iter().flatten().any(|c| c.ends_with('*')) {
+ println!("c5* is an in-between (klad show c5 names its keys; klad inbetween --redo remakes it)");
+ }
+ doc.timeline
+ .clips
+ .iter()
+ .for_each(|c| println!("clip {}", clip_line(&doc.timeline, c)));
+ Ok(())
+}
+
+pub fn clip_line(t: &Timeline, c: &Clip) -> String {
+ let fps = t.fps_of(c);
+ format!(
+ "{} frames {} to {} ({} frame{}, {:.2} s at {fps} fps{}), {}",
+ c.name,
+ c.from,
+ c.to,
+ c.frames(),
+ if c.frames() == 1 { "" } else { "s" },
+ c.frames() as f64 / fps as f64,
+ if c.fps.is_some() { ", its own" } else { "" },
+ if c.looping { "loops" } else { "plays once" }
+ )
+}
+
+pub fn show_timeline(bundle: &Bundle) {
+ let doc = &bundle.doc;
+ let t = &doc.timeline;
+ println!("{} frames at {} fps", t.frames, t.fps);
+ let (w, h) = (doc.canvas.width as f32, doc.canvas.height as f32);
+ match t.origin {
+ Some([x, y]) => println!("origin {x},{y}"),
+ None => println!("origin {},{} (the centre)", w / 2.0, h / 2.0),
+ }
+ if let Some(dir) = &doc.export.godot {
+ println!("godot export folder {dir}");
+ }
+ t.clips.iter().for_each(|c| println!("clip {}", clip_line(t, c)));
+}
+
+pub fn list_clips(bundle: &Bundle, as_json: bool) -> Result<()> {
+ let t = &bundle.doc.timeline;
+ if as_json {
+ let clips: Vec<Value> = t
+ .clips
+ .iter()
+ .map(|c| {
+ json!({
+ "name": c.name,
+ "from": c.from,
+ "to": c.to,
+ "loop": c.looping,
+ "fps": t.fps_of(c),
+ "ownFps": c.fps.is_some(),
+ "seconds": c.frames() as f64 / t.fps_of(c) as f64,
+ })
+ })
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&clips)?);
+ return Ok(());
+ }
+ if t.clips.is_empty() {
+ println!("no clips (the timeline is {} frames at {} fps)", t.frames, t.fps);
+ }
+ t.clips.iter().for_each(|c| println!("{}", clip_line(t, c)));
+ Ok(())
+}
diff --git a/crates/cli/src/history.rs b/crates/cli/src/history.rs
new file mode 100644
index 0000000..1e33875
--- /dev/null
+++ b/crates/cli/src/history.rs
@@ -0,0 +1,254 @@
+use crate::agent::{Look, Output, PREVIEW_SIDE, preview, render_look};
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::{Bundle, now_ms, write_atomic};
+use klad_core::history::{Entry, Stack, before, entries, step};
+use klad_render::View;
+use klad_render::overlay::side_by_side;
+use serde_json::json;
+use std::fs;
+use std::path::Path;
+
+fn ago(at_ms: u64) -> String {
+ let secs = now_ms().saturating_sub(at_ms) / 1000;
+ match secs {
+ 0..=59 => format!("{secs}s ago"),
+ 60..=3599 => format!("{}m ago", secs / 60),
+ 3600..=86_399 => format!("{}h ago", secs / 3600),
+ _ => format!("{}d ago", secs / 86_400),
+ }
+}
+
+pub fn log(path: &Path, limit: usize, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let undo = entries(&bundle, Stack::Undo)?;
+ let redo = entries(&bundle, Stack::Redo)?;
+ if as_json {
+ let value = json!({ "rev": bundle.doc.rev, "undo": undo.iter().take(limit).collect::<Vec<_>>(), "redo": redo });
+ println!("{}", serde_json::to_string_pretty(&value)?);
+ return Ok(());
+ }
+ println!(
+ "rev {} {} undo steps, {} redo steps",
+ bundle.doc.rev,
+ undo.len(),
+ redo.len()
+ );
+ undo.iter().take(limit).for_each(|e| {
+ println!(
+ "#{:<4} from rev {:<5} {:<7} {:>8} {}",
+ e.seq,
+ e.rev,
+ e.author,
+ ago(e.at_ms),
+ e.summary
+ );
+ });
+ if undo.len() > limit {
+ println!("... {} older", undo.len() - limit);
+ }
+ Ok(())
+}
+
+pub fn walk(path: &Path, stack: Stack, out: &Output) -> Result<()> {
+ let mut bundle = Bundle::open(path)?;
+ let word = if stack == Stack::Undo { "undid" } else { "redid" };
+ match step(&mut bundle, stack)? {
+ Some(entry) => {
+ bundle.stamp("cli")?;
+ let render = preview(&bundle, out)?;
+ if out.json {
+ let value =
+ json!({ "rev": bundle.doc.rev, word: entry, "render": render.map(|p| p.display().to_string()) });
+ println!("{value}");
+ } else {
+ println!("{word} #{}: {} (now rev {})", entry.seq, entry.summary, bundle.doc.rev);
+ if let Some(p) = render {
+ println!("{}", p.display());
+ }
+ }
+ }
+ None => println!("nothing to {}", if stack == Stack::Undo { "undo" } else { "redo" }),
+ }
+ Ok(())
+}
+
+fn copy_dir(from: &Path, to: &Path) -> Result<()> {
+ if !from.exists() {
+ return Ok(());
+ }
+ fs::create_dir_all(to)?;
+ fs::read_dir(from)?.try_for_each(|e| {
+ let e = e?;
+ let target = to.join(e.file_name());
+ if e.file_type()?.is_dir() {
+ copy_dir(&e.path(), &target)
+ } else {
+ fs::copy(e.path(), target).map(|_| ()).map_err(Into::into)
+ }
+ })
+}
+
+fn before_bundle(bundle: &Bundle, entry: &Entry) -> Result<Bundle> {
+ let state = before(bundle, entry.seq)?;
+ let dir = bundle.cache_dir().join("diff").join(entry.seq.to_string());
+ if dir.exists() {
+ fs::remove_dir_all(&dir)?;
+ }
+ copy_dir(&bundle.root.join("strokes"), &dir.join("strokes"))?;
+ copy_dir(&bundle.root.join("brushes"), &dir.join("brushes"))?;
+ state.files.iter().try_for_each(|(rel, bytes)| {
+ let target = dir.join(rel);
+ match bytes {
+ Some(bytes) => write_atomic(&target, bytes),
+ None if target.exists() => fs::remove_file(&target).map_err(Into::into),
+ None => Ok(()),
+ }
+ })?;
+ write_atomic(&dir.join("doc.json"), serde_json::to_string(&state.doc)?.as_bytes())?;
+ Bundle::open(&dir)
+}
+
+pub fn diff(path: &Path, seq: Option<u64>, frame: u32, scale: Option<f32>) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let undo = entries(&bundle, Stack::Undo)?;
+ let entry = match seq {
+ Some(seq) => undo
+ .into_iter()
+ .find(|e| e.seq == seq)
+ .ok_or_else(|| anyhow!("no undo step #{seq}"))?,
+ None => undo.into_iter().next().ok_or_else(|| anyhow!("no history yet"))?,
+ };
+ let before = before_bundle(&bundle, &entry)?;
+ let longest = bundle.doc.canvas.width.max(bundle.doc.canvas.height) as f32;
+ if before.doc.canvas != bundle.doc.canvas {
+ bail!("the canvas changed size in #{}; render each side separately", entry.seq);
+ }
+ let view = View::scaled(scale.unwrap_or((PREVIEW_SIDE / 2.0 / longest).min(1.0)));
+ let look = Look::plain(None);
+ let scratch = bundle.cache_dir().join("diff").join(format!("{}-parts", entry.seq));
+ let left = render_look(&before, frame, view, &look, Some(scratch.join("before.png")), true)?.frame;
+ let right = render_look(&bundle, frame, view, &look, Some(scratch.join("after.png")), true)?.frame;
+ let labels = (
+ format!("before #{} rev {}", entry.seq, entry.rev),
+ format!("now rev {}", bundle.doc.rev),
+ );
+ let mut pair = side_by_side(&[(&left, &labels.0), (&right, &labels.1)])?;
+ let out = bundle
+ .cache_dir()
+ .join("renders")
+ .join(format!("diff-{}.png", entry.seq));
+ write_atomic(&out, &pair.png()?)?;
+ println!("#{} {}: {}", entry.seq, entry.author, entry.summary);
+ println!("{}", out.display());
+ Ok(())
+}
+
+pub fn selection(path: &Path, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let Some(sel) = klad_core::notes::read_selection(&bundle) else {
+ println!("nothing selected in the editor");
+ return Ok(());
+ };
+ let nodes: Vec<serde_json::Value> = sel
+ .nodes
+ .iter()
+ .map(|id| {
+ let bounds = crate::agent::item_box(&bundle, id, sel.frame).ok().flatten();
+ let kind = match (bundle.doc.item(id), crate::agent::find_mark(&bundle, id).ok().flatten()) {
+ (Some(klad_core::doc::Item::Node(_, _, n)), _) => format!("{} {}", n.type_name(), n.name),
+ (_, Some((_, klad_core::stroke::Mark::Stroke(s)))) => format!("stroke {} {:.1}px", s.brush, s.size),
+ (_, Some((_, klad_core::stroke::Mark::Fill(_)))) => "fill".into(),
+ _ => "missing".into(),
+ };
+ json!({ "id": id, "what": kind.trim(), "bounds": bounds })
+ })
+ .collect();
+ let layer = sel.layer.as_deref().and_then(|id| bundle.doc.layer(id));
+ if as_json {
+ let value = json!({
+ "layer": layer.map(|l| json!({ "id": l.id, "name": l.name, "kind": l.kind().name() })),
+ "nodes": nodes,
+ "frame": sel.frame,
+ "atMs": sel.at_ms,
+ });
+ println!("{}", serde_json::to_string_pretty(&value)?);
+ return Ok(());
+ }
+ let at = if bundle.doc.timeline.frames > 1 {
+ format!(" on frame {}", sel.frame)
+ } else {
+ String::new()
+ };
+ println!("selected {}{at}", ago(sel.at_ms));
+ if let Some(l) = layer {
+ println!("layer {} {} ({})", l.id, l.name, l.kind().name());
+ }
+ nodes.iter().for_each(|n| {
+ let b = n["bounds"].as_array().map_or("".into(), |b| {
+ let v: Vec<f64> = b.iter().filter_map(|x| x.as_f64()).collect();
+ format!("{:.0},{:.0} {:.0}x{:.0}", v[0], v[1], v[2], v[3])
+ });
+ println!(
+ "{} {} {b}",
+ n["id"].as_str().unwrap_or(""),
+ n["what"].as_str().unwrap_or("")
+ );
+ });
+ if let Some(first) = sel.nodes.first().or(sel.layer.as_ref()) {
+ let frame = if sel.frame > 0 {
+ format!(" --frame {}", sel.frame)
+ } else {
+ String::new()
+ };
+ println!(
+ "look: klad render {}{frame} --focus {first} --overlay ids,bbox",
+ path.display()
+ );
+ }
+ Ok(())
+}
+
+pub fn notes(path: &Path, done: Option<u32>, all: bool, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ if let Some(id) = done {
+ if !klad_core::notes::set_done(&bundle, id, true)? {
+ bail!("no note #{id}");
+ }
+ println!("note #{id} marked done");
+ return Ok(());
+ }
+ let list: Vec<klad_core::notes::Note> = klad_core::notes::read(&bundle)
+ .into_iter()
+ .filter(|n| all || !n.done)
+ .collect();
+ if as_json {
+ println!("{}", serde_json::to_string_pretty(&list)?);
+ return Ok(());
+ }
+ if list.is_empty() {
+ println!("no open notes");
+ }
+ list.iter().for_each(|n| {
+ let state = if n.done { " (done)" } else { "" };
+ println!(
+ "#{} at {:.0},{:.0} frame {} by {} {}{state}: {}",
+ n.id,
+ n.x,
+ n.y,
+ n.frame,
+ n.author,
+ ago(n.at_ms),
+ n.text
+ );
+ let r = 160.0;
+ println!(
+ " look: klad render {} --region {:.0},{:.0},{:.0},{:.0} --overlay ids,bbox",
+ path.display(),
+ (n.x - r).max(0.0),
+ (n.y - r).max(0.0),
+ r * 2.0,
+ r * 2.0
+ );
+ });
+ Ok(())
+}
diff --git a/crates/cli/src/inbetween.rs b/crates/cli/src/inbetween.rs
new file mode 100644
index 0000000..72ce64f
--- /dev/null
+++ b/crates/cli/src/inbetween.rs
@@ -0,0 +1,1232 @@
+use crate::colour::needs_vectors;
+use crate::layers::{self, Vectors};
+use anyhow::{Result, anyhow, bail};
+use klad_brush::{BrushSet, Raster, accepts, flood, nearest_accepted, paint_fill, polygon, replay_onto};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Cel, Document, Kind, Layer, Loc, Tween};
+use klad_core::fill::{FillRef, FillSource};
+use klad_core::markedit::address;
+use klad_core::ops::{InbetweenSpec, Inbetweens, Op, TweenCel, apply_all};
+use klad_core::stroke::Mark;
+use klad_core::tween::{self, Anchor, Lines, Match, Plan, Unpaired, made_hash};
+use klad_render::{Rasters, fill_reference};
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+use std::time::Instant;
+
+struct Key {
+ layer: String,
+ name: String,
+ a: String,
+ b: String,
+ a_frame: u32,
+ plan: Plan,
+ parts: Vec<String>,
+ unpaired: Unpaired,
+}
+
+struct Kept {
+ index: usize,
+ hand: Vec<Mark>,
+ before: Vec<Mark>,
+ parts: BTreeMap<String, Vec<u32>>,
+}
+
+fn parts_of(doc: &Document, cel: &str) -> BTreeMap<String, Vec<u32>> {
+ match doc.locate(cel) {
+ Some(Loc::Cel(path, c)) => doc.layer_at(&path).cels()[c].parts.clone(),
+ _ => BTreeMap::new(),
+ }
+}
+
+type Group = (Vec<u32>, Vec<u32>);
+type Line = Vec<(f32, f32)>;
+
+fn shared_parts(doc: &Document, a: &str, b: &str) -> (Vec<String>, Vec<Group>) {
+ let (pa, pb) = (parts_of(doc, a), parts_of(doc, b));
+ pa.iter()
+ .filter_map(|(name, xs)| pb.get(name).map(|ys| (name.clone(), (xs.clone(), ys.clone()))))
+ .unzip()
+}
+
+fn key(
+ bundle: &Bundle,
+ layer: &Layer,
+ (a, b): (&str, &str),
+ a_frame: u32,
+ (how, pairs, unpaired): (Match, &[[u32; 2]], Unpaired),
+) -> Result<Key> {
+ let (names, groups) = shared_parts(&bundle.doc, a, b);
+ Ok(Key {
+ layer: layer.id.clone(),
+ name: layer.name.clone(),
+ a: a.to_string(),
+ b: b.to_string(),
+ a_frame,
+ plan: tween::plan_parts(
+ &bundle.read_marks(&layer.id, a)?,
+ &bundle.read_marks(&layer.id, b)?,
+ how,
+ pairs,
+ &groups,
+ ),
+ parts: names,
+ unpaired,
+ })
+}
+
+fn kept_on_top(made: &mut [TweenCel], kept: Vec<Kept>, notes: &mut Vec<String>) {
+ kept.into_iter().for_each(|k| {
+ let cel = &mut made[k.index];
+ let old: BTreeMap<u32, &Mark> = k.before.iter().map(|m| (m.id(), m)).collect();
+ let aligned: Vec<(u32, Line, Line)> = cel
+ .marks
+ .iter()
+ .filter_map(Mark::as_stroke)
+ .filter_map(|s| {
+ let before = old.get(&s.id)?.as_stroke()?;
+ Some((s.id, tween::line_of(before), tween::line_of(s)))
+ })
+ .collect();
+ let ids: Vec<u32> = aligned.iter().map(|a| a.0).collect();
+ let (from, to): (Lines, Lines) = aligned.into_iter().map(|(_, a, b)| (a, b)).unzip();
+ let mut next = cel.marks.iter().map(Mark::id).max().unwrap_or(0) + 1;
+ let count = k.hand.len();
+ k.hand.into_iter().for_each(|hand| {
+ let part = k
+ .parts
+ .iter()
+ .find(|(_, list)| list.contains(&hand.id()))
+ .map(|(n, _)| n.clone());
+ let within: Option<Vec<usize>> = part.as_ref().map(|name| {
+ let members = &k.parts[name];
+ ids.iter()
+ .enumerate()
+ .filter(|(_, id)| members.contains(id))
+ .map(|(i, _)| i)
+ .collect()
+ });
+ let within = within.filter(|w| !w.is_empty());
+ let mut moved = match &hand {
+ Mark::Fill(f) if matches!(f.source, FillSource::Seed { .. }) => hand.clone(),
+ _ => tween::carry(&hand, &from, &to, within.as_deref()),
+ };
+ moved.set_id(next);
+ if let Some(name) = part {
+ cel.parts.entry(name).or_default().push(next);
+ }
+ next += 1;
+ cel.marks.push(moved);
+ });
+ notes.push(format!(
+ " {}: {count} mark{} drawn by hand kept on top",
+ cel.cel,
+ if count == 1 { "" } else { "s" }
+ ));
+ });
+}
+
+fn keep_parts(doc: &Document, made: &mut [TweenCel]) {
+ made.iter_mut().for_each(|c| {
+ let ids: BTreeSet<u32> = c.marks.iter().map(Mark::id).collect();
+ c.parts = parts_of(doc, &c.tween.from)
+ .into_iter()
+ .map(|(name, list)| (name, list.into_iter().filter(|i| ids.contains(i)).collect::<Vec<_>>()))
+ .filter(|(_, list)| !list.is_empty())
+ .collect();
+ });
+}
+
+struct Job {
+ key: usize,
+ index: usize,
+ frame: u32,
+ t: f32,
+}
+
+struct Done {
+ index: usize,
+ marks: Vec<Mark>,
+ failed: Vec<String>,
+}
+
+fn source(cel: &Cel) -> String {
+ cel.link.clone().unwrap_or_else(|| cel.id.clone())
+}
+
+fn paint_layers(doc: &Document, keys: &[String]) -> Result<Vec<String>> {
+ fn walk(layer: &Layer, out: &mut Vec<String>) -> Result<()> {
+ match layer.kind() {
+ Kind::Paint => {
+ out.push(layer.id.clone());
+ Ok(())
+ }
+ Kind::Group => layer.children().iter().try_for_each(|c| walk(c, out)),
+ Kind::Vector => bail!("{} is a vector layer; in-betweens are made on paint layers", layer.id),
+ Kind::Adjust => bail!(
+ "{} is an adjustment layer; in-betweens are made on paint layers",
+ layer.id
+ ),
+ }
+ }
+ let mut out = Vec::new();
+ keys.iter().try_for_each(|k| walk(doc.find_layer(k)?, &mut out))?;
+ let mut seen = BTreeSet::new();
+ out.retain(|id| seen.insert(id.clone()));
+ Ok(out)
+}
+
+fn spread(from: u32, to: u32, count: u32) -> Vec<u32> {
+ let span = (to - from) as u64;
+ (1..=count as u64)
+ .map(|i| from + ((2 * i * span + count as u64 + 1) / (2 * (count as u64 + 1))) as u32)
+ .collect()
+}
+
+fn describe(t: f32) -> String {
+ format!("{:.2}", t)
+ .trim_end_matches('0')
+ .trim_end_matches('.')
+ .to_string()
+}
+
+fn tween_of(key: &Key, t: f32, spec: &InbetweenSpec) -> Tween {
+ Tween {
+ from: key.a.clone(),
+ to: key.b.clone(),
+ t,
+ matching: match spec.matching {
+ Match::Id => String::new(),
+ other => other.name().to_string(),
+ },
+ pairs: spec.pairs.clone(),
+ made: String::new(),
+ unpaired: spec.unpaired.name(),
+ }
+}
+
+fn pairing_notes(key: &Key, notes: &mut Vec<String>) {
+ let p = &key.plan.pairing;
+ let mut line = format!(
+ "{}: {} -> {}, {} marks paired ({} flood fills)",
+ key.name,
+ key.a,
+ key.b,
+ p.pairs.len(),
+ key.plan.floods().len()
+ );
+ if !key.parts.is_empty() {
+ line.push_str(&format!(", by part first: {}", key.parts.join(", ")));
+ }
+ let touching = key.plan.touching_ends();
+ if touching > 0 {
+ line.push_str(&format!(", {touching} line ends kept touching"));
+ }
+ notes.push(line);
+ let alone: Vec<String> = p
+ .alone_a
+ .iter()
+ .map(|id| format!("{} (only in the first key)", address(&key.a, *id)))
+ .chain(
+ p.alone_b
+ .iter()
+ .map(|id| format!("{} (only in the second key)", address(&key.b, *id))),
+ )
+ .chain(p.clashes.iter().map(|(x, y)| {
+ format!(
+ "{} and {} (one is a stroke or lasso fill, the other not)",
+ address(&key.a, *x),
+ address(&key.b, *y)
+ )
+ }))
+ .collect();
+ if !alone.is_empty() {
+ let how = match key.unpaired {
+ Unpaired::Leave => "left out".to_string(),
+ other => format!("{} (flood fills left out)", other.name()),
+ };
+ notes.push(format!(" unpaired, {how}: {}", alone.join(", ")));
+ }
+}
+
+pub fn resolve(bundle: &Bundle, ops: &mut [Op]) -> Result<Vec<String>> {
+ if !ops.iter().any(|op| matches!(op, Op::Inbetween(_))) {
+ return Ok(Vec::new());
+ }
+ if ops.len() > 1 {
+ bail!("an inbetween op needs a batch of its own: it reads its keys from the bundle as it is");
+ }
+ let Op::Inbetween(spec) = &mut ops[0] else {
+ unreachable!("checked above");
+ };
+ if spec.resolved.is_some() {
+ return Ok(Vec::new());
+ }
+ let start = Instant::now();
+ let (made, mut notes) = match spec.redo {
+ true => redo(bundle, spec)?,
+ false => make(bundle, spec)?,
+ };
+ let frames: BTreeSet<u32> = made.cels.iter().map(|c| c.frame).collect();
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ notes.push(format!(
+ "{} in-between{} on {} frame{} in {:.0} ms ({:.0} ms per frame)",
+ made.cels.len(),
+ if made.cels.len() == 1 { "" } else { "s" },
+ frames.len(),
+ if frames.len() == 1 { "" } else { "s" },
+ ms,
+ ms / frames.len().max(1) as f64
+ ));
+ spec.resolved = Some(made);
+ Ok(notes)
+}
+
+fn make(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<String>)> {
+ let doc = &bundle.doc;
+ let Some(from) = spec.from else {
+ bail!("give the frames of the two keys: --from and --to");
+ };
+ let span = doc
+ .timeline
+ .clip_at(from)
+ .map_or((0, doc.timeline.frames), |c| (c.from, c.to + 1));
+ let to = match (spec.to, spec.looping) {
+ (Some(to), _) => to,
+ (None, true) => span.1,
+ (None, false) => bail!("give the frames of the two keys: --from and --to"),
+ };
+ if to <= from + 1 {
+ bail!("there is no frame between the keys at {from} and {to}");
+ }
+ let room = to - from - 1;
+ let count = match (spec.count, spec.spacing.count()) {
+ (Some(c), Some(n)) if c as usize != n => {
+ bail!("--count {c} and {n} spacing values disagree; give one of them")
+ }
+ (Some(c), _) => c,
+ (None, Some(n)) => n as u32,
+ (None, None) => room,
+ };
+ if count > room {
+ bail!(
+ "{count} in-betweens do not fit between frames {from} and {to}: there are {room} frames; give --count {room} or less"
+ );
+ }
+ let frames = spread(from, to, count);
+ let ts = spec.spacing.ts(count as usize);
+ let mut staged = doc.clone();
+ let mut taken = staged.ids();
+ let mut keys = Vec::new();
+ let mut made = Inbetweens::default();
+ let mut notes = Vec::new();
+ let mut jobs = Vec::new();
+ paint_layers(doc, &spec.layers)?.into_iter().try_for_each(|layer| {
+ let owner = doc.layer(&layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let name = owner.name.clone();
+ let at_a = owner
+ .cel_at(from)
+ .ok_or_else(|| anyhow!("{name} shows nothing at frame {from}, so it has no first key there"))?;
+ let at_b = match spec.looping {
+ true => owner.cel_at(span.0).ok_or_else(|| {
+ anyhow!(
+ "{name} shows nothing at frame {}, the loop's first frame, so the loop has no first drawing",
+ span.0
+ )
+ })?,
+ false => owner
+ .cel_at(to)
+ .ok_or_else(|| anyhow!("{name} shows nothing at frame {to}, so it has no second key there"))?,
+ };
+ if !spec.looping && at_b.frame != to {
+ bail!(
+ "frame {to} of {name} shows {} from frame {}: the second key is the frame where a drawing starts (--to {})",
+ at_b.id,
+ at_b.frame,
+ at_b.frame
+ );
+ }
+ let (a, b) = (source(at_a), source(at_b));
+ if a == b {
+ notes.push(format!("{name} shows {a} at both keys; left as it is"));
+ return Ok(());
+ }
+ let inside: Vec<&Cel> = owner.cels().iter().filter(|c| c.frame > from && c.frame < to).collect();
+ let foreign: Vec<&str> = inside
+ .iter()
+ .filter(|c| !c.tween.as_ref().is_some_and(|t| t.from == a && t.to == b))
+ .map(|c| c.id.as_str())
+ .collect();
+ if !foreign.is_empty() && !spec.force {
+ bail!(
+ "frames {} to {} of {name} already hold {}, which are not in-betweens of {a} and {b}; remove them, or --force replaces them",
+ from + 1,
+ to - 1,
+ foreign.join(", ")
+ );
+ }
+ let changed: Vec<String> = inside
+ .iter()
+ .filter(|c| !foreign.contains(&c.id.as_str()))
+ .map(|c| Ok((c, bundle.read_marks(&layer, &c.id)?)))
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .filter(|(c, marks)| c.tween.as_ref().is_some_and(|t| made_hash(marks) != t.made))
+ .map(|(c, _)| c.id.clone())
+ .collect();
+ if !changed.is_empty() && !spec.force {
+ bail!(
+ "{} on {name} were changed after they were made (drawn on or edited); remove them, or --force replaces them",
+ changed.join(", ")
+ );
+ }
+ made.removed.extend(inside.iter().map(|c| c.id.clone()));
+ made.holds.push((at_a.id.clone(), frames[0] - at_a.frame));
+ let key = key(
+ bundle,
+ owner,
+ (&a, &b),
+ from,
+ (spec.matching, &spec.pairs, spec.unpaired),
+ )?;
+ frames.iter().zip(&ts).enumerate().for_each(|(i, (&frame, &t))| {
+ let next = frames.get(i + 1).copied().unwrap_or(to);
+ jobs.push(Job {
+ key: keys.len(),
+ index: made.cels.len(),
+ frame,
+ t,
+ });
+ made.cels.push(TweenCel {
+ layer: layer.clone(),
+ cel: staged.alloc_id_in('c', &mut taken),
+ frame,
+ hold: Some(next - frame),
+ tween: tween_of(&key, t, spec),
+ marks: Vec::new(),
+ fresh: true,
+ parts: BTreeMap::new(),
+ });
+ });
+ keys.push(key);
+ Ok(())
+ })?;
+ if made.cels.is_empty() {
+ bail!("nothing to in-between: every layer shows the same drawing at both keys");
+ }
+ let (staged, _) = apply_all(
+ doc,
+ &[Op::Inbetween(InbetweenSpec {
+ resolved: Some(made.clone()),
+ ..spec.clone()
+ })],
+ )?;
+ keys.iter().for_each(|k| pairing_notes(k, &mut notes));
+ compute(bundle, &staged, &keys, &jobs, &mut made.cels, &mut notes)?;
+ keep_parts(doc, &mut made.cels);
+ made.cels.iter().for_each(|c| {
+ notes.push(format!(
+ " {} at frame {} (t {}) on {}",
+ c.cel,
+ c.frame,
+ describe(c.tween.t),
+ c.layer
+ ))
+ });
+ Ok((made, notes))
+}
+
+fn redo(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<String>)> {
+ let doc = &bundle.doc;
+ let wanted: Option<Vec<String>> = (!spec.layers.is_empty())
+ .then(|| paint_layers(doc, &spec.layers))
+ .transpose()?;
+ let mut keys: Vec<Key> = Vec::new();
+ let mut made = Inbetweens::default();
+ let mut jobs = Vec::new();
+ let mut refused = Vec::new();
+ let mut notes = Vec::new();
+ let mut kept = Vec::new();
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Paint)
+ .filter(|l| wanted.as_ref().is_none_or(|w| w.contains(&l.id)))
+ .flat_map(|l| l.cels().iter().map(move |c| (l, c)))
+ .filter(|(_, c)| spec.from.is_none_or(|f| c.frame >= f) && spec.to.is_none_or(|t| c.frame <= t))
+ .filter(|(_, c)| spec.only.is_empty() || spec.only.contains(&c.id))
+ .try_for_each(|(layer, cel)| {
+ let Some(tween) = &cel.tween else {
+ return Ok(());
+ };
+ let drawing = |id: &str| layer.cels().iter().find(|c| c.id == id && c.link.is_none());
+ let (Some(first), Some(_)) = (drawing(&tween.from), drawing(&tween.to)) else {
+ bail!(
+ "{} is an in-between of {} and {}, but {} has no such drawing any more",
+ cel.id,
+ tween.from,
+ tween.to,
+ layer.name
+ );
+ };
+ let marks = bundle.read_marks(&layer.id, &cel.id)?;
+ let human = |m: &Mark| m.author() == klad_core::stroke::Author::Human;
+ let keep_drawn = spec.keep_drawn || spec.keep_cels.contains(&cel.id);
+ let force = spec.force || spec.force_cels.contains(&cel.id);
+ if made_hash(&marks) != tween.made && keep_drawn {
+ let (hand, before): (Vec<Mark>, Vec<Mark>) = marks.iter().cloned().partition(|m| human(m));
+ if made_hash(&before) != tween.made {
+ notes.push(format!(
+ " {}: marks the agent made were edited too; they are made again from the keys",
+ cel.id
+ ));
+ }
+ kept.push(Kept {
+ index: made.cels.len(),
+ hand,
+ before,
+ parts: cel.parts.clone(),
+ });
+ } else if made_hash(&marks) != tween.made && !force {
+ let hand = marks.iter().filter(|m| human(m)).count();
+ refused.push(match hand {
+ 0 => format!("{} (changed since it was made)", cel.id),
+ n => format!("{} ({n} mark{} drawn by hand)", cel.id, if n == 1 { "" } else { "s" }),
+ });
+ return Ok(());
+ }
+ let pairs = tween.pairs.clone();
+ let matching = Match::parse(&tween.matching)?;
+ let unpaired = Unpaired::parse(&tween.unpaired)?;
+ let at = match keys
+ .iter()
+ .position(|k| k.layer == layer.id && k.a == tween.from && k.b == tween.to)
+ {
+ Some(at) => at,
+ None => {
+ keys.push(key(
+ bundle,
+ layer,
+ (&tween.from, &tween.to),
+ first.frame,
+ (matching, &pairs, unpaired),
+ )?);
+ keys.len() - 1
+ }
+ };
+ jobs.push(Job {
+ key: at,
+ index: made.cels.len(),
+ frame: cel.frame,
+ t: tween.t,
+ });
+ made.cels.push(TweenCel {
+ layer: layer.id.clone(),
+ cel: cel.id.clone(),
+ frame: cel.frame,
+ hold: cel.hold,
+ tween: tween.clone(),
+ marks: Vec::new(),
+ fresh: false,
+ parts: BTreeMap::new(),
+ });
+ Ok(())
+ })?;
+ if !refused.is_empty() {
+ bail!(
+ "these in-betweens were changed after they were made, so --redo leaves them: {}; --keep-drawn remakes them and keeps the marks drawn by hand on top, --force remakes them all",
+ refused.join(", ")
+ );
+ }
+ if made.cels.is_empty() {
+ bail!("no in-betweens to redo here (klad inbetween marks the cels it makes; klad frames shows them)");
+ }
+ keys.iter().for_each(|k| pairing_notes(k, &mut notes));
+ compute(bundle, doc, &keys, &jobs, &mut made.cels, &mut notes)?;
+ keep_parts(doc, &mut made.cels);
+ kept_on_top(&mut made.cels, kept, &mut notes);
+ Ok((made, notes))
+}
+
+fn depends(keys: &[Key], jobs: &[&Job], j: usize, k: usize) -> bool {
+ let key = &keys[jobs[j].key];
+ let other = &keys[jobs[k].key].layer;
+ key.plan.floods().iter().any(|(a, _)| match a.reference() {
+ Some(FillRef::Layer(id)) => id == other,
+ Some(FillRef::All) => true,
+ _ => false,
+ })
+}
+
+fn ordered<'a>(keys: &[Key], jobs: Vec<&'a Job>) -> Vec<&'a Job> {
+ let mut left: Vec<usize> = (0..jobs.len()).collect();
+ let mut out = Vec::new();
+ while !left.is_empty() {
+ let ready = left
+ .iter()
+ .position(|&j| {
+ !left
+ .iter()
+ .any(|&k| k != j && depends(keys, &jobs, j, k) && !depends(keys, &jobs, k, j))
+ })
+ .unwrap_or(0);
+ out.push(jobs[left.remove(ready)]);
+ }
+ out
+}
+
+fn accept_colours(bundle: &Bundle, keys: &[Key], brushes: &BrushSet) -> Result<BTreeMap<(usize, u32), [f32; 4]>> {
+ keys.iter()
+ .enumerate()
+ .filter(|(_, k)| !k.plan.floods().is_empty())
+ .map(|(i, key)| {
+ let ids: Vec<u32> = key.plan.floods().iter().map(|(a, _)| a.id).collect();
+ let marks = bundle.read_marks(&key.layer, &key.a)?;
+ let found = crate::colour::seed_colours(bundle, &key.a, key.a_frame, &marks, &ids, brushes)?;
+ Ok(found.into_iter().map(move |(id, c)| ((i, id), c)))
+ })
+ .collect::<Result<Vec<_>>>()
+ .map(|v| v.into_iter().flatten().collect())
+}
+
+fn lines_now(marks: &[Mark]) -> Lines {
+ marks.iter().filter_map(Mark::as_stroke).map(tween::line_of).collect()
+}
+
+fn compute(
+ bundle: &Bundle,
+ staged: &Document,
+ keys: &[Key],
+ jobs: &[Job],
+ cels: &mut [TweenCel],
+ notes: &mut Vec<String>,
+) -> Result<()> {
+ let brushes = BrushSet::for_bundle(bundle)?;
+ let accept = accept_colours(bundle, keys, &brushes)?;
+ let view = Bundle {
+ root: bundle.root.clone(),
+ doc: staged.clone(),
+ };
+ let frames: BTreeSet<u32> = jobs.iter().map(|j| j.frame).collect();
+ let ids: Vec<String> = cels.iter().map(|c| c.cel.clone()).collect();
+ let done = frames
+ .par_iter()
+ .map(|&frame| {
+ let here: Vec<&Job> = jobs.iter().filter(|j| j.frame == frame).collect();
+ frame_job(&view, &brushes, keys, ordered(keys, here), frame, &ids, &accept)
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let mut failed = Vec::new();
+ done.into_iter().flatten().for_each(|d| {
+ cels[d.index].tween.made = made_hash(&d.marks);
+ cels[d.index].marks = d.marks;
+ failed.extend(d.failed);
+ });
+ if !failed.is_empty() {
+ notes.push(format!(" fills left out: {}", failed.join("; ")));
+ }
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+fn frame_job(
+ view: &Bundle,
+ brushes: &BrushSet,
+ keys: &[Key],
+ jobs: Vec<&Job>,
+ frame: u32,
+ ids: &[String],
+ accept: &BTreeMap<(usize, u32), [f32; 4]>,
+) -> Result<Vec<Done>> {
+ let doc = &view.doc;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let mut rasters: Rasters = layers::load(view, frame, brushes, true)?.rasters;
+ if jobs.iter().any(|j| {
+ keys[j.key]
+ .plan
+ .floods()
+ .iter()
+ .any(|(a, _)| needs_vectors(doc, a.reference()))
+ }) {
+ Vectors::default().add_to(doc, frame, &mut rasters)?;
+ }
+ let mut lines_at: BTreeMap<String, (Lines, Lines, Lines)> = BTreeMap::new();
+ jobs.iter()
+ .map(|job| {
+ let key = &keys[job.key];
+ let cel = &ids[job.index];
+ let mut marks = key.plan.at(job.t);
+ let (la, lb) = key.plan.key_lines();
+ let now = lines_now(&marks);
+ let extra = key.plan.unpaired_at(job.t, key.unpaired, &now);
+ lines_at.insert(key.layer.clone(), (la, lb, now));
+ let mut own = Raster::new(w, h);
+ let mut failed = Vec::new();
+ let mut keep = vec![true; marks.len()];
+ let floods = key.plan.floods();
+ (0..marks.len()).try_for_each(|m| {
+ if marks[m].as_stroke().is_some() {
+ replay_onto(&mut own, std::slice::from_ref(&marks[m]), brushes)?;
+ return Ok::<_, anyhow::Error>(());
+ }
+ match &mut marks[m] {
+ Mark::Stroke(_) => {}
+ Mark::Fill(fill) => {
+ let id = fill.id;
+ let what = |why: String| format!("{} at frame {frame}: {why}", address(&key.a, id));
+ match fill.source.clone() {
+ FillSource::Polygon(points) => fill.coverage = polygon(&points, w, h),
+ FillSource::Seed { mut seed, reference } => {
+ let Some((a, b)) = floods.iter().find(|(a, _)| a.id == id) else {
+ return Ok(());
+ };
+ rasters.insert(cel.clone(), own.clone());
+ let image = fill_reference(doc, frame, &rasters, cel, &reference)?;
+ let lines = match &reference {
+ FillRef::This => lines_at.get(&key.layer).cloned(),
+ FillRef::Layer(other) => lines_at.get(other).cloned(),
+ FillRef::All => Some(lines_at.values().fold(
+ (Vec::new(), Vec::new(), Vec::new()),
+ |(mut x, mut y, mut z), (a, b, c)| {
+ x.extend(a.iter().cloned());
+ y.extend(b.iter().cloned());
+ z.extend(c.iter().cloned());
+ (x, y, z)
+ },
+ )),
+ };
+ let (sa, sb) = match (&a.source, &b.source) {
+ (FillSource::Seed { seed: x, .. }, FillSource::Seed { seed: y, .. }) => {
+ ((x.x, x.y), (y.x, y.y))
+ }
+ _ => unreachable!("floods pair with floods"),
+ };
+ let carried = lines.and_then(|(la, lb, lt)| {
+ let at = |anchor: Option<Anchor>| anchor.and_then(|an| tween::place(&an, &lt));
+ Some((at(tween::anchor(&la, sa))?, at(tween::anchor(&lb, sb))?))
+ });
+ let t = job.t;
+ let ((ax, ay), (bx, by)) = carried.unwrap_or((sa, sb));
+ seed.x = ax + (bx - ax) * t;
+ seed.y = ay + (by - ay) * t;
+ let colour = accept.get(&(job.key, id)).copied().unwrap_or([0.0; 4]);
+ let reach = 12 + seed.gap.ceil() as u32;
+ if !accepts(&image, seed.x, seed.y, colour, seed.tolerance) {
+ match nearest_accepted(&image, [seed.x, seed.y], colour, seed.tolerance, reach) {
+ Some([x, y]) => (seed.x, seed.y) = (x, y),
+ None => {
+ failed.push(what("its seed lands on a line".into()));
+ keep[m] = false;
+ return Ok(());
+ }
+ }
+ }
+ fill.source = FillSource::Seed {
+ seed,
+ reference: reference.clone(),
+ };
+ fill.coverage = flood(&image, &seed);
+ let px = fill.coverage.pixels() as f32;
+ let (pa, pb) = (a.coverage.pixels() as f32, b.coverage.pixels() as f32);
+ let expected = pa + (pb - pa) * t;
+ if px > expected * 1.6 + 64.0 {
+ failed.push(what(format!(
+ "it leaked ({px:.0} px where the keys have {pa:.0} and {pb:.0})"
+ )));
+ keep[m] = false;
+ return Ok(());
+ }
+ if px < expected * 0.4 {
+ failed.push(what(format!(
+ "it found a smaller region ({px:.0} px where the keys have {pa:.0} and {pb:.0})"
+ )));
+ keep[m] = false;
+ return Ok(());
+ }
+ }
+ }
+ if fill.coverage.is_empty() {
+ failed.push(what("it covers no pixels".into()));
+ keep[m] = false;
+ return Ok(());
+ }
+ paint_fill(&mut own, fill);
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let mut kept: Vec<Mark> = marks
+ .into_iter()
+ .zip(keep)
+ .filter(|(_, k)| *k)
+ .map(|(m, _)| m)
+ .collect();
+ let mut next = kept.iter().chain(&extra).map(Mark::id).max().unwrap_or(0) + 1;
+ let taken: BTreeSet<u32> = kept.iter().map(Mark::id).collect();
+ extra.into_iter().try_for_each(|mut m| {
+ if taken.contains(&m.id()) || key.plan.pairing.alone_b.contains(&m.id()) {
+ m.set_id(next);
+ next += 1;
+ }
+ if let Mark::Fill(f) = &mut m
+ && let FillSource::Polygon(points) = &f.source
+ {
+ f.coverage = polygon(points, w, h);
+ paint_fill(&mut own, f);
+ } else {
+ replay_onto(&mut own, std::slice::from_ref(&m), brushes)?;
+ }
+ kept.push(m);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ rasters.insert(cel.clone(), own);
+ Ok(Done {
+ index: job.index,
+ marks: kept,
+ failed,
+ })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use crate::agent::Output;
+ use klad_core::doc::Layer;
+ use klad_core::ops::parse_lines;
+ use klad_core::stroke::Stroke;
+ use std::fs;
+
+ fn scratch(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-tween-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ fn quiet() -> Output {
+ Output {
+ json: false,
+ render: false,
+ scale: None,
+ frame: 0,
+ overlay: None,
+ }
+ }
+
+ fn line(points: &[(f32, f32)], size: f32) -> String {
+ let path: Vec<String> = points.iter().map(|(x, y)| format!("{x} {y}")).collect();
+ format!(
+ r##"{{"op":"stroke","layer":"lines","brush":"ink","size":{size},"color":"#202020","taper":[0,0],"path":"M{}"}}"##,
+ path.join(" L")
+ )
+ }
+
+ pub(crate) fn swing(name: &str) -> std::path::PathBuf {
+ let dir = scratch(name);
+ let mut doc = Document::new(320, 320);
+ doc.timeline.frames = 8;
+ let mut colour = Layer::paint("colour", "colour", "col0");
+ colour.cels_mut().unwrap()[0].hold = Some(6);
+ let mut lines = Layer::paint("lines", "lines", "ln0");
+ lines.cels_mut().unwrap()[0].hold = Some(6);
+ doc.layers = vec![colour, lines];
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let (x, y) = (80.0, 100.0);
+ let text = [
+ line(&[(x, y - 16.0), (x + 150.0, y - 16.0)], 4.0),
+ line(&[(x, y + 16.0), (x + 150.0, y + 16.0)], 4.0),
+ line(&[(x, y - 16.0), (x, y + 16.0)], 4.0),
+ line(&[(x + 150.0, y - 16.0), (x + 150.0, y + 16.0)], 4.0),
+ line(
+ &[
+ (x + 150.0, y - 16.0),
+ (x + 180.0, y - 10.0),
+ (x + 180.0, y + 10.0),
+ (x + 150.0, y + 16.0),
+ ],
+ 4.0,
+ ),
+ r##"{"op":"fill","layer":"colour","at":[120,100],"ref":"lines","gap":3,"color":"#d04030"}"##.to_string(),
+ r##"{"op":"fill","layer":"colour","at":[245,100],"ref":"lines","gap":3,"color":"#f0e0c0"}"##.to_string(),
+ r#"{"op":"cel","dup":"ln0","frame":6,"id":"ln6"}"#.to_string(),
+ r#"{"op":"cel","dup":"col0","frame":6,"id":"col6"}"#.to_string(),
+ r#"{"op":"transform","ids":["ln6:s1","ln6:s2","ln6:s3","ln6:s4","ln6:s5"],"rotate":60,"pivot":[80,100]}"#
+ .to_string(),
+ r#"{"op":"transform","ids":["col6:s1","col6:s2"],"rotate":60,"pivot":[80,100]}"#.to_string(),
+ ]
+ .join("\n");
+ let mut ops = parse_lines(&text).unwrap();
+ crate::fills::resolve(&bundle, &mut ops).unwrap();
+ bundle.apply(&ops).unwrap();
+ crate::fills::refill(&dir, "colour", 6, None, &quiet()).unwrap();
+ dir
+ }
+
+ fn inbetween(dir: &std::path::Path, spec: InbetweenSpec) -> Result<()> {
+ crate::agent::edit(dir, &[Op::Inbetween(spec)], &quiet())
+ }
+
+ fn keys() -> InbetweenSpec {
+ InbetweenSpec {
+ layers: vec!["lines".into(), "colour".into()],
+ from: Some(0),
+ to: Some(6),
+ ..InbetweenSpec::default()
+ }
+ }
+
+ fn stroked(points: &[(f32, f32)], frame: u32, part: &str) -> String {
+ let path: Vec<String> = points.iter().map(|(x, y)| format!("{x} {y}")).collect();
+ let part = match part {
+ "" => String::new(),
+ name => format!(r#","part":"{name}""#),
+ };
+ format!(
+ r##"{{"op":"stroke","layer":"lines","frame":{frame},"brush":"ink","size":4,"color":"#202020","taper":[0,0]{part},"path":"M{}"}}"##,
+ path.join(" L")
+ )
+ }
+
+ fn two_keys(name: &str, second: &[String]) -> std::path::PathBuf {
+ let dir = scratch(name);
+ let mut doc = Document::new(320, 320);
+ doc.timeline.frames = 8;
+ let mut lines = Layer::paint("lines", "lines", "a0");
+ lines.cels_mut().unwrap()[0].hold = Some(6);
+ doc.layers = vec![lines];
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let text = [
+ stroked(&[(40.0, 100.0), (200.0, 100.0)], 0, "body"),
+ stroked(&[(40.0, 220.0), (120.0, 200.0), (200.0, 220.0)], 0, "leaf"),
+ r#"{"op":"cel","new":"lines","frame":6,"id":"b6"}"#.to_string(),
+ ]
+ .into_iter()
+ .chain(second.iter().cloned())
+ .chain([r#"{"op":"clip","add":"walk","from":0,"to":7,"loop":true}"#.to_string()])
+ .collect::<Vec<_>>()
+ .join("\n");
+ bundle.apply(&parse_lines(&text).unwrap()).unwrap();
+ dir
+ }
+
+ fn mean(marks: &[Mark], id: u32) -> (f32, f32) {
+ let s = marks.iter().find(|m| m.id() == id).unwrap().as_stroke().unwrap();
+ let n = s.samples.len() as f32;
+ s.samples
+ .iter()
+ .map(|q| q.pos())
+ .fold((0.0, 0.0), |a, (x, y)| (a.0 + x / n, a.1 + y / n))
+ }
+
+ fn shown_at(bundle: &Bundle, frame: u32) -> (Cel, Vec<Mark>) {
+ let cel = bundle.doc.layer("lines").unwrap().content_at(frame).unwrap().clone();
+ let marks = bundle.read_marks("lines", &cel.id).unwrap();
+ (cel, marks)
+ }
+
+ fn lines_between(from: u32, to: u32) -> InbetweenSpec {
+ InbetweenSpec {
+ layers: vec!["lines".into()],
+ from: Some(from),
+ to: Some(to),
+ ..InbetweenSpec::default()
+ }
+ }
+
+ #[test]
+ fn parts_pair_keys_drawn_separately_and_a_loop_closes_on_its_first_drawing() {
+ let dir = two_keys(
+ "parts",
+ &[
+ stroked(&[(80.0, 220.0), (160.0, 200.0), (240.0, 220.0)], 6, "leaf"),
+ stroked(&[(80.0, 100.0), (240.0, 100.0)], 6, "body"),
+ ],
+ );
+ let bundle = Bundle::open(&dir).unwrap();
+ let (a, b) = (
+ bundle.read_marks("lines", "a0").unwrap(),
+ bundle.read_marks("lines", "b6").unwrap(),
+ );
+ let by_id = tween::pair(&a, &b, Match::Id, &[]);
+ assert!(by_id.pairs.iter().any(|p| (p.a, p.b) == (1, 1)));
+ inbetween(&dir, lines_between(0, 6)).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let (mid, marks) = shown_at(&bundle, 3);
+ assert!(mid.tween.is_some());
+ assert!((mean(&marks, 1).1 - 100.0).abs() < 2.0, "{:?}", mean(&marks, 1));
+ assert!(mean(&marks, 2).1 > 190.0);
+ assert!((mean(&marks, 1).0 - 140.0).abs() < 2.0, "{:?}", mean(&marks, 1));
+ assert_eq!(mid.parts.get("body"), Some(&vec![1]));
+ assert_eq!(mid.parts.get("leaf"), Some(&vec![2]));
+ let looping = InbetweenSpec {
+ layers: vec!["lines".into()],
+ from: Some(6),
+ looping: true,
+ ..InbetweenSpec::default()
+ };
+ inbetween(&dir, looping).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ assert_eq!(bundle.doc.timeline.frames, 8);
+ let (last, marks) = shown_at(&bundle, 7);
+ let t = last.tween.clone().unwrap();
+ assert_eq!((t.from.as_str(), t.to.as_str(), last.frame), ("b6", "a0", 7));
+ let (body, leaf) = (last.parts["body"][0], last.parts["leaf"][0]);
+ assert_eq!((body, leaf), (2, 1));
+ assert!(
+ (mean(&marks, body).0 - 140.0).abs() < 2.0 && (mean(&marks, body).1 - 100.0).abs() < 2.0,
+ "{:?}",
+ mean(&marks, body)
+ );
+ assert!((mean(&marks, leaf).1 - 207.0).abs() < 8.0, "{:?}", mean(&marks, leaf));
+ assert_eq!(bundle.doc.layer("lines").unwrap().cels().len(), 8);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn marks_in_one_key_only_pop_fade_or_draw_on() {
+ let second = [
+ stroked(&[(80.0, 100.0), (240.0, 100.0)], 6, "body"),
+ stroked(&[(80.0, 220.0), (160.0, 200.0), (240.0, 220.0)], 6, "leaf"),
+ stroked(&[(250.0, 40.0), (250.0, 160.0)], 6, ""),
+ ];
+ let counts = |dir: &std::path::Path| -> Vec<usize> {
+ let bundle = Bundle::open(dir).unwrap();
+ (1..6).map(|f| shown_at(&bundle, f).1.len()).collect()
+ };
+ let extra = |dir: &std::path::Path, frame: u32| -> Option<Stroke> {
+ let (_, marks) = shown_at(&Bundle::open(dir).unwrap(), frame);
+ marks.iter().filter_map(Mark::as_stroke).find(|s| s.id > 2).cloned()
+ };
+ let leave = two_keys("leave", &second);
+ inbetween(&leave, lines_between(0, 6)).unwrap();
+ assert_eq!(counts(&leave), [2, 2, 2, 2, 2]);
+ let pop = two_keys("pop", &second);
+ inbetween(
+ &pop,
+ InbetweenSpec {
+ unpaired: Unpaired::Pop(0.5),
+ ..lines_between(0, 6)
+ },
+ )
+ .unwrap();
+ assert_eq!(counts(&pop), [2, 2, 3, 3, 3]);
+ let (cel, _) = shown_at(&Bundle::open(&pop).unwrap(), 4);
+ assert_eq!(cel.tween.unwrap().unpaired, "pop");
+ let fade = two_keys("fade", &second);
+ inbetween(
+ &fade,
+ InbetweenSpec {
+ unpaired: Unpaired::Fade,
+ ..lines_between(0, 6)
+ },
+ )
+ .unwrap();
+ assert_eq!(counts(&fade), [3, 3, 3, 3, 3]);
+ let (early, late) = (extra(&fade, 1).unwrap(), extra(&fade, 5).unwrap());
+ assert!((early.opacity - 1.0 / 6.0).abs() < 0.02, "{}", early.opacity);
+ assert!((late.opacity - 5.0 / 6.0).abs() < 0.02, "{}", late.opacity);
+ let draw_on = two_keys("drawon", &second);
+ inbetween(
+ &draw_on,
+ InbetweenSpec {
+ unpaired: Unpaired::DrawOn,
+ ..lines_between(0, 6)
+ },
+ )
+ .unwrap();
+ let (early, late) = (extra(&draw_on, 1).unwrap(), extra(&draw_on, 5).unwrap());
+ assert!(
+ early.samples.len() * 3 < late.samples.len(),
+ "{} {}",
+ early.samples.len(),
+ late.samples.len()
+ );
+ let tip = |s: &Stroke| s.samples.iter().map(|q| q.pos().1).fold(0.0f32, f32::max);
+ assert!(
+ tip(&early) < 70.0 && tip(&late) > 130.0,
+ "{} {}",
+ tip(&early),
+ tip(&late)
+ );
+ [leave, pop, fade, draw_on]
+ .iter()
+ .for_each(|d| fs::remove_dir_all(d).unwrap());
+ }
+
+ #[test]
+ fn hand_marks_stay_on_top_through_two_redos_and_move_with_their_line() {
+ let dir = swing("keep");
+ inbetween(&dir, keys()).unwrap();
+ let mut bundle = Bundle::open(&dir).unwrap();
+ let mid = bundle.doc.layer("lines").unwrap().content_at(3).unwrap().id.clone();
+ let mut drawn = bundle.read_marks("lines", &mid).unwrap();
+ let top = drawn[0].as_stroke().unwrap().clone();
+ let (x0, y0) = top.samples[top.samples.len() / 2].pos();
+ drawn.push(Mark::Stroke(
+ Stroke::new(99, "ink", [0.0, 0.0, 0.0, 1.0], 3.0, 1)
+ .with_points(&[(x0 - 6.0, y0 - 12.0, 1.0), (x0 + 6.0, y0 - 18.0, 1.0)], 8.0),
+ ));
+ bundle.replace_marks("lines", &mid, &drawn, "editor", "pen").unwrap();
+ let hand = |dir: &std::path::Path| -> Vec<Stroke> {
+ Bundle::open(dir)
+ .unwrap()
+ .read_marks("lines", &mid)
+ .unwrap()
+ .into_iter()
+ .filter(|m| m.author() == klad_core::stroke::Author::Human)
+ .filter_map(|m| m.as_stroke().cloned())
+ .collect()
+ };
+ let line = |dir: &std::path::Path| -> (f32, f32) {
+ let marks = Bundle::open(dir).unwrap().read_marks("lines", &mid).unwrap();
+ let s = marks.iter().find(|m| m.id() == 1).unwrap().as_stroke().unwrap().clone();
+ s.samples[s.samples.len() / 2].pos()
+ };
+ let keep = InbetweenSpec {
+ redo: true,
+ keep_drawn: true,
+ ..InbetweenSpec::default()
+ };
+ let shift = r#"{"op":"transform","ids":["ln6:s1","ln6:s2","ln6:s3","ln6:s4","ln6:s5"],"x":30}"#;
+ (1..=2).for_each(|round| {
+ let (start, under) = (hand(&dir)[0].samples[0].pos(), line(&dir));
+ let mut bundle = Bundle::open(&dir).unwrap();
+ bundle.apply(&parse_lines(shift).unwrap()).unwrap();
+ let plain = InbetweenSpec {
+ redo: true,
+ ..InbetweenSpec::default()
+ };
+ let refused = inbetween(&dir, plain).unwrap_err();
+ assert!(format!("{refused:#}").contains("--keep-drawn"), "{refused:#}");
+ inbetween(&dir, keep.clone()).unwrap();
+ let kept = hand(&dir);
+ assert_eq!(kept.len(), 1, "round {round}");
+ let (now, moved) = (kept[0].samples[0].pos(), line(&dir));
+ let (dx, dy) = (moved.0 - under.0, moved.1 - under.1);
+ assert!((dx - 15.0).abs() < 2.0, "round {round}: the line moved {dx},{dy}");
+ assert!(
+ (now.0 - start.0 - dx).abs() < 2.5 && (now.1 - start.1 - dy).abs() < 2.5,
+ "round {round}: {start:?} -> {now:?}, the line moved {dx},{dy}"
+ );
+ let all = Bundle::open(&dir).unwrap().read_marks("lines", &mid).unwrap();
+ assert_eq!(all.len(), 6);
+ assert_eq!(all.last().unwrap().author(), klad_core::stroke::Author::Human);
+ });
+ let mut bundle = Bundle::open(&dir).unwrap();
+ bundle.apply(&parse_lines(shift).unwrap()).unwrap();
+ let other = bundle.doc.layer("lines").unwrap().content_at(2).unwrap().id.clone();
+ let before = bundle.read_marks("lines", &other).unwrap();
+ let chosen = InbetweenSpec {
+ redo: true,
+ only: vec![mid.clone()],
+ force_cels: vec![mid.clone()],
+ ..InbetweenSpec::default()
+ };
+ inbetween(&dir, chosen).unwrap();
+ assert!(hand(&dir).is_empty());
+ let bundle = Bundle::open(&dir).unwrap();
+ assert_eq!(bundle.read_marks("lines", &other).unwrap(), before);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn in_betweens_turn_with_the_keys_and_refill_their_flats() {
+ let dir = swing("make");
+ inbetween(&dir, keys()).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let lines = bundle.doc.layer("lines").unwrap();
+ let made: Vec<&Cel> = lines.cels().iter().filter(|c| c.tween.is_some()).collect();
+ assert_eq!(made.iter().map(|c| c.frame).collect::<Vec<_>>(), [1, 2, 3, 4, 5]);
+ assert_eq!(lines.cels()[0].hold, Some(1));
+ let mid = made[2];
+ let tween = mid.tween.as_ref().unwrap();
+ assert_eq!((tween.from.as_str(), tween.to.as_str(), tween.t), ("ln0", "ln6", 0.5));
+ let marks = bundle.read_marks("lines", &mid.id).unwrap();
+ assert_eq!(made_hash(&marks), tween.made);
+ let tip = marks[0].as_stroke().unwrap().samples.last().unwrap().pos();
+ let (s, c) = (libm::sinf(30f32.to_radians()), libm::cosf(30f32.to_radians()));
+ let want = (80.0 + 150.0 * c + 16.0 * s, 100.0 + 150.0 * s - 16.0 * c);
+ assert!(
+ (tip.0 - want.0).abs() < 1.5 && (tip.1 - want.1).abs() < 1.5,
+ "{tip:?} {want:?}"
+ );
+ let colour = bundle.doc.layer("colour").unwrap();
+ let flats = colour.content_at(3).unwrap();
+ let fills = bundle.read_marks("colour", &flats.id).unwrap();
+ assert_eq!(fills.len(), 2);
+ let keyed = bundle.read_marks("colour", "col0").unwrap();
+ fills.iter().zip(&keyed).for_each(|(f, k)| {
+ let (now, then) = (
+ f.as_fill().unwrap().coverage.pixels(),
+ k.as_fill().unwrap().coverage.pixels(),
+ );
+ assert!((now as f32 - then as f32).abs() < then as f32 * 0.15, "{now} vs {then}");
+ });
+ let sleeve = fills[0].as_fill().unwrap();
+ let mid_arm = (80.0 + 75.0 * c, 100.0 + 75.0 * s);
+ assert_eq!(sleeve.coverage.at(mid_arm.0 as u32, mid_arm.1 as u32), 255);
+ let again = inbetween(&dir, keys());
+ assert!(again.is_ok(), "in-betweens of the same keys are replaced: {again:?}");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn redo_follows_a_changed_key_and_leaves_hand_drawn_in_betweens() {
+ let dir = swing("redo");
+ inbetween(&dir, keys()).unwrap();
+ let mut bundle = Bundle::open(&dir).unwrap();
+ let mid = bundle.doc.layer("lines").unwrap().content_at(3).unwrap().id.clone();
+ let before = bundle.read_marks("lines", &mid).unwrap();
+ let moved =
+ parse_lines(r#"{"op":"transform","ids":["ln6:s1","ln6:s2","ln6:s3","ln6:s4","ln6:s5"],"x":30}"#).unwrap();
+ bundle.apply(&moved).unwrap();
+ let redo = InbetweenSpec {
+ redo: true,
+ ..InbetweenSpec::default()
+ };
+ inbetween(&dir, redo.clone()).unwrap();
+ let mut bundle = Bundle::open(&dir).unwrap();
+ let after = bundle.read_marks("lines", &mid).unwrap();
+ let shift = after[0].as_stroke().unwrap().samples[0].x - before[0].as_stroke().unwrap().samples[0].x;
+ assert!((shift as f32 / 16.0 - 15.0).abs() < 1.0, "{shift}");
+ let mut drawn = bundle.read_marks("lines", &mid).unwrap();
+ drawn.push(Mark::Stroke(
+ Stroke::new(99, "ink", [0.0, 0.0, 0.0, 1.0], 3.0, 1)
+ .with_points(&[(10.0, 10.0, 1.0), (20.0, 20.0, 1.0)], 8.0),
+ ));
+ bundle.replace_marks("lines", &mid, &drawn, "editor", "pen").unwrap();
+ let refused = inbetween(&dir, redo.clone()).unwrap_err();
+ assert!(format!("{refused:#}").contains("1 mark drawn by hand"), "{refused:#}");
+ let forced = InbetweenSpec { force: true, ..redo };
+ inbetween(&dir, forced).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ assert_eq!(bundle.read_marks("lines", &mid).unwrap().len(), 5);
+ let foreign = InbetweenSpec {
+ from: Some(0),
+ to: Some(6),
+ layers: vec!["lines".into()],
+ ..InbetweenSpec::default()
+ };
+ let mut doc_bundle = Bundle::open(&dir).unwrap();
+ doc_bundle
+ .apply(&parse_lines(&format!(r#"{{"op":"set","id":"{mid}","tween":null}}"#)).unwrap())
+ .unwrap();
+ let blocked = inbetween(&dir, foreign.clone()).unwrap_err();
+ assert!(format!("{blocked:#}").contains("not in-betweens"), "{blocked:#}");
+ let mut again = Bundle::open(&dir).unwrap();
+ let next = again.doc.layer("lines").unwrap().content_at(2).unwrap().id.clone();
+ let mut touched = again.read_marks("lines", &next).unwrap();
+ touched.pop();
+ again
+ .replace_marks("lines", &next, &touched, "editor", "erase")
+ .unwrap();
+ again
+ .apply(&parse_lines(&format!(r#"{{"op":"rm","id":"{mid}"}}"#)).unwrap())
+ .unwrap();
+ let kept = inbetween(&dir, foreign).unwrap_err();
+ assert!(format!("{kept:#}").contains("changed after they were made"), "{kept:#}");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/layers.rs b/crates/cli/src/layers.rs
new file mode 100644
index 0000000..5493d26
--- /dev/null
+++ b/crates/cli/src/layers.rs
@@ -0,0 +1,305 @@
+use anyhow::{Context, Result};
+use klad_brush::cache::{CelCache, How, Write};
+use klad_brush::{BrushSet, CelReplay, Raster};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Document, Kind, Node};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use klad_core::stroke::decode_cel;
+use klad_render::{Rasters, rasterize_nodes};
+use rayon::prelude::*;
+use std::collections::BTreeMap;
+use std::fs;
+
+pub struct Loaded {
+ pub rasters: Rasters,
+ pub replayed: usize,
+ pub updated: usize,
+ pub cached: usize,
+ pub strokes: usize,
+ pub dabs: usize,
+}
+
+struct CelLoad {
+ cel: String,
+ raster: Raster,
+ cached: bool,
+ updated: bool,
+ strokes: usize,
+ dabs: usize,
+}
+
+pub fn load(bundle: &Bundle, frame: u32, brushes: &BrushSet, use_cache: bool) -> Result<Loaded> {
+ let cels: Vec<(String, String)> = bundle
+ .doc
+ .paint_content_at(frame)
+ .iter()
+ .map(|(layer, cel)| (layer.id.clone(), cel.id.clone()))
+ .collect();
+ let loads = cels
+ .par_iter()
+ .map(|(layer, cel)| load_cel(bundle, brushes, layer, cel, use_cache))
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Loaded {
+ replayed: loads.iter().filter(|l| !l.cached && !l.updated).count(),
+ updated: loads.iter().filter(|l| l.updated).count(),
+ cached: loads.iter().filter(|l| l.cached).count(),
+ strokes: loads.iter().map(|l| l.strokes).sum(),
+ dabs: loads.iter().map(|l| l.dabs).sum(),
+ rasters: loads.into_iter().map(|l| (l.cel, l.raster)).collect(),
+ })
+}
+
+pub fn prepare(bundle: &Bundle, brushes: &BrushSet, from: u32, to: u32) -> Result<Loaded> {
+ let cels: std::collections::BTreeSet<(String, String)> = (from..=to)
+ .flat_map(|frame| {
+ bundle
+ .doc
+ .paint_content_at(frame)
+ .into_iter()
+ .map(|(layer, cel)| (layer.id.clone(), cel.id.clone()))
+ })
+ .collect();
+ let loads = cels
+ .par_iter()
+ .map(|(layer, cel)| load_cel(bundle, brushes, layer, cel, true).map(|l| (l.cached, l.updated)))
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Loaded {
+ replayed: loads.iter().filter(|(c, u)| !c && !u).count(),
+ updated: loads.iter().filter(|(_, u)| *u).count(),
+ cached: loads.iter().filter(|(c, _)| *c).count(),
+ strokes: 0,
+ dabs: 0,
+ rasters: Rasters::new(),
+ })
+}
+
+pub fn load_one(bundle: &Bundle, brushes: &BrushSet, layer: &str, cel: &str) -> Result<Raster> {
+ Ok(load_cel(bundle, brushes, layer, cel, true)?.raster)
+}
+
+pub fn load_cels(bundle: &Bundle, brushes: &BrushSet, cels: &[(String, String, Kind)]) -> Result<Rasters> {
+ let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ cels.par_iter()
+ .map(|(layer, cel, kind)| {
+ let raster = match kind {
+ Kind::Vector => rasterize_nodes(&nodes_of(&bundle.doc, cel), w, h)?,
+ _ => load_cel(bundle, brushes, layer, cel, true)?.raster,
+ };
+ Ok((cel.clone(), raster))
+ })
+ .collect()
+}
+
+fn nodes_of(doc: &Document, cel: &str) -> Vec<Node> {
+ match doc.item(cel) {
+ Some(klad_core::doc::Item::Cel(_, c)) => c.nodes.clone(),
+ _ => Vec::new(),
+ }
+}
+
+#[derive(Default)]
+pub struct Vectors {
+ known: BTreeMap<String, (u64, Raster)>,
+}
+
+impl Vectors {
+ pub fn add_to(&mut self, doc: &Document, frame: u32, rasters: &mut Rasters) -> Result<()> {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let cels: Vec<(String, u64, &Vec<Node>)> = doc
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(frame))
+ .map(|c| {
+ let hash = fnv(FNV_OFFSET, &serde_json::to_vec(&c.nodes).unwrap_or_default());
+ (c.id.clone(), hash, &c.nodes)
+ })
+ .collect();
+ let fresh = cels
+ .par_iter()
+ .filter(|(id, hash, _)| self.known.get(id).is_none_or(|(h, _)| h != hash))
+ .map(|(id, hash, nodes)| Ok((id.clone(), (*hash, rasterize_nodes(nodes, w, h)?))))
+ .collect::<Result<Vec<_>>>()?;
+ self.known.extend(fresh);
+ cels.iter().for_each(|(id, _, _)| {
+ if let Some((_, raster)) = self.known.get(id) {
+ rasters.insert(id.clone(), raster.clone());
+ }
+ });
+ Ok(())
+ }
+}
+
+fn load_cel(bundle: &Bundle, brushes: &BrushSet, layer: &str, cel: &str, use_cache: bool) -> Result<CelLoad> {
+ let cache = CelCache::new(bundle, brushes, Write::Always);
+ let load = match use_cache {
+ true => cache.load(bundle, brushes, layer, cel, false)?,
+ false => {
+ let (width, height) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
+ let path = bundle.strokes_path(layer, cel);
+ let bytes = if path.exists() { fs::read(&path)? } else { Vec::new() };
+ let marks = match bytes.is_empty() {
+ true => Vec::new(),
+ false => decode_cel(&bytes).with_context(|| format!("cel {cel}"))?,
+ };
+ let count = marks.len();
+ let (replay, raster, dabs) =
+ CelReplay::replay(width, height, marks, brushes).with_context(|| format!("cel {cel}"))?;
+ cache.store(cel, cache.key(&bytes), &raster, &replay)?;
+ klad_brush::cache::CelLoad {
+ raster,
+ replay,
+ file_hash: 0,
+ how: How::Replayed,
+ strokes: count,
+ dabs,
+ }
+ }
+ };
+ Ok(CelLoad {
+ cel: cel.to_string(),
+ raster: load.raster,
+ cached: load.how == How::Cached,
+ updated: matches!(load.how, How::Updated(_)),
+ strokes: load.strokes,
+ dabs: load.dabs,
+ })
+}
+
+pub fn compress_raster(raster: &Raster) -> Result<Vec<u8>> {
+ klad_brush::cache::compress(raster)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_brush::{PressureCurve, Raw, Recorder, StrokeBuffer, StrokePainter, commit, draw_stroke, needs_repaint};
+ use klad_core::doc::{Document, Layer};
+ use klad_core::ops::{Op, StrokeSpec};
+ use klad_core::stroke::Stroke;
+
+ fn scratch(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-layers-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ fn alpha(raster: &Raster, x: usize, y: usize) -> f32 {
+ let t = klad_brush::TILE;
+ raster
+ .get(x / t, y / t)
+ .map(|tile| tile[((y % t) * t + x % t) * 4 + 3].to_f32())
+ .unwrap_or(0.0)
+ }
+
+ fn width_at(raster: &Raster, x: usize) -> usize {
+ (0..raster.height as usize)
+ .filter(|&y| alpha(raster, x, y) > 0.5)
+ .count()
+ }
+
+ #[test]
+ fn a_calibrated_stabilised_pen_stroke_replays_to_the_same_pixels_in_the_cli() {
+ let dir = scratch("pen");
+ let mut doc = Document::new(512, 256);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let bundle = Bundle::create(&dir, doc).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let brush = brushes.get("ink").unwrap();
+ let def = brush.def.clone();
+ let heavy = PressureCurve {
+ low: 0.0,
+ high: 0.88,
+ gamma: 1.0,
+ };
+ let mut recorder = Recorder::new(heavy, def.stabilizer, def.smoothing);
+ let mut stroke = Stroke::new(1, "ink", [0.05, 0.05, 0.08, 1.0], 24.0, 9).tapered(def.taper);
+ let mut buffer = StrokeBuffer::new(512, 256);
+ let mut live = StrokePainter::live(brush, &stroke);
+ (0..180).for_each(|i| {
+ let t = i as f32 / 179.0;
+ let raw = Raw {
+ x: 30.0 + 450.0 * t,
+ y: 128.0 + 30.0 * libm::sinf(t * 6.0) + if i % 2 == 0 { 1.5 } else { -1.5 },
+ pressure: 0.88 * libm::sinf(t * std::f32::consts::PI).min(0.999),
+ tilt: (0.3, -0.2),
+ dt_ms: if i == 0 { 0.0 } else { 4.5 },
+ };
+ let sample = recorder.push(raw);
+ live.push(&sample, &mut buffer);
+ stroke.samples.push(sample);
+ });
+ let tail = recorder.finish();
+ tail.iter().for_each(|s| live.push(s, &mut buffer));
+ stroke.samples.extend(tail);
+ assert!(stroke.samples.iter().any(|s| s.pressure() > 0.97));
+ assert!(needs_repaint(&stroke));
+ buffer.reset();
+ draw_stroke(&mut buffer, brush, &stroke);
+ let mut editor = Raster::new(512, 256);
+ commit(&mut editor, &mut buffer, stroke.color(), stroke.opacity, brush.blend);
+ bundle.write_marks("l1", "c1", &[stroke.into()]).unwrap();
+ let cli = load(&Bundle::open(&dir).unwrap(), 0, &brushes, false).unwrap();
+ assert_eq!(cli.rasters["c1"].hash(), editor.hash());
+ let cached = load(&Bundle::open(&dir).unwrap(), 0, &brushes, true).unwrap();
+ assert_eq!(cached.cached, 1);
+ assert_eq!(cached.rasters["c1"].hash(), editor.hash());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn agent_strokes_take_the_brush_taper_unless_told_otherwise() {
+ let dir = scratch("taper");
+ let mut doc = Document::new(512, 128);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let spec = |taper: Option<[f32; 2]>| {
+ Op::Stroke(StrokeSpec {
+ layer: "l1".into(),
+ frame: 0,
+ brush: "ink".into(),
+ color: "#000000".into(),
+ size: 16.0,
+ opacity: 1.0,
+ flow: 1.0,
+ path: Some("M20 64 L490 64".into()),
+ points: None,
+ pressure: vec![1.0],
+ tilt: [0.0, 0.0],
+ speed: 700.0,
+ seed: Some(3),
+ taper,
+ part: None,
+ second: None,
+ })
+ };
+ let mut ops = vec![spec(None), spec(Some([0.0, 0.0])), spec(Some([12.0, 30.0]))];
+ crate::agent::resolve_strokes(&bundle, &mut ops).unwrap();
+ bundle.apply(&ops).unwrap();
+ let strokes = bundle.read_strokes("l1", "c1").unwrap();
+ let tapers: Vec<[f32; 2]> = strokes.iter().map(|s| s.taper).collect();
+ assert_eq!(tapers, [[10.0, 24.0], [0.0, 0.0], [12.0, 30.0]]);
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let one = |stroke: &Stroke| {
+ klad_brush::replay(512, 128, &[stroke.clone().into()], &brushes)
+ .unwrap()
+ .raster
+ };
+ let (plain, tapered) = (one(&strokes[1]), one(&strokes[2]));
+ assert_eq!(width_at(&plain, 22), width_at(&plain, 250));
+ assert!(width_at(&tapered, 22) < width_at(&tapered, 250) / 2);
+ assert!(width_at(&tapered, 480) < width_at(&tapered, 250) / 2);
+ let mut bad = vec![Op::Stroke(StrokeSpec {
+ brush: "felt".into(),
+ ..match spec(None) {
+ Op::Stroke(s) => s,
+ _ => unreachable!(),
+ }
+ })];
+ let err = crate::agent::resolve_strokes(&bundle, &mut bad)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("felt") && err.contains("marker"), "{err}");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/looks.rs b/crates/cli/src/looks.rs
new file mode 100644
index 0000000..10d97bc
--- /dev/null
+++ b/crates/cli/src/looks.rs
@@ -0,0 +1,241 @@
+use crate::agent::{self, Output, parse_props};
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::Bundle;
+use klad_core::look::{ADJUSTMENTS, Adjustment, EFFECTS, Effect};
+use klad_core::ops::Op;
+use serde_json::{Map, Value, json};
+use std::path::Path;
+
+const LAYER_KEYS: [&str; 9] = [
+ "id", "name", "opacity", "blend", "visible", "locked", "clip", "mask", "effects",
+];
+
+fn with_props(mut value: Value, props: Map<String, Value>) -> Result<Value> {
+ let inner = value
+ .as_object_mut()
+ .and_then(|m| m.values_mut().next())
+ .and_then(Value::as_object_mut)
+ .ok_or_else(|| anyhow!("cannot set fields here"))?;
+ props.into_iter().for_each(|(k, v)| {
+ inner.insert(k, v);
+ });
+ Ok(value)
+}
+
+pub fn effect_of(kind: &str, props: &[String]) -> Result<Effect> {
+ let start = Effect::named(kind).ok_or_else(|| anyhow!("no effect {kind:?}: use {}", EFFECTS.join(", ")))?;
+ let effect: Effect = serde_json::from_value(with_props(serde_json::to_value(&start)?, parse_props(props)?)?)?;
+ effect.validate()?;
+ Ok(effect)
+}
+
+pub fn adjust_layer(rest: &[String]) -> Result<Value> {
+ let Some((kind, props)) = rest.split_first().filter(|(k, _)| !k.contains('=')) else {
+ bail!(
+ "say which adjustment: klad add <bundle> layer adjust {} [key=value ...]",
+ ADJUSTMENTS.join("|")
+ );
+ };
+ let start =
+ Adjustment::named(kind).ok_or_else(|| anyhow!("no adjustment {kind:?}: use {}", ADJUSTMENTS.join(", ")))?;
+ let (own, layer): (Map<String, Value>, Map<String, Value>) = parse_props(props)?
+ .into_iter()
+ .partition(|(k, _)| !LAYER_KEYS.contains(&k.split('.').next().unwrap_or("")));
+ let adjust: Adjustment = serde_json::from_value(with_props(serde_json::to_value(&start)?, own)?)?;
+ adjust.validate()?;
+ let mut value = agent::nest(layer);
+ value["kind"] = json!("adjust");
+ value["adjust"] = serde_json::to_value(&adjust)?;
+ if value.get("name").is_none() {
+ value["name"] = json!(adjust.label());
+ }
+ Ok(value)
+}
+
+pub enum Change {
+ List,
+ Add(String, Vec<String>),
+ Remove(usize),
+ Clear,
+}
+
+pub fn effect(path: &Path, layer: &str, change: Change, out: &Output) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let found = bundle.doc.find_layer(layer)?;
+ let mut list = found.effects.clone();
+ match change {
+ Change::List => {
+ if list.is_empty() {
+ println!("layer {layer} has no effects; add one of {}", EFFECTS.join(", "));
+ }
+ list.iter()
+ .enumerate()
+ .try_for_each(|(i, e)| serde_json::to_string(e).map(|json| println!("{i}: {json}")))?;
+ return Ok(());
+ }
+ Change::Add(kind, props) => list.push(effect_of(&kind, &props)?),
+ Change::Remove(i) if i < list.len() => {
+ list.remove(i);
+ }
+ Change::Remove(i) => bail!("layer {layer} has {} effects; there is no {i}", list.len()),
+ Change::Clear => list.clear(),
+ }
+ let props: Map<String, Value> = [("effects".to_string(), serde_json::to_value(&list)?)]
+ .into_iter()
+ .collect();
+ agent::edit(
+ path,
+ &[Op::Set {
+ id: found.id.clone(),
+ props,
+ }],
+ out,
+ )
+}
+
+fn imported(bundle: &Path, props: &mut Map<String, Value>) -> Result<Value> {
+ let file = match props.remove("src") {
+ Some(Value::String(s)) => s,
+ _ => bail!("say which picture: src=photo.jpg (a PNG or JPEG file)"),
+ };
+ let bytes = std::fs::read(&file).map_err(|e| anyhow!("reading {file}: {e}"))?;
+ let doc = Bundle::open(bundle)?.doc;
+ let (src, w, h) = klad_render::assets::import_image(bundle, &bytes)?;
+ let (cw, ch) = (doc.canvas.width as f32, doc.canvas.height as f32);
+ let fit = (cw / w as f32).min(ch / h as f32).min(1.0);
+ let (pw, ph) = (w as f32 * fit, h as f32 * fit);
+ let take = |props: &mut Map<String, Value>, key: &str, or: f32| {
+ props.remove(key).and_then(|v| v.as_f64()).map_or(or, |v| v as f32)
+ };
+ let (x, y) = (take(props, "x", (cw - pw) / 2.0), take(props, "y", (ch - ph) / 2.0));
+ let (pw, ph) = (take(props, "w", pw), take(props, "h", ph));
+ Ok(json!({ "type": "image", "src": src, "x": x, "y": y, "w": pw, "h": ph }))
+}
+
+pub fn image_layer(bundle: &Path, props: &[String]) -> Result<Value> {
+ let mut props = parse_props(props)?;
+ let file = props.get("src").and_then(Value::as_str).unwrap_or_default().to_string();
+ let node = imported(bundle, &mut props)?;
+ let mut layer = agent::nest(props);
+ layer["kind"] = json!("vector");
+ if layer.get("name").is_none() {
+ let stem = Path::new(&file)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("picture");
+ layer["name"] = json!(stem);
+ }
+ layer["cels"] = json!([{ "frame": 0, "nodes": [node] }]);
+ Ok(layer)
+}
+
+pub fn image_node(bundle: &Path, props: &[String]) -> Result<Value> {
+ let mut props = parse_props(props)?;
+ let mut node = imported(bundle, &mut props)?;
+ props.into_iter().for_each(|(k, v)| node[k] = v);
+ Ok(node)
+}
+
+pub fn font(bundle: &Path, file: Option<&Path>) -> Result<()> {
+ match file {
+ Some(file) => {
+ let name = klad_render::assets::import_font(bundle, file)?;
+ println!("{name}: text nodes use it as font={name}");
+ }
+ None => {
+ let dir = bundle.join(klad_render::assets::FONTS);
+ let mut names: Vec<String> = std::fs::read_dir(&dir)
+ .map(|entries| {
+ entries
+ .flatten()
+ .filter_map(|e| e.file_name().into_string().ok())
+ .collect()
+ })
+ .unwrap_or_default();
+ names.sort();
+ match names.is_empty() {
+ true => println!("no fonts yet: klad font <bundle> <file.ttf> adds one"),
+ false => names.iter().for_each(|n| println!("{n}")),
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn atmosphere(path: &Path, props: &[String], off: bool, out: &Output) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ if props.is_empty() && !off {
+ match &bundle.doc.atmosphere {
+ Some(air) => println!("{}", serde_json::to_string(air)?),
+ None => {
+ println!("no atmosphere: klad atmosphere <bundle> color=#9aa8b8 density=0.5 blur=1 desaturate=0.15")
+ }
+ }
+ return Ok(());
+ }
+ let op = match off {
+ true => Op::Atmosphere(None),
+ false => {
+ let start = serde_json::to_value(bundle.doc.atmosphere.clone().unwrap_or_default())?;
+ let mut map = start.as_object().cloned().unwrap_or_default();
+ parse_props(props)?.into_iter().for_each(|(k, v)| {
+ map.insert(k, v);
+ });
+ Op::Atmosphere(Some(serde_json::from_value(Value::Object(map))?))
+ }
+ };
+ agent::edit(path, &[op], out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_picture_layer_imports_its_file_and_fits_the_canvas() {
+ let dir = std::env::temp_dir().join(format!("klad-cli-picture-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("art.draw");
+ Bundle::create(&bundle, klad_core::doc::Document::new(200, 100)).unwrap();
+ let rgba = klad_render::assets::Rgba {
+ width: 400,
+ height: 100,
+ pixels: vec![120; 400 * 100 * 4],
+ };
+ let file = dir.join("wide.png");
+ std::fs::write(&file, klad_render::assets::encode_png(&rgba).unwrap()).unwrap();
+ let layer = image_layer(&bundle, &[format!("src={}", file.display()), "reference=true".into()]).unwrap();
+ assert_eq!(
+ (layer["kind"].clone(), layer["name"].clone(), layer["reference"].clone()),
+ (json!("vector"), json!("wide"), json!(true))
+ );
+ let node = &layer["cels"][0]["nodes"][0];
+ assert_eq!(
+ (node["w"].as_f64(), node["h"].as_f64(), node["y"].as_f64()),
+ (Some(200.0), Some(50.0), Some(25.0))
+ );
+ assert!(bundle.join("images").join(node["src"].as_str().unwrap()).exists());
+ assert!(image_layer(&bundle, &["name=x".into()]).is_err());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn effects_and_adjustments_take_their_fields() {
+ let glow = effect_of("glow", &["radius=30".into(), "color=#ffd080".into()]).unwrap();
+ assert!(matches!(glow, Effect::Glow(ref g) if g.radius == 30.0 && g.color.as_deref() == Some("#ffd080")));
+ assert!(effect_of("glow", &["radios=3".into()]).is_err());
+ assert!(effect_of("sparkle", &[]).is_err());
+ let layer = adjust_layer(&[
+ "curves".into(),
+ "points=[[0,0],[0.5,0.3],[1,1]]".into(),
+ "name=dusk".into(),
+ "opacity=0.7".into(),
+ ])
+ .unwrap();
+ assert_eq!(layer["name"], "dusk");
+ assert_eq!(layer["opacity"], 0.7);
+ assert!((layer["adjust"]["curves"]["points"][1][1].as_f64().unwrap() - 0.3).abs() < 1e-6);
+ assert!(adjust_layer(&["levels".into(), "white=0.1".into(), "black=0.5".into()]).is_err());
+ }
+}
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
new file mode 100644
index 0000000..bb9fc9d
--- /dev/null
+++ b/crates/cli/src/main.rs
@@ -0,0 +1,2870 @@
+mod agent;
+mod arcs;
+mod bench;
+mod brushes;
+mod colour;
+mod demo;
+mod edit;
+mod export;
+mod fills;
+mod frames;
+mod history;
+mod inbetween;
+mod layers;
+mod looks;
+mod marks;
+mod paths;
+mod shapes;
+mod sheet;
+mod sprites;
+
+use agent::{Look, Output};
+use anyhow::{Result, anyhow};
+use clap::{Args, Parser, Subcommand};
+use klad_brush::BrushSet;
+use klad_core::bundle::{Blank, Bundle};
+use klad_core::doc::Kind;
+use klad_core::fill::{EXPAND, FillSource, TOLERANCE};
+use klad_core::history::Stack;
+use klad_core::markedit::{LassoAction, MarkTransform};
+use klad_core::ops::{
+ ClipEdit, CopySpec, CopyTarget, FillSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec, LightSpec, Op, PaintSpec,
+ PaletteEdit, Place, ScatterSpec, StrokeSpec,
+};
+use klad_core::retime::{Retime, RetimeSpec};
+use klad_core::stroke::{fills_of, strokes_of};
+use klad_core::timing::{CelAction, CelSpec, FrameSpec};
+use klad_core::tween::{Match, Spacing, Unpaired};
+use klad_render::{View, compose};
+use marks::{fill_json, hex8, stroke_json};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+#[derive(Parser)]
+#[command(
+ name = "klad",
+ version,
+ about = "klad: draw and paint with an agent, from the command line"
+)]
+struct Cli {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Args)]
+struct EditFlags {
+ #[arg(long, help = "Render a preview after the edit and print its path")]
+ render: bool,
+ #[arg(long, help = "Preview scale (default: longest side 1024 px)")]
+ scale: Option<f32>,
+ #[arg(long, help = "Print the result as JSON")]
+ json: bool,
+ #[arg(long, help = "Draw on the preview: ids, bbox, grid or all (comma separated)")]
+ overlay: Option<String>,
+}
+
+#[derive(Args)]
+struct MarkFlags {
+ #[arg(
+ long,
+ help = "Render a preview after the edit and print its path (longest side 1024 px)"
+ )]
+ render: bool,
+ #[arg(long, help = "Print the result as JSON")]
+ json: bool,
+ #[arg(long, help = "Draw on the preview: ids, bbox, grid or all (comma separated)")]
+ overlay: Option<String>,
+}
+
+impl MarkFlags {
+ fn edit(&self) -> EditFlags {
+ EditFlags {
+ render: self.render,
+ scale: None,
+ json: self.json,
+ overlay: self.overlay.clone(),
+ }
+ }
+}
+
+#[derive(Args)]
+struct Where {
+ #[arg(long = "in", help = "Container: group layer, vector layer, cel or group node")]
+ into: Option<String>,
+ #[arg(long, help = "Place just above this sibling")]
+ above: Option<String>,
+ #[arg(long, help = "Place just below this sibling")]
+ below: Option<String>,
+ #[arg(long, help = "Position in the container, 0 is the bottom")]
+ index: Option<usize>,
+ #[arg(long, help = "Frame whose cel receives new nodes (default 0)")]
+ frame: Option<u32>,
+}
+
+impl Where {
+ fn place(&self) -> Place {
+ Place {
+ above: self.above.clone(),
+ below: self.below.clone(),
+ into: self.into.clone(),
+ index: self.index,
+ frame: self.frame,
+ }
+ }
+}
+
+#[derive(Subcommand)]
+enum Command {
+ #[command(about = "Create an empty bundle with paint layers")]
+ New {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 2048)]
+ width: u32,
+ #[arg(long, default_value_t = 2048)]
+ height: u32,
+ #[arg(long, default_value_t = 1)]
+ layers: usize,
+ #[arg(long, help = "Background colour, for example #ffffff")]
+ background: Option<String>,
+ #[arg(long, default_value_t = 12)]
+ fps: u32,
+ #[arg(long, default_value_t = 1)]
+ frames: u32,
+ #[arg(long, help = "Add a vector layer named sketch on top, for blocking in shapes")]
+ sketch: bool,
+ },
+ #[command(
+ about = "Exposure sheet: a row per frame, a column per layer (top first)",
+ long_about = "Exposure sheet: a row per frame, a column per layer (top first).\n\nA cel id marks the frame a drawing starts, | that it is still showing, c5->c1 a link (c5 shows c1's drawing), . a blank frame. Clips are listed on the right ([run on their first frame, run] on their last)."
+ )]
+ Frames {
+ bundle: PathBuf,
+ #[arg(long)]
+ from: Option<u32>,
+ #[arg(long)]
+ to: Option<u32>,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(
+ about = "Insert or remove frames in every layer or the listed ones",
+ long_about = "Insert or remove frames in every layer or the listed ones.\n\n klad frame art.draw insert 4 --count 2\n klad frame art.draw remove 4 --layers l3,l5\n\nInsert: what showed at the frame now shows there and for the inserted frames too (that exposure lengthens), everything after moves later. Remove: exposures over the removed frames get shorter, drawings left with no frames go (links to them take them over), everything after moves earlier. On every layer, clips and the timeline length follow; on listed layers an insert lengthens the timeline only as far as their drawings need (a last drawing without a hold keeps its length)."
+ )]
+ Frame {
+ bundle: PathBuf,
+ #[arg(value_parser = ["insert", "remove"])]
+ action: String,
+ at: u32,
+ #[arg(long, default_value_t = 1)]
+ count: u32,
+ #[arg(long, value_delimiter = ',', help = "Layer ids or names (default: every layer)")]
+ layers: Vec<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Track marks, parts or points across frames: positions, spacing, ground contacts, feet crossing",
+ long_about = "Track things across frames, the way an animator checks arcs and spacing: a mark (c4:s12, through the drawings that keep its id, as in-betweens do), a part (leaf, or lines:leaf: the centre of the part's marks in each drawing) or a point (x,y: carried by the stroke nearest to it). Prints each frame's position, the distance moved since the frame before, and the lowest point. --ground y (one for all tracks, or one per track) adds the frames where a track goes under the ground line or slides along it while touching it (for a cycle drawn in place, --travel gives the px per frame the planted foot should move back by); with two or more tracks, the frames where two of them swap sides (feet crossing) are listed. --check makes any of these an error, for scripts. klad render --overlay arcs --track ... draws the same paths.\n\n klad arcs walk.draw --track 'near foot' --track 'far foot' --clip walk --ground 610,598 --travel 7 --check\n klad arcs walk.draw --track c12:s4 --from 12 --to 27 --json"
+ )]
+ Arcs {
+ bundle: PathBuf,
+ #[arg(long, required = true)]
+ track: Vec<String>,
+ #[arg(long, conflicts_with_all = ["from", "to"], help = "The frames of this clip")]
+ clip: Option<String>,
+ #[arg(long)]
+ from: Option<u32>,
+ #[arg(long)]
+ to: Option<u32>,
+ #[arg(
+ long,
+ allow_hyphen_values = true,
+ value_delimiter = ',',
+ help = "The ground line's y, one for every track or one per track: report feet under it or sliding on it"
+ )]
+ ground: Vec<f32>,
+ #[arg(
+ long,
+ default_value_t = 0.0,
+ allow_hyphen_values = true,
+ help = "For a cycle drawn in place: how far the character travels per frame (px, + to the right); a planted foot should move back by as much"
+ )]
+ travel: f32,
+ #[arg(long, default_value_t = arcs::SLACK, help = "How many px off still counts as on the ground and not sliding")]
+ slack: f32,
+ #[arg(long)]
+ json: bool,
+ #[arg(
+ long,
+ help = "Exit with an error when a track goes under the ground, slides, or two tracks swap sides"
+ )]
+ check: bool,
+ },
+ #[command(
+ about = "Name a group of marks in a drawing (a part), so in-betweens pair them whatever their ids",
+ long_about = "Name a group of marks in a drawing: a part such as leaf, near leg or body. In-betweens pair marks part by part first (in order within a part, nearest shape when the counts differ), whatever their ids; arcs track a part's centre. A mark is in one part at most; naming it again moves it. dup, copy and in-betweens keep parts. --name '' takes the marks out of their part.\n\n klad part art.draw c4:s14 c4:s15 --name leaf\n klad part art.draw c9:s17 c9:s18 --name leaf\n klad stroke art.draw lines --path \"M...\" --part leaf\n\nAlso an op: {\"op\":\"part\",\"ids\":[\"c4:s14\",\"c4:s15\"],\"name\":\"leaf\"}. klad strokes lists each mark's part."
+ )]
+ Part {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[arg(long)]
+ name: String,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Duplicate a layer with its drawings, links and mask, above it",
+ long_about = "Duplicate a layer: its drawings, links, in-between marks and mask are copied with new ids, and the copy, named \"<name> copy\", goes right above it.\n\n klad duplicate art.draw l3\n\nAlso an op in klad apply: {\"op\":\"duplicate\",\"layer\":\"l3\"}."
+ )]
+ Duplicate {
+ bundle: PathBuf,
+ layer: String,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Make drawings on the timeline: new, dup, link, unlink, move",
+ long_about = "Make drawings on the timeline.\n\n klad cel art.draw new l3 --frame 4 a blank drawing on layer l3 at frame 4\n klad cel art.draw dup c4 [--frame 6] a copy of c4's drawing (default: right after c4's exposure)\n klad cel art.draw link c4 --frame 8 show c4's drawing again at frame 8\n klad cel art.draw unlink c9 turn the link c9 into a drawing of its own\n klad cel art.draw move c5 --frame 12 start c5 at frame 12, keeping its hold; drawings in the way are pushed along\n\nInside an exposure a new cel takes over the rest of it; elsewhere it lasts until the next cel, or --hold frames (dup and link default to their source's hold). --insert moves later cels of that layer back to make room (only at the start or end of an exposure). Strokes keep their ids in a dup."
+ )]
+ Cel {
+ bundle: PathBuf,
+ #[arg(value_parser = ["new", "dup", "link", "unlink", "move"])]
+ action: String,
+ #[arg(help = "new: the layer; dup, link, unlink, move: the cel")]
+ target: String,
+ #[arg(long)]
+ frame: Option<u32>,
+ #[arg(long)]
+ hold: Option<u32>,
+ #[arg(long)]
+ insert: bool,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Copy strokes and fills into another drawing, with new ids, moving them on the way",
+ long_about = "Copy strokes and fills (<cel>:s<id>) into another drawing. The copies get new ids, printed as a map (c1:s3 -> c9:s12), and land on top of that drawing in the order they had. --to names the drawing; --frame takes the drawing the layer shows at that frame (a new drawing on an empty frame or past the end; a frame that shows a link names its source instead). The marks' own layer unless --layer. The move, turn, scale and flip options are klad transform's, applied to the copies together about the middle of their bounds or --pivot. --cut keeps only the parts inside a polygon.\n\n klad copy art.draw c1:s3 c1:s4 --frame 4\n klad copy art.draw c1:s3 --to c9 --move 12,-4 --rotate 8\n klad copy art.draw c1:s3 --frame 6 --layer shade --flip h --pivot 512,400\n\nAlso a copy op in klad apply: {\"op\":\"copy\",\"ids\":[\"c1:s3\"],\"frame\":4,\"x\":12,\"y\":-4} (or \"to\":\"c9\")."
+ )]
+ Copy {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[arg(long, conflicts_with = "frame", help = "The drawing (cel id) the copies go into")]
+ to: Option<String>,
+ #[arg(long, help = "The drawing shown at this frame (a new drawing on an empty frame)")]
+ frame: Option<u32>,
+ #[arg(long, requires = "frame", help = "With --frame: the layer (default: the marks' own)")]
+ layer: Option<String>,
+ #[arg(long = "move", value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px")]
+ offset: Option<[f32; 2]>,
+ #[arg(long, allow_hyphen_values = true, help = "Degrees, clockwise")]
+ rotate: Option<f32>,
+ #[arg(long, allow_hyphen_values = true, help = "Uniform scale")]
+ scale: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sx: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sy: Option<f32>,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "x,y to turn, scale and flip about")]
+ pivot: Option<[f32; 2]>,
+ #[arg(long, value_parser = ["h", "v"], help = "Mirror: h (left-right) or v (up-down)")]
+ flip: Option<String>,
+ #[arg(
+ long,
+ help = "Keep only the parts inside this polygon: x,y pairs separated by spaces"
+ )]
+ cut: Option<String>,
+ #[command(flatten)]
+ flags: MarkFlags,
+ },
+ #[command(
+ about = "Retime a range of frames: on ones/twos/threes, fit into n frames, reverse, ping-pong",
+ long_about = "Retime frames FROM-TO (both included) on every layer, or on --layers (with their masks and children). The range is cut where any of those layers changes what it shows; each piece is one picture.\n\n klad retime art.draw 0-11 --on 2 every picture shows for 2 frames (ones to twos)\n klad retime art.draw 0-23 --on 1 and back to ones\n klad retime art.draw 0-11 --fit 16 the range becomes 16 frames; order and relative timing kept, at least one frame each\n klad retime art.draw 0-7 --reverse\n klad retime art.draw 0-7 --pingpong the pictures again backwards as links, the ends not repeated: a b c d c b\n\nLater cels move by the change in length; on every layer clips move and stretch with it and the timeline grows or shrinks; on listed layers clips stay and the timeline only grows. A drawing that ends up in two places is shown again by a link. One history step. Also a retime op: {\"op\":\"retime\",\"from\":0,\"to\":11,\"on\":2,\"layers\":[\"l3\"]} (or \"fit\":16, \"reverse\":true, \"pingpong\":true)."
+ )]
+ Retime {
+ bundle: PathBuf,
+ #[arg(value_parser = parse_frames_span, help = "FROM-TO, both included")]
+ range: (u32, u32),
+ #[arg(long, help = "Frames per picture: 1, 2, 3 ...")]
+ on: Option<u32>,
+ #[arg(long, help = "The range becomes this many frames")]
+ fit: Option<u32>,
+ #[arg(long)]
+ reverse: bool,
+ #[arg(long)]
+ pingpong: bool,
+ #[arg(long, value_delimiter = ',', help = "Layer ids or names (default: every layer)")]
+ layers: Vec<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Make the drawings between two keys: a new cel on each frame between them",
+ long_about = "Make in-betweens of two keys on paint layers: the drawings shown at --from and --to (the second key is the frame where a drawing starts; a link there names its source, so a loop's last in-betweens can lead back to its first drawing). By default a new cel on every frame between them; --count n spreads n of them, each holding until the next.\n\n klad inbetween art.draw --layers lines,colour --from 0 --to 6\n klad inbetween art.draw --layers lines --from 0 --to 8 --count 3 --spacing in-out\n klad inbetween art.draw --layers arm --from 4 --to 10 --match near --pair s3=s7\n klad inbetween art.draw --redo after a key changed\n\nStrokes pair by id (a key duplicated from the other keeps its ids), by --match order or by nearest shape; --pair forces pairs (first key id = second key id). Each pair is resampled along its length; points, pressure, tilt, size, opacity, flow and taper move at the spacing, and the pair turns and scales along an arc about the point its best-fit rotation turns around, so a swinging limb keeps its length. A line end that touches another line in both keys touches it in every in-between. Lasso fills are interpolated; flood fills are recomputed in each in-between from a seed carried with the lines next to it (the layers they fill against go first). Unpaired marks and fills that fail (a seed on a line, a leak) are left out and listed.\n\nSpacing: even, in (eases in: the in-betweens bunch near the first key), out (they bunch near the second key), in-out, or the positions themselves, 0.2,0.5,0.9. Every in-between remembers its keys (tween in klad show), so --redo remakes them after a key changed; it refuses cels changed since they were made unless --force. One history step."
+ )]
+ Inbetween {
+ bundle: PathBuf,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ help = "Paint layers (ids or names; a group means its paint layers)"
+ )]
+ layers: Vec<String>,
+ #[arg(long, help = "The frame of the first key")]
+ from: Option<u32>,
+ #[arg(long, help = "The frame where the second key starts")]
+ to: Option<u32>,
+ #[arg(long, help = "How many in-betweens (default: one per frame between the keys)")]
+ count: Option<u32>,
+ #[arg(
+ long,
+ default_value = "even",
+ help = "even, in, out, in-out, or positions like 0.25,0.5,0.9"
+ )]
+ spacing: String,
+ #[arg(
+ long = "match",
+ default_value = "id",
+ help = "Pair strokes by id, order or near (nearest shape)"
+ )]
+ matching: String,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ help = "Force pairs: s3=s7 (first key's s3 with the second key's s7)"
+ )]
+ pair: Vec<String>,
+ #[arg(
+ long,
+ help = "Remake the in-betweens (of --layers, between --from and --to when given)"
+ )]
+ redo: bool,
+ #[arg(
+ long,
+ help = "Replace drawings between the keys, or redo in-betweens changed since they were made"
+ )]
+ force: bool,
+ #[arg(
+ long = "loop",
+ help = "The second key is the loop's first drawing (the clip holding --from, else frame 0); --to defaults to the loop's end"
+ )]
+ looping: bool,
+ #[arg(
+ long,
+ requires = "redo",
+ help = "With --redo: remake the agent's marks and keep the marks drawn by hand on top, carried with the lines under them"
+ )]
+ keep_drawn: bool,
+ #[arg(
+ long,
+ value_parser = ["leave", "pop", "fade", "draw-on"],
+ default_value = "leave",
+ help = "Marks in one key only: leave them out (listed), pop at --at, fade, or draw on along their length"
+ )]
+ unpaired: String,
+ #[arg(long, help = "With --unpaired pop: when it pops, 0 to 1 (default 0.5)")]
+ at: Option<f32>,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ requires = "redo",
+ help = "With --redo: only these in-betweens (cel ids)"
+ )]
+ only: Vec<String>,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ requires = "redo",
+ help = "With --redo: these in-betweens keep their hand-drawn marks on top"
+ )]
+ keep_cels: Vec<String>,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ requires = "redo",
+ help = "With --redo: these in-betweens are remade with their hand-drawn marks"
+ )]
+ force_cels: Vec<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Add a font file to the bundle for text nodes, or list the fonts it has",
+ long_about = "Add a font file (TTF or OTF) to the bundle's fonts folder, so text nodes render the same on every machine; with no file, list the fonts.\n\n klad font art.draw ~/fonts/Signage.ttf\n klad add art.draw text --in l4 text=INN font=Signage.ttf size=48 x=120 y=80 fill=#2b1d12"
+ )]
+ Font { bundle: PathBuf, file: Option<PathBuf> },
+ #[command(
+ about = "Fog and haze by depth: show, set or turn off the document's atmosphere",
+ long_about = "The atmosphere fades layers at the top of the stack that have a depth (klad set art.draw g2 depth=2) towards the fog colour, blurs them and takes colour out, more the deeper they are.\n\n klad atmosphere art.draw\n klad atmosphere art.draw color=#9aa8b8 top=#d8e0e8 density=0.5 blur=1 desaturate=0.15\n klad atmosphere art.draw --off"
+ )]
+ Atmosphere {
+ bundle: PathBuf,
+ props: Vec<String>,
+ #[arg(long, help = "Remove the atmosphere")]
+ off: bool,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Show the timeline (fps, length, origin, clips) or set fps, length and origin",
+ long_about = "Show the timeline (fps, length, origin, clips) or set fps, length and origin.\n\n klad timeline art.draw\n klad timeline art.draw --fps 12 --frames 24\n klad timeline art.draw --origin 512,700 the canvas point a Godot export puts on the node's position\n klad timeline art.draw --origin centre back to the middle of the canvas (the default)"
+ )]
+ Timeline {
+ bundle: PathBuf,
+ #[arg(long)]
+ fps: Option<u32>,
+ #[arg(long)]
+ frames: Option<u32>,
+ #[arg(long, help = "x,y on the canvas, or centre")]
+ origin: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "List, add, change, rename and remove clips (named frame ranges)",
+ long_about = "List, add, change, rename and remove clips: named frame ranges such as idle, run or attack. Exports turn each clip into an animation; a clip may have its own fps.\n\n klad clip art.draw list them\n klad clip art.draw --add run --from 0 --to 11 --loop --fps 12\n klad clip art.draw --set run --to 15 --no-loop\n klad clip art.draw --set run --name sprint rename\n klad clip art.draw --set run --fps doc use the document's fps again\n klad clip art.draw --rm run\n\nFrames inserted or removed on every layer move and stretch clips; a clip ends where the timeline ends."
+ )]
+ Clip {
+ bundle: PathBuf,
+ #[arg(long, conflicts_with_all = ["set", "rm"], help = "Add a clip with this name")]
+ add: Option<String>,
+ #[arg(long, conflicts_with = "rm", help = "Change the clip with this name")]
+ set: Option<String>,
+ #[arg(long, help = "Remove the clip with this name")]
+ rm: Option<String>,
+ #[arg(long, help = "With --set: the clip's new name")]
+ name: Option<String>,
+ #[arg(long, help = "First frame")]
+ from: Option<u32>,
+ #[arg(long, help = "Last frame (included)")]
+ to: Option<u32>,
+ #[arg(long = "loop", conflicts_with = "no_loop", help = "The clip loops")]
+ looping: bool,
+ #[arg(long = "no-loop", help = "The clip plays once")]
+ no_loop: bool,
+ #[arg(long, help = "The clip's own fps, or doc for the document's")]
+ fps: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Layer tree with ids, kinds, contents and bounds at a frame, top layer first")]
+ Ls {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = "One layer, cel, node, stroke or fill (<cel>:s<id>) in full (JSON)")]
+ Show { bundle: PathBuf, id: String },
+ #[command(
+ about = "Add a layer, cel or shape",
+ long_about = "Add a layer, cel or shape.\n\n klad add art.draw layer vector name=sky\n klad add art.draw rect --in l2 x=0 y=0 w=2048 h=900 fill=#1b2a41\n klad add art.draw ellipse --in l2 cx=500 cy=300 rx=80 ry=80 'fill={\"radial\":{\"center\":[500,300],\"radius\":80,\"stops\":[[0,\"#fff6d5\"],[1,\"#f3c76a\"]]}}'\n klad add art.draw cel --in l3 frame=4 hold=2\n\nValues are JSON when they parse as JSON, otherwise strings. Dotted keys nest: transform.rotate=15, stroke.width=3."
+ )]
+ Add {
+ bundle: PathBuf,
+ #[arg(help = "layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text")]
+ what: String,
+ #[arg(
+ help = "For layers the kind first (paint, vector, group, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs"
+ )]
+ rest: Vec<String>,
+ #[command(flatten)]
+ place: Where,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Change properties: klad set art.draw n4 fill=#ff0000 transform.rotate=15 (null removes)",
+ long_about = "Change properties of a layer, cel, shape, stroke or fill. Values are JSON when they parse as JSON, otherwise strings; null removes a key. Dotted keys nest.\n\n klad set art.draw n4 fill=#ff0000 transform.rotate=15\n klad set art.draw l2 opacity=0.5 blend=multiply\n klad set art.draw c4:s12 color=#c84a3a size=6 brush=pencil\n klad set art.draw c4:s7 color=skin opacity=0.8\n\nStrokes take color, size, opacity, flow, brush and taper ([in,out] or null); fills take color and opacity. Colours may be palette names."
+ )]
+ Set {
+ bundle: PathBuf,
+ id: String,
+ props: Vec<String>,
+ #[arg(long, default_value_t = 0, help = "Frame to render with --render")]
+ frame: u32,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Remove layers, cels or nodes")]
+ Rm {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Move, rotate or scale strokes and fills (<cel>:s<id>)",
+ long_about = "Move, rotate or scale strokes and fills, addressed as <cel>:s<id> (klad strokes lists them). Rotation and scale turn about --pivot, by default the middle of the marks' bounds. Stroke sizes and tapers scale with them; fills move by whole pixels and are resampled when turned or scaled.\n\n klad transform art.draw c4:s12 c4:s13 --move 40,-10\n klad transform art.draw c4:s12 --rotate 15 --scale 1.2\n klad transform art.draw c4:s3 c4:s5 --sx -1 --pivot 512,400\n\nAlso a transform op in klad apply: {\"op\":\"transform\",\"ids\":[\"c4:s12\"],\"x\":40,\"y\":-10,\"rotate\":15,\"sx\":1.2,\"sy\":1.2}"
+ )]
+ Transform {
+ bundle: PathBuf,
+ ids: Vec<String>,
+ #[arg(long = "move", value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px")]
+ offset: Option<[f32; 2]>,
+ #[arg(long, allow_hyphen_values = true, help = "Degrees, clockwise")]
+ rotate: Option<f32>,
+ #[arg(long, allow_hyphen_values = true, help = "Uniform scale")]
+ scale: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sx: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sy: Option<f32>,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "x,y to turn and scale about")]
+ pivot: Option<[f32; 2]>,
+ #[arg(long, value_parser = ["h", "v"], help = "Mirror: h (left-right) or v (up-down)")]
+ flip: Option<String>,
+ #[arg(long, default_value_t = 0, help = "Frame to render with --render")]
+ frame: u32,
+ #[command(flatten)]
+ flags: MarkFlags,
+ },
+ #[command(
+ about = "Lasso strokes and fills on a paint layer; --cut also takes the parts crossing the edge",
+ long_about = "Select the strokes and fills of a paint layer inside a polygon and move, turn, scale, flip or delete them in one step. Without --cut only whole marks move: strokes whose points are all inside and fills whose pixels are. With --cut every stroke or fill crossing the edge is split at the edge: the part outside stays where it is and the part inside moves with the rest, so nothing outside the lasso changes. Without a move, turn, scale, flip or --rm it only lists what is inside and what crosses.\n\n klad lasso art.draw l3 --polygon '100,100 400,120 380,400 90,380'\n klad lasso art.draw l3 --polygon '100,100 400,120 380,400 90,380' --cut --move 60,-20\n klad lasso art.draw l3 --polygon '...' --cut --rotate 15 --scale 1.2\n klad lasso art.draw l3 --polygon '...' --flip h\n klad lasso art.draw l3 --polygon '...' --cut --rm\n\nAlso a lasso op in klad apply: {\"op\":\"lasso\",\"layer\":\"l3\",\"polygon\":[[100,100],[400,120],[380,400]],\"cut\":true,\"x\":60,\"y\":-20} (or \"rm\":true)."
+ )]
+ Lasso {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, help = "x,y pairs separated by spaces")]
+ polygon: String,
+ #[arg(
+ long,
+ help = "Split strokes and fills crossing the edge and take the inside parts too"
+ )]
+ cut: bool,
+ #[arg(long = "move", value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px")]
+ offset: Option<[f32; 2]>,
+ #[arg(long, allow_hyphen_values = true, help = "Degrees, clockwise")]
+ rotate: Option<f32>,
+ #[arg(long, allow_hyphen_values = true, help = "Uniform scale")]
+ scale: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sx: Option<f32>,
+ #[arg(long, allow_hyphen_values = true)]
+ sy: Option<f32>,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "x,y to turn, scale and flip about")]
+ pivot: Option<[f32; 2]>,
+ #[arg(long, value_parser = ["h", "v"], help = "Mirror: h (left-right) or v (up-down)")]
+ flip: Option<String>,
+ #[arg(long, help = "Delete what the lasso holds")]
+ rm: bool,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[command(flatten)]
+ flags: MarkFlags,
+ },
+ #[command(
+ about = "List the points of a path, rect or ellipse, or edit them",
+ long_about = "Without edit flags: list the points (anchors) of a path, rect or ellipse with their handles, numbered across subpaths. Coordinates are the shape's own, as in its d, before its transform. Any edit turns a rect or ellipse into a path that looks the same.\n\n klad path art.draw n7\n klad path art.draw n7 --move 3 412,230\n klad path art.draw n7 --nudge 3,4,5 0,-20\n klad path art.draw n7 --handle 3 out 430,210\n klad path art.draw n7 --insert 3,0.5 (split the segment after point 3)\n klad path art.draw n7 --add 418,236 (a point on the nearest segment)\n klad path art.draw n7 --rm 4,5 --corner 2 --smooth 6\n klad path art.draw n7 --simplify 1.5 (fewer, smooth points within 1.5 px)\n\nAs ops: {\"op\":\"path\",\"id\":\"n7\",\"move\":3,\"to\":[412,230]}, \"move\":[3,4],\"by\":[0,-20]; \"handle\":3,\"out\":[430,210]; \"insert\":3,\"t\":0.5; \"add\":[418,236]; \"rm\":[4,5]; \"corner\":2; \"smooth\":6; \"simplify\":1.5. A smooth point keeps its handles in line unless \"free\":true."
+ )]
+ Path {
+ bundle: PathBuf,
+ node: String,
+ #[arg(long = "move", num_args = 2, value_names = ["POINT", "X,Y"], allow_hyphen_values = true)]
+ move_to: Option<Vec<String>>,
+ #[arg(long, num_args = 2, value_names = ["POINTS", "DX,DY"], allow_hyphen_values = true)]
+ nudge: Option<Vec<String>>,
+ #[arg(long, num_args = 3, value_names = ["POINT", "in|out", "X,Y"], allow_hyphen_values = true)]
+ handle: Option<Vec<String>>,
+ #[arg(long, value_name = "POINT[,T]")]
+ insert: Option<String>,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, value_name = "X,Y")]
+ add: Option<[f32; 2]>,
+ #[arg(long, value_name = "POINTS")]
+ rm: Option<String>,
+ #[arg(long, value_name = "POINTS")]
+ corner: Option<String>,
+ #[arg(long, value_name = "POINTS")]
+ smooth: Option<String>,
+ #[arg(long, value_name = "PX")]
+ simplify: Option<f32>,
+ #[arg(long, help = "Turn a rect or ellipse into a path without other changes")]
+ convert: bool,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Move a layer or node: --above, --below, --in, --index")]
+ Mv {
+ bundle: PathBuf,
+ id: String,
+ #[command(flatten)]
+ place: Where,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Apply many edits from JSON lines (stdin or --file) in one write",
+ long_about = "Apply many edits from JSON lines in one transaction: all apply or none.\n\n {\"op\":\"add\",\"layer\":{\"kind\":\"vector\",\"name\":\"sky\"}}\n {\"op\":\"add\",\"node\":{\"type\":\"rect\",\"x\":0,\"y\":0,\"w\":100,\"h\":50,\"fill\":\"#336699\"},\"in\":\"l1\"}\n {\"op\":\"set\",\"id\":\"n2\",\"fill\":\"#ff0000\",\"transform.rotate\":15}\n {\"op\":\"rm\",\"id\":\"n2\"}\n {\"op\":\"mv\",\"id\":\"l1\",\"below\":\"l3\"}\n {\"op\":\"add\",\"cel\":{\"frame\":4,\"hold\":2},\"in\":\"l3\"}\n\nNew ids are printed in order."
+ )]
+ Apply {
+ bundle: PathBuf,
+ #[arg(long)]
+ file: Option<PathBuf>,
+ #[arg(long, default_value_t = 0, help = "Frame to render with --render")]
+ frame: u32,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Render a frame to PNG and print the path")]
+ Render {
+ bundle: PathBuf,
+ #[arg(short, long)]
+ out: Option<PathBuf>,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Scale (default 1, or longest side 1024 px with --focus)")]
+ scale: Option<f32>,
+ #[arg(long, value_parser = parse_region, help = "Only this canvas region: x,y,w,h")]
+ region: Option<[i32; 4]>,
+ #[arg(long, help = "Zoom to a layer, cel or node, with a margin")]
+ focus: Option<String>,
+ #[arg(
+ long,
+ help = "Draw on top: ids, bbox, grid, onion, parts, arcs or all (comma separated); onion shows the drawings before (red) and after (green) under each animated layer, parts boxes each named part, arcs the paths of --track"
+ )]
+ overlay: Option<String>,
+ #[arg(
+ long,
+ help = "With --overlay arcs (implied): a mark (c4:s12), a part (leaf, or lines:leaf) or a point (x,y) whose path across the clip or sheet is drawn; repeat for more"
+ )]
+ track: Vec<String>,
+ #[arg(long, default_value_t = 1, help = "How deep into groups the overlay labels go")]
+ depth: usize,
+ #[arg(long, help = "Replay every stroke instead of using cached tiles")]
+ no_cache: bool,
+ #[arg(long, help = "Show reference layers (photos to trace over), which renders leave out")]
+ references: bool,
+ #[arg(long, value_name = "BEFORE,AFTER", value_parser = parse_onion_counts, help = "Onion skin: how many drawings (or frames) before and after (default 2,2)")]
+ onion: Option<(u32, u32)>,
+ #[arg(
+ long,
+ value_name = "drawings|frames",
+ help = "Count the onion skin in drawings (default) or in frames"
+ )]
+ onion_by: Option<String>,
+ #[arg(
+ long,
+ value_name = "LAYERS",
+ value_delimiter = ',',
+ help = "Layers that show onion skin (ids or names; default: every layer with more than one drawing)"
+ )]
+ onion_layers: Option<Vec<String>>,
+ #[arg(long, help = "Onion skin without the red and green tint")]
+ no_tint: bool,
+ #[arg(long, value_name = "FROM-TO", value_parser = parse_span, help = "Treat these frames as a loop: the onion skin wraps around inside them")]
+ onion_loop: Option<(u32, u32)>,
+ #[arg(
+ long,
+ value_name = "all|FROM-TO|CLIP",
+ help = "Render many frames in one grid, labelled with frame numbers, drawing ids and holds"
+ )]
+ sheet: Option<String>,
+ #[arg(
+ long,
+ help = "With --sheet: one cell per drawing (frames that look the same share a cell)"
+ )]
+ drawings: bool,
+ #[arg(
+ long,
+ default_value_t = 256,
+ help = "With --sheet: the longest side of each cell in px"
+ )]
+ cell: u32,
+ #[arg(long, help = "With --sheet: cells per row (default: about square)")]
+ columns: Option<usize>,
+ },
+ #[command(
+ about = "Paint a stroke with a brush along an SVG path or explicit points",
+ long_about = "Paint with a brush along an SVG path (M, L, H, V, C, S, Q, T, Z; several subpaths make several strokes) or explicit points.\n\n klad stroke art.draw l3 --brush ink --size 14 --color #1b1b1b --path 'M100 400 C 300 200 500 600 700 400' --pressure 0.1,1,0.05\n klad stroke art.draw l3 --brush ink --size 6 --taper 12,30 --path 'M100 100 Q 200 40 300 120'\n klad stroke art.draw l3 --points '10,10,0.5 40,30,1 80,35,0.2'\n\nPressure is spread evenly along the stroke. --taper thins the first and last px of the line whatever the pressure. Brushes are a bundle brush id or a library brush (klad brushes). Strokes are marked as agent strokes."
+ )]
+ Stroke {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long)]
+ path: Option<String>,
+ #[arg(long, help = "x,y,pressure triples separated by spaces")]
+ points: Option<String>,
+ #[arg(long, default_value = "ink")]
+ brush: String,
+ #[arg(long, default_value = "#000000")]
+ color: String,
+ #[arg(long, default_value_t = 8.0)]
+ size: f32,
+ #[arg(long, default_value_t = 1.0)]
+ opacity: f32,
+ #[arg(long, default_value_t = 1.0)]
+ flow: f32,
+ #[arg(long, help = "Pressure along the stroke, for example 0.2,1,0.1")]
+ pressure: Option<String>,
+ #[arg(
+ long,
+ default_value_t = 700.0,
+ help = "Pen speed in px/s, sets sample spacing and timing"
+ )]
+ speed: f32,
+ #[arg(long)]
+ seed: Option<u32>,
+ #[arg(
+ long,
+ help = "Taper in and out by length in px, for example 12,30 (default: the brush's)"
+ )]
+ taper: Option<String>,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[arg(
+ long,
+ help = "The second colour, for brushes that mix towards it with pressure or along the stroke"
+ )]
+ second: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Fill a region of a paint layer, inside the lines (flood) or inside a polygon (lasso)",
+ long_about = "Fill a region of a paint layer. A flood fill starts at --at and spreads over pixels within --tolerance of that pixel in the reference: this layer (default), all (everything visible) or a layer id or name. --gap closes openings in the lines up to that many px wide; --expand grows the fill under the lines by that many px. --polygon fills a lasso polygon instead. The fill is stored with its coverage, so it renders the same later; klad refill recomputes it after the lines change.\n\n klad fill art.draw l2 --at 820,640 --ref lines --gap 4 --color '#c84a3a'\n klad fill art.draw l2 --at 820,640 --ref all --color skin\n klad fill art.draw l2 --polygon '100,100 400,120 260,380' --color '#20304a'\n\nColours are #rrggbb, #rrggbbaa or a palette name. Also a fill op in klad apply: {\"op\":\"fill\",\"layer\":\"l2\",\"at\":[820,640],\"ref\":\"lines\",\"gap\":4,\"color\":\"#c84a3a\"}"
+ )]
+ Fill {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, value_parser = parse_pair, help = "Seed point x,y for a flood fill")]
+ at: Option<[f32; 2]>,
+ #[arg(long, help = "Lasso polygon: x,y pairs separated by spaces")]
+ polygon: Option<String>,
+ #[arg(long = "ref", help = "this (default), all, or a layer id or name")]
+ reference: Option<String>,
+ #[arg(long, default_value_t = TOLERANCE, help = "0..1, how different a pixel may be from the seed")]
+ tolerance: f32,
+ #[arg(long, default_value_t = 0.0, help = "Close openings in the lines up to this many px")]
+ gap: f32,
+ #[arg(long, default_value_t = EXPAND, help = "Grow the fill under the lines by this many px")]
+ expand: f32,
+ #[arg(long, default_value = "#000000")]
+ color: String,
+ #[arg(long, default_value_t = 1.0)]
+ opacity: f32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(
+ long,
+ conflicts_with_all = ["at", "polygon"],
+ help = "Carry the flood fills of this drawing (a cel of the layer) to the layer's other drawings"
+ )]
+ like: Option<String>,
+ #[arg(
+ long,
+ requires = "like",
+ help = "With --like: the frames whose drawings get them: all, FROM-TO or a clip"
+ )]
+ frames: Option<String>,
+ #[arg(
+ long,
+ conflicts_with_all = ["at", "polygon", "like"],
+ help = "Fill exactly the area of a vector shape (a group: each closed shape in it), grown by --expand"
+ )]
+ shape: Option<String>,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Ink the outlines of vector shapes as tapered strokes, the way an inker would",
+ long_about = "Ink the outlines of vector shapes (rects, ellipses, paths, groups of them; often on a hidden sketch layer) as strokes on a paint layer. An outline is split into separate strokes at corners sharper than --break degrees, each stroke tapers in and out, and its weight follows rules instead of pressure written by hand: heavier on the side facing away from the light, heavier on the silhouette (the outer edge of the shapes inked together) than on inner lines, thinner along tight curves, with a small seeded wobble.\n\n klad ink art.draw lines --from body,eye,leg --weight 6 --light -1,-1\n klad ink art.draw lines --from rock --weight 9 --break 45 --gap 3 --wobble 1\n klad ink art.draw lines --path \"M10 10 C 80 0 120 60 200 40\" --weight 4\n\nThe strokes are ordinary agent strokes: klad set, klad transform and the editor edit them. Also an ink op: {\"op\":\"ink\",\"layer\":\"l3\",\"from\":[\"n5\"],\"weight\":6,\"light\":[-1,-1],\"break\":60,\"gap\":0,\"wobble\":0.6}."
+ )]
+ Ink {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ help = "Vector shape ids; a group inks every shape in it"
+ )]
+ from: Vec<String>,
+ #[arg(long, help = "SVG path data to ink instead of shapes")]
+ path: Option<String>,
+ #[arg(long, default_value_t = 6.0, help = "The full line weight in px")]
+ weight: f32,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "Where the light comes from, x,y (-1,-1: top left)")]
+ light: Option<[f32; 2]>,
+ #[arg(
+ long = "break",
+ default_value_t = 60.0,
+ help = "Split strokes at corners sharper than this many degrees"
+ )]
+ break_deg: f32,
+ #[arg(
+ long,
+ default_value_t = 0.0,
+ help = "Leave this many px open at the ends of each stroke"
+ )]
+ gap: f32,
+ #[arg(long, default_value_t = 0.6, help = "Seeded wobble in px (0: none)")]
+ wobble: f32,
+ #[arg(long, value_parser = parse_pair, help = "Taper in,out in px (default: the brush's)")]
+ taper: Option<[f32; 2]>,
+ #[arg(long, default_value = "ink")]
+ brush: String,
+ #[arg(long, default_value = "#000000")]
+ color: String,
+ #[arg(long, default_value_t = 1)]
+ seed: u32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[arg(
+ long,
+ default_value_t = 1.0,
+ help = "How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)"
+ )]
+ hand: f32,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Shade and rim light vector shapes from one light direction",
+ long_about = "Make the two lighting layers of the flat-colour recipe from the shapes: on --shade, the side of each shape facing away from the light (the shape minus itself moved towards the light by --depth, in --soft overlapping steps so the inner edge is soft); on --rim, a thin band along the edge facing the light. Both are lasso fills with a cut, so with the layers clipped to the flats (multiply for shade, screen or add for rim) the light follows the shapes.\n\n klad light art.draw --from body,head --light -1,-1 --shade shade --rim rim\n klad light art.draw --from rock --shade shade --depth 24 --soft 4 --shade-color '#3a2f50'\n\nAlso a light op: {\"op\":\"light\",\"from\":[\"n5\"],\"light\":[-1,-1],\"shade\":\"l5\",\"rim\":\"l6\",\"depth\":14,\"soft\":3,\"rimWidth\":4}."
+ )]
+ Light {
+ bundle: PathBuf,
+ #[arg(
+ long,
+ value_delimiter = ',',
+ help = "Vector shape ids; a group lights every closed shape in it"
+ )]
+ from: Vec<String>,
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "Where the light comes from, x,y (-1,-1: top left)")]
+ light: Option<[f32; 2]>,
+ #[arg(long, help = "The paint layer for the shade")]
+ shade: Option<String>,
+ #[arg(long, help = "The paint layer for the rim light")]
+ rim: Option<String>,
+ #[arg(long, default_value_t = 14.0, help = "How far the shade reaches into a shape, px")]
+ depth: f32,
+ #[arg(long, default_value_t = 3, help = "Overlapping shade steps (1: a hard edge)")]
+ soft: u32,
+ #[arg(long = "rim-width", default_value_t = 4.0)]
+ rim_width: f32,
+ #[arg(long = "shade-color", default_value = "#5a4a6a")]
+ shade_color: String,
+ #[arg(long = "rim-color", default_value = "#fff1cc")]
+ rim_color: String,
+ #[arg(long = "shade-opacity", default_value_t = 0.6)]
+ shade_opacity: f32,
+ #[arg(long = "rim-opacity", default_value_t = 0.85)]
+ rim_opacity: f32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(
+ long,
+ allow_hyphen_values = true,
+ help = "A lamp at x,y,height in canvas px: each shape is shaded away from it"
+ )]
+ lamp: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Fill a shape's area with short tapered strokes: hatching, bark, fur, stone grain",
+ long_about = "Fill the area of closed vector shapes (or a polygon) with short tapered strokes, parallel at --angle or following the outline (--along), clipped to the area, with seeded variation.\n\n klad hatch art.draw shade --in body --angle 35 --spacing 7 --length 10-24\n klad hatch art.draw lines --in trunk --along --spacing 9 --weight 1.5 --color '#3b2a1e'\n\nAlso a hatch op: {\"op\":\"hatch\",\"layer\":\"l5\",\"in\":[\"n5\"],\"angle\":30,\"spacing\":6,\"length\":[12,30],\"jitter\":0.3,\"weight\":2}."
+ )]
+ Hatch {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long = "in", value_delimiter = ',', help = "Closed vector shapes to hatch inside")]
+ within: Vec<String>,
+ #[arg(long, help = "Or a polygon: x,y pairs separated by spaces")]
+ polygon: Option<String>,
+ #[arg(long, default_value_t = 30.0, allow_hyphen_values = true)]
+ angle: f32,
+ #[arg(long, help = "Follow the outline instead of parallel lines")]
+ along: bool,
+ #[arg(long, default_value_t = 6.0)]
+ spacing: f32,
+ #[arg(long, value_parser = parse_range, default_value = "12-30", help = "Stroke lengths MIN-MAX px")]
+ length: [f32; 2],
+ #[arg(long, default_value_t = 0.3)]
+ jitter: f32,
+ #[arg(long, default_value_t = 2.0, help = "Stroke size in px")]
+ weight: f32,
+ #[arg(long, default_value = "ink")]
+ brush: String,
+ #[arg(long, default_value = "#000000")]
+ color: String,
+ #[arg(long, default_value_t = 1.0)]
+ opacity: f32,
+ #[arg(long, default_value_t = 1)]
+ seed: u32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[arg(
+ long,
+ default_value_t = 1.0,
+ help = "How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)"
+ )]
+ hand: f32,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Paint a shape as a form, with strokes that follow it and colours from a light model",
+ long_about = "Paint closed vector shapes (or a polygon) as forms. --form round bulges any closed shape like a pillow (its height grows with the distance to its outline), flat is a plane facing --facing x,y,z, cylinder is round across --axis degrees. The light model: a key light from --light x,y at --elevation (or a --lamp x,y,height in canvas px; the shape nearest the lamp gets the full key light and farther ones less, by inverse square), cool fill from above (--fill, --fill-strength), warm bounce from below (--bounce, --bounce-strength) and a darker core just past the terminator (--core). --color is the local colour in full light.\n\nStrokes follow the form: along bands of equal light on round forms, along the axis on cylinders, at --angle on planes. Each takes its colour from the model where it lies and stops where the light changes, so no stroke carries the lit colour into the shadow. Passes go from 2x --weight down to half of it (the small ones only where the form turns), then a decisive pass with --bold in the lights and a few quiet strokes in the shadows (--decisive 0 skips both). Every stroke is drawn like a hand (--hand): its own pressure curve, tapers and width.\n\nPaint on a layer clipped to the flats, or lock the flats layer and paint into it: then strokes run past the outline and a pass of short strokes along it cuts the edge in, so no flat colour shows at the rim. On a plain layer strokes stay inside the outline.\n\n klad paint art.draw paint --in rock --color '#8a8f96' --light -1,-1\n klad paint art.draw paint --in pillar --form cylinder --axis 90 --color '#c9b8a0' --lamp 200,600,150\n klad paint art.draw paint --in wall --form flat --facing 0,0,1 --angle 0 --weight 10\n\nAlso a paint op: {\"op\":\"paint\",\"layer\":\"l5\",\"in\":[\"n5\"],\"color\":\"#5d6a78\",\"light\":[-1,-1],\"weight\":14,\"form\":\"round\"}."
+ )]
+ Paint {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long = "in", value_delimiter = ',', help = "Closed vector shapes to paint inside")]
+ within: Vec<String>,
+ #[arg(long, help = "Or a polygon: x,y pairs separated by spaces")]
+ polygon: Option<String>,
+ #[arg(long, default_value = "oil")]
+ brush: String,
+ #[arg(
+ long,
+ default_value = "oil-load",
+ help = "The brush for the decisive strokes in the lights"
+ )]
+ bold: String,
+ #[arg(long, default_value = "#808080", help = "The local colour in full light")]
+ color: String,
+ #[arg(long, default_value = "round", help = "round, flat or cylinder")]
+ form: String,
+ #[arg(
+ long,
+ default_value_t = 90.0,
+ allow_hyphen_values = true,
+ help = "A cylinder's axis in degrees (90 is vertical)"
+ )]
+ axis: f32,
+ #[arg(
+ long,
+ default_value = "0,0,1",
+ allow_hyphen_values = true,
+ help = "A flat form's facing x,y,z (z toward the viewer, y down)"
+ )]
+ facing: String,
+ #[arg(long, value_parser = parse_pair, default_value = "-1,-1", allow_hyphen_values = true, help = "Where the light comes from, as a direction x,y")]
+ light: [f32; 2],
+ #[arg(
+ long,
+ default_value_t = 0.6,
+ help = "How far the light is toward the viewer (0 grazes the picture)"
+ )]
+ elevation: f32,
+ #[arg(
+ long,
+ allow_hyphen_values = true,
+ help = "A lamp at x,y,height in canvas px instead of a direction"
+ )]
+ lamp: Option<String>,
+ #[arg(long, default_value = "#fff3e2", help = "The key light's colour")]
+ key: String,
+ #[arg(long, default_value = "#8a9ab8", help = "The fill light's colour, from above")]
+ fill: String,
+ #[arg(long, default_value_t = 0.16)]
+ fill_strength: f32,
+ #[arg(long, default_value = "#b08a66", help = "The bounce light's colour, from below")]
+ bounce: String,
+ #[arg(long, default_value_t = 0.1)]
+ bounce_strength: f32,
+ #[arg(
+ long,
+ default_value_t = 0.35,
+ help = "How much darker the core just past the terminator is"
+ )]
+ core: f32,
+ #[arg(
+ long,
+ default_value_t = 30.0,
+ allow_hyphen_values = true,
+ help = "Stroke direction on flat forms, degrees"
+ )]
+ angle: f32,
+ #[arg(long, default_value_t = 14.0, help = "Stroke size in px of the middle pass")]
+ weight: f32,
+ #[arg(
+ long,
+ default_value_t = 1.0,
+ help = "How many decisive and quiet strokes, 0 for none"
+ )]
+ decisive: f32,
+ #[arg(long, default_value_t = 0.03, help = "How much each stroke's value strays")]
+ vary: f32,
+ #[arg(
+ long,
+ default_value_t = 1.0,
+ help = "How much each stroke is drawn like a hand (0 gives even strokes)"
+ )]
+ hand: f32,
+ #[arg(long, default_value_t = 1.0)]
+ opacity: f32,
+ #[arg(long, default_value_t = 1)]
+ seed: u32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Buffer the drawings of a span of frames, as the editor's prepare does",
+ long_about = "Replay every painted drawing shown in frames --from to --to (all frames by default) into the bundle's cache, so the editor and later renders read them instead of replaying their strokes. Run it after a big change made by the CLI, before the editor opens or plays the file.\n\n klad prepare art.draw\n klad prepare art.draw --from 0 --to 23"
+ )]
+ Prepare {
+ bundle: PathBuf,
+ #[arg(long)]
+ from: Option<u32>,
+ #[arg(long)]
+ to: Option<u32>,
+ },
+ #[command(
+ about = "Scatter copies of a small mark over a shape: grass, cracks, dots",
+ long_about = "Scatter copies of a small mark (SVG path data around 0,0) inside closed vector shapes (or a polygon), avoiding other shapes, each copy scaled and turned a little (seeded).\n\n klad scatter art.draw lines --in ground --mark \"M0 0 L0 -18\" --count 40 --size 0.7-1.2 --turn -15,15\n klad scatter art.draw lines --in rock --mark \"M0 0 L6 3 L10 -2\" --spacing 22 --avoid moss\n\nAlso a scatter op: {\"op\":\"scatter\",\"layer\":\"l3\",\"in\":[\"n5\"],\"mark\":\"M0 0 L0 -18\",\"count\":40,\"size\":[0.7,1.2],\"turn\":[-15,15],\"avoid\":[\"n9\"]}."
+ )]
+ Scatter {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long = "in", value_delimiter = ',', help = "Closed vector shapes to scatter inside")]
+ within: Vec<String>,
+ #[arg(long, help = "Or a polygon: x,y pairs separated by spaces")]
+ polygon: Option<String>,
+ #[arg(long, value_delimiter = ',', help = "Shapes to keep clear of")]
+ avoid: Vec<String>,
+ #[arg(long, default_value = "M0 0 L0 -18", allow_hyphen_values = true)]
+ mark: String,
+ #[arg(long, help = "How many marks (default: one every --spacing px)")]
+ count: Option<usize>,
+ #[arg(long, default_value_t = 14.0)]
+ spacing: f32,
+ #[arg(long, value_parser = parse_range, default_value = "0.7-1.2", help = "Scale of each copy MIN-MAX")]
+ size: [f32; 2],
+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, default_value = "-15,15", help = "Turn of each copy MIN,MAX degrees")]
+ turn: [f32; 2],
+ #[arg(long, default_value_t = 2.0, help = "Stroke size in px")]
+ weight: f32,
+ #[arg(long, default_value = "ink")]
+ brush: String,
+ #[arg(long, default_value = "#000000")]
+ color: String,
+ #[arg(long, default_value_t = 1.0)]
+ opacity: f32,
+ #[arg(long, default_value_t = 1)]
+ seed: u32,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the new marks in this part of the drawing (see klad part)")]
+ part: Option<String>,
+ #[arg(
+ long,
+ default_value_t = 1.0,
+ help = "How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)"
+ )]
+ hand: f32,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "List closed regions of the lines that no fill on the layer covers",
+ long_about = "List the closed regions of a fill layer's reference (the lines its flood fills fill against) that no fill on the layer covers: pockets a fill missed, or drawings not coloured yet. Regions open to the canvas edge are the outside and do not count. Each pocket prints its bounds and size, and a render of the frame marks them in magenta with a box.\n\n klad gaps art.draw colour --frame 4\n klad gaps art.draw colour --sheet all\n klad gaps art.draw colour --sheet walk --ref lines --gap 4\n\nThe reference, gap and tolerance default to those of the layer's flood fills on those frames."
+ )]
+ Gaps {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, conflicts_with = "sheet")]
+ frame: Option<u32>,
+ #[arg(long, value_name = "all|FROM-TO|CLIP", help = "Check many frames")]
+ sheet: Option<String>,
+ #[arg(long = "ref", help = "this, all or a layer (default: what the layer's fills use)")]
+ reference: Option<String>,
+ #[arg(long, help = "Close openings up to this many px (default: the fills' gap)")]
+ gap: Option<f32>,
+ #[arg(long)]
+ tolerance: Option<f32>,
+ #[arg(long, default_value_t = 12, help = "Ignore pockets smaller than this many px")]
+ min: usize,
+ #[arg(long, help = "Render the frames even when nothing is found")]
+ render: bool,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = "Recompute the flood fills of a paint cel after the lines they were made from changed")]
+ Refill {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Only this fill (klad strokes lists fill ids)")]
+ id: Option<u32>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "The document palette: list, --add a colour (with --name), --rm a name, colour or index",
+ long_about = "The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin).\n\n klad palette art.draw\n klad palette art.draw --add '#f0c8a0' --name skin\n klad palette art.draw --add '#d0a080' --name skin (changes skin)\n klad palette art.draw --rm skin\n\nAs ops: {\"op\":\"palette\",\"add\":\"#f0c8a0\",\"name\":\"skin\"}, {\"op\":\"palette\",\"rm\":\"skin\"}, {\"op\":\"palette\",\"set\":[{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]}"
+ )]
+ Palette {
+ bundle: PathBuf,
+ #[arg(long)]
+ add: Option<String>,
+ #[arg(long, requires = "add")]
+ name: Option<String>,
+ #[arg(long, conflicts_with = "add")]
+ rm: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene",
+ long_about = "Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.\n\n klad export art.draw\n klad export art.draw --scale 2\n klad export art.draw --layer lines --scale 4 --depth 16 -o lines.png\n\nAnimations (each clip, or the whole timeline when there are no clips):\n\n klad export art.draw --sheet all [--scale 0.5] [--padding 2] [--max 4096]\n a PNG holding each distinct picture once, trimmed to its pixels (more pages, art-sheet-2.png ..., when it does not fit --max), plus art-sheet.json in Aseprite's array layout: one entry per exposure with its duration in ms, frameTags for clips\n klad export art.draw --sheet run one clip; --sheet 0-11 a range\n klad export art.draw --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/\n klad export art.draw --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder."
+ )]
+ Export {
+ bundle: PathBuf,
+ #[arg(long, help = "PNG output (the default for a single image)")]
+ png: bool,
+ #[arg(long, help = "A layer or group id or name instead of the whole image")]
+ layer: Option<String>,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, default_value_t = 1.0)]
+ scale: f32,
+ #[arg(long, default_value_t = 8, help = "8 (dithered) or 16 bits per channel")]
+ depth: u8,
+ #[arg(long, help = "Keep the canvas background instead of transparency")]
+ background: bool,
+ #[arg(long, help = "Keep reference layers (photos to trace over), which exports leave out")]
+ references: bool,
+ #[arg(
+ long,
+ conflicts_with_all = ["frames", "godot"],
+ help = "Sprite sheet and Aseprite JSON: all, a clip or a range like 0-11"
+ )]
+ sheet: Option<String>,
+ #[arg(
+ long,
+ conflicts_with = "godot",
+ help = "Numbered PNGs, one per frame: all, a clip or a range"
+ )]
+ frames: Option<String>,
+ #[arg(
+ long,
+ num_args = 0..=1,
+ help = "Godot SpriteFrames and AnimatedSprite2D scene into this folder (default: the document's export.godot)"
+ )]
+ godot: Option<Option<PathBuf>>,
+ #[arg(
+ long,
+ requires = "godot",
+ help = "Keep the --godot folder as the document's, replacing the one it has"
+ )]
+ store: bool,
+ #[arg(long, default_value_t = 2, help = "Sheets: transparent pixels around each picture")]
+ padding: u32,
+ #[arg(long, default_value_t = 4096, help = "Sheets: largest page side in px")]
+ max: u32,
+ #[arg(short, long)]
+ out: Option<PathBuf>,
+ },
+ #[command(
+ about = "List brushes: the library, and with a bundle the ones it embeds",
+ long_about = "List brushes: the built-in library, and with a bundle the brushes it embeds (a document keeps every brush it uses in brushes/<id>.json, so it renders the same when the library changes).\n\n klad brushes\n klad brushes art.draw\n klad brushes art.draw --show ink"
+ )]
+ Brushes {
+ bundle: Option<PathBuf>,
+ #[arg(long, help = "Print one brush in full (JSON)")]
+ show: Option<String>,
+ #[arg(long)]
+ json: bool,
+ #[arg(long, num_args = 2, value_names = ["ID", "FILE"], help = "Add a brush to the bundle from a JSON file (- for stdin)")]
+ set: Option<Vec<String>>,
+ #[arg(long, num_args = 2, value_names = ["NAME", "PNG"], help = "Add a picture (tip or texture) to the bundle's brushes/images")]
+ picture: Option<Vec<String>>,
+ },
+ #[command(
+ about = "List, add or remove a layer's effects: klad effect art.draw l3 glow radius=24 color=#ffd080",
+ long_about = "Effects apply in order when the layer composes: blur (radius), glow (radius, strength, threshold, color, blend), outline (width, color, inside), shadow (x, y, radius, color), noise (amount, size, seed, mono), displace (amount, size, seed, by: a layer id whose red and green push the pixels). With no effect name it lists them."
+ )]
+ Effect {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(help = "blur, glow, outline, shadow, noise or displace, then key=value pairs")]
+ rest: Vec<String>,
+ #[arg(long, help = "Remove the effect at this position (0 is the first)")]
+ rm: Option<usize>,
+ #[arg(long, help = "Remove every effect")]
+ clear: bool,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "Bend a brush stroke along a new path; it keeps its pressure, tilt and timing (klad strokes --json gives each stroke's fitted path)"
+ )]
+ Reshape {
+ bundle: PathBuf,
+ #[arg(help = "The stroke, <cel>:s<id>")]
+ stroke: String,
+ #[arg(long, help = "SVG path data the stroke follows from start to end")]
+ path: String,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Undo the last change (from the CLI or the editor)")]
+ Undo {
+ bundle: PathBuf,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Redo the last undone change")]
+ Redo {
+ bundle: PathBuf,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(about = "Recent changes, newest first")]
+ Log {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 20)]
+ limit: usize,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = "What the human has selected in the editor (layer and shapes, with bounds)")]
+ Selection {
+ bundle: PathBuf,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = "Notes the human pinned on the canvas; --done <id> marks one as handled")]
+ Notes {
+ bundle: PathBuf,
+ #[arg(long)]
+ done: Option<u32>,
+ #[arg(long, help = "Include notes already marked done")]
+ all: bool,
+ #[arg(long)]
+ json: bool,
+ },
+ #[command(about = "Before and after renders of a change, side by side (default: the last one)")]
+ Diff {
+ bundle: PathBuf,
+ #[arg(long, help = "History step number from klad log")]
+ step: Option<u64>,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long)]
+ scale: Option<f32>,
+ },
+ #[command(about = "Paint cels with stroke counts and file sizes")]
+ Info { bundle: PathBuf },
+ #[command(about = "List the strokes and fills of a paint layer's cel at a frame")]
+ Strokes {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, default_value_t = 0, help = "Only strokes with an id above this")]
+ after: u32,
+ #[arg(long, help = "Print strokes as JSON with their points (x, y, pressure)")]
+ json: bool,
+ },
+ #[command(about = "Print pixel hashes, for comparing macOS and Linux renders")]
+ Hash {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "One line per frame of the timeline")]
+ all: bool,
+ #[arg(long)]
+ no_cache: bool,
+ },
+ #[command(about = "Write a sample bundle (vector sky and hills, painted glow, clouds, hatching, grass)")]
+ Demo {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 2048)]
+ size: u32,
+ #[arg(long, default_value_t = 1)]
+ seed: u64,
+ #[arg(long, help = "Replace an existing bundle")]
+ force: bool,
+ },
+ #[command(about = "Create a large bundle of synthetic paint layers for editor performance tests")]
+ Stress {
+ bundle: PathBuf,
+ #[arg(long, default_value_t = 4096)]
+ size: u32,
+ #[arg(long, default_value_t = 30)]
+ layers: usize,
+ #[arg(long, default_value_t = 300)]
+ strokes: usize,
+ #[arg(long, default_value_t = 1)]
+ seed: u64,
+ #[arg(
+ long,
+ default_value_t = 1,
+ help = "Timeline length; a drawing per layer every --every frames"
+ )]
+ frames: u32,
+ #[arg(long, default_value_t = 2)]
+ every: u32,
+ },
+ #[command(about = "Append synthetic ink strokes to a paint layer (sync test)")]
+ Scribble {
+ bundle: PathBuf,
+ #[arg(long)]
+ layer: Option<String>,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, default_value_t = 1)]
+ count: usize,
+ #[arg(long)]
+ seed: Option<u64>,
+ #[arg(long, help = "Brush size for every stroke (default: varied)")]
+ size: Option<f32>,
+ #[arg(long, default_value = "#bf2620")]
+ color: String,
+ },
+ #[command(about = "Print editor saves as they arrive, with how long they took to show up here")]
+ Watch {
+ bundle: PathBuf,
+ #[arg(long, help = "Poll instead of native file events")]
+ poll: bool,
+ #[arg(long, default_value_t = 120)]
+ seconds: u64,
+ },
+ #[command(
+ about = "Print the licence and the third-party notices (every open source part klad is built on)",
+ alias = "licenses"
+ )]
+ Licences,
+ #[command(about = "Measure stroke storage, brush speed, replay, cache and compositing")]
+ Bench {
+ #[arg(long, default_value_t = 10_000)]
+ strokes: usize,
+ #[arg(long, default_value_t = 4096)]
+ size: u32,
+ #[arg(long, default_value_t = 1)]
+ seed: u64,
+ },
+ #[cfg(target_os = "macos")]
+ #[command(about = "Open the editor, on a bundle or on the start window (new, open, recent)")]
+ Open { bundle: Option<PathBuf> },
+}
+
+fn output(flags: &EditFlags, frame: u32) -> Output {
+ Output {
+ json: flags.json,
+ render: flags.render || flags.overlay.is_some(),
+ scale: flags.scale,
+ frame,
+ overlay: flags.overlay.clone(),
+ }
+}
+
+fn mark_transform(
+ offset: Option<[f32; 2]>,
+ rotate: Option<f32>,
+ (scale, sx, sy): (Option<f32>, Option<f32>, Option<f32>),
+ pivot: Option<[f32; 2]>,
+ flip: Option<&str>,
+) -> Result<Option<MarkTransform>> {
+ if offset.is_none() && rotate.is_none() && scale.is_none() && sx.is_none() && sy.is_none() && flip.is_none() {
+ return Ok(None);
+ }
+ let [x, y] = offset.unwrap_or_default();
+ let k = scale.unwrap_or(1.0);
+ let (fx, fy) = match flip {
+ Some("h") => (-1.0, 1.0),
+ Some("v") => (1.0, -1.0),
+ _ => (1.0, 1.0),
+ };
+ let transform = MarkTransform {
+ x,
+ y,
+ rotate: rotate.unwrap_or(0.0),
+ sx: sx.unwrap_or(1.0) * k * fx,
+ sy: sy.unwrap_or(1.0) * k * fy,
+ pivot,
+ };
+ if transform.sx == 0.0 || transform.sy == 0.0 {
+ return Err(anyhow!("scale cannot be 0"));
+ }
+ Ok(Some(transform))
+}
+
+fn parse_numbers(text: &str) -> Result<Vec<f32>> {
+ text.split(',')
+ .map(|v| v.trim().parse::<f32>().map_err(|e| anyhow!("{v:?}: {e}")))
+ .collect()
+}
+
+fn parse_range(text: &str) -> Result<[f32; 2]> {
+ let (a, b) = text
+ .split_once('-')
+ .ok_or_else(|| anyhow!("{text:?} is not MIN-MAX, for example 12-30"))?;
+ Ok([a.trim().parse()?, b.trim().parse()?])
+}
+
+fn polygon_arg(polygon: Option<String>) -> Result<Option<Vec<[f32; 2]>>> {
+ polygon
+ .as_deref()
+ .map(|p| p.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>())
+ .transpose()
+}
+
+fn layer_id(bundle: &std::path::Path, name: &str) -> Result<String> {
+ let opened = klad_core::bundle::Bundle::open(bundle)?;
+ Ok(opened.doc.find_layer(name).map_or(name.to_string(), |l| l.id.clone()))
+}
+
+fn parse_pair(text: &str) -> Result<[f32; 2]> {
+ parse_numbers(text)?
+ .try_into()
+ .map_err(|_| anyhow!("{text:?} is not x,y"))
+}
+
+fn parse_origin(text: &str) -> Result<Option<[f32; 2]>> {
+ match text {
+ "centre" | "center" => Ok(None),
+ _ => Ok(Some(parse_pair(text)?)),
+ }
+}
+
+fn parse_clip_fps(text: &str) -> Result<Option<u32>> {
+ match text {
+ "doc" => Ok(None),
+ _ => text
+ .parse::<u32>()
+ .ok()
+ .filter(|f| (1..=240).contains(f))
+ .map(Some)
+ .ok_or_else(|| anyhow!("--fps takes 1 to 240, or doc for the document's fps")),
+ }
+}
+
+fn parse_points(text: &str) -> Result<Vec<[f32; 3]>> {
+ text.split_whitespace()
+ .map(|triple| {
+ let v = parse_numbers(triple)?;
+ match v[..] {
+ [x, y] => Ok([x, y, 1.0]),
+ [x, y, p] => Ok([x, y, p]),
+ _ => Err(anyhow!("{triple:?} is not x,y or x,y,pressure")),
+ }
+ })
+ .collect()
+}
+
+const CHANGED_EXIT: i32 = 75;
+
+fn main() {
+ #[cfg(unix)]
+ unsafe {
+ libc::signal(libc::SIGPIPE, libc::SIG_DFL);
+ }
+ if let Err(e) = run() {
+ eprintln!("Error: {e:?}");
+ let changed = e.downcast_ref::<klad_core::bundle::Changed>().is_some();
+ std::process::exit(if changed { CHANGED_EXIT } else { 1 });
+ }
+}
+
+fn run() -> Result<()> {
+ match Cli::parse().command {
+ Command::New {
+ bundle,
+ width,
+ height,
+ layers,
+ background,
+ fps,
+ frames,
+ sketch,
+ } => {
+ edit::new(
+ &bundle,
+ &Blank {
+ width,
+ height,
+ layers,
+ background,
+ fps,
+ frames,
+ sketch,
+ },
+ )?;
+ println!("{}", bundle.display());
+ }
+ Command::Frames { bundle, from, to, json } => frames::sheet(&bundle, from, to, json)?,
+ Command::Frame {
+ bundle,
+ action,
+ at,
+ count,
+ layers,
+ flags,
+ } => {
+ let spec = FrameSpec {
+ insert: action == "insert",
+ at,
+ count,
+ layers: (!layers.is_empty()).then_some(layers),
+ };
+ agent::edit(&bundle, &[Op::Frames(spec)], &output(&flags, at))?;
+ }
+ Command::Arcs {
+ bundle,
+ track,
+ clip,
+ from,
+ to,
+ ground,
+ travel,
+ slack,
+ json,
+ check,
+ } => {
+ let opened = Bundle::open(&bundle)?;
+ let span = match clip {
+ Some(name) => {
+ let c = opened
+ .doc
+ .timeline
+ .clip(&name)
+ .ok_or_else(|| anyhow!("no clip {name}"))?;
+ (c.from, c.to)
+ }
+ None => (
+ from.unwrap_or(0),
+ to.unwrap_or(opened.doc.timeline.frames.saturating_sub(1)),
+ ),
+ };
+ let tracks = track
+ .iter()
+ .map(|t| arcs::Track::parse(t))
+ .collect::<Result<Vec<_>>>()?;
+ let checks = arcs::Checks {
+ ground,
+ travel,
+ slack,
+ json,
+ check,
+ };
+ arcs::report(&opened, &tracks, span, &checks)?;
+ }
+ Command::Part {
+ bundle,
+ ids,
+ name,
+ flags,
+ } => {
+ agent::edit(&bundle, &[Op::Part { ids, name }], &output(&flags, 0))?;
+ }
+ Command::Duplicate { bundle, layer, flags } => {
+ let layer = layer_id(&bundle, &layer)?;
+ agent::edit(&bundle, &[Op::Duplicate { layer }], &output(&flags, 0))?;
+ }
+ Command::Cel {
+ bundle,
+ action,
+ target,
+ frame,
+ hold,
+ insert,
+ flags,
+ } => {
+ let action = match action.as_str() {
+ "new" => CelAction::New { layer: target },
+ "dup" => CelAction::Dup { cel: target },
+ "link" => CelAction::Link { cel: target },
+ "move" => CelAction::Move { cel: target },
+ _ => CelAction::Unlink { cel: target },
+ };
+ let spec = CelSpec {
+ action,
+ id: None,
+ frame,
+ hold,
+ insert,
+ };
+ agent::edit(&bundle, &[Op::Cel(spec)], &output(&flags, frame.unwrap_or(0)))?;
+ }
+ Command::Copy {
+ bundle,
+ ids,
+ to,
+ frame,
+ layer,
+ offset,
+ rotate,
+ scale,
+ sx,
+ sy,
+ pivot,
+ flip,
+ cut,
+ flags,
+ } => {
+ if ids.is_empty() {
+ return Err(anyhow!("give the strokes and fills to copy (<cel>:s<id>)"));
+ }
+ let target = match (to, frame) {
+ (Some(cel), None) => CopyTarget::Cel(cel),
+ (None, Some(frame)) => CopyTarget::Frame { frame, layer },
+ _ => return Err(anyhow!("say where the copies go: --to <cel> or --frame <n>")),
+ };
+ let cut = cut
+ .map(|text| text.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>())
+ .transpose()?;
+ let shown = match &target {
+ CopyTarget::Frame { frame, .. } => *frame,
+ CopyTarget::Cel(_) => 0,
+ };
+ let spec = CopySpec {
+ ids,
+ to: target,
+ transform: mark_transform(offset, rotate, (scale, sx, sy), pivot, flip.as_deref())?,
+ cut,
+ };
+ agent::edit(&bundle, &[Op::Copy(spec)], &output(&flags.edit(), shown))?;
+ }
+ Command::Inbetween {
+ bundle,
+ layers,
+ from,
+ to,
+ count,
+ spacing,
+ matching,
+ pair,
+ redo,
+ force,
+ looping,
+ keep_drawn,
+ unpaired,
+ at,
+ only,
+ keep_cels,
+ force_cels,
+ flags,
+ } => {
+ let pairs = pair.iter().map(|p| parse_mark_pair(p)).collect::<Result<Vec<_>>>()?;
+ let unpaired = match (unpaired.as_str(), at) {
+ ("pop", Some(at)) => Unpaired::parse(&format!("pop {at}"))?,
+ (_, Some(_)) => return Err(anyhow!("--at goes with --unpaired pop")),
+ (mode, None) => Unpaired::parse(mode)?,
+ };
+ let spec = InbetweenSpec {
+ layers,
+ from,
+ to,
+ count,
+ spacing: Spacing::parse(&spacing)?,
+ matching: Match::parse(&matching)?,
+ pairs,
+ redo,
+ force,
+ looping,
+ keep_drawn,
+ unpaired,
+ only,
+ keep_cels,
+ force_cels,
+ resolved: None,
+ };
+ if !redo && (spec.layers.is_empty() || from.is_none() || (to.is_none() && !looping)) {
+ return Err(anyhow!(
+ "give --layers, --from and --to (the two keys; with --loop --to may be left out), or --redo"
+ ));
+ }
+ agent::edit(&bundle, &[Op::Inbetween(spec)], &output(&flags, from.unwrap_or(0)))?;
+ }
+ Command::Retime {
+ bundle,
+ range: (from, to),
+ on,
+ fit,
+ reverse,
+ pingpong,
+ layers,
+ flags,
+ } => {
+ let action = match (on, fit, reverse, pingpong) {
+ (Some(n), None, false, false) => Retime::On(n),
+ (None, Some(n), false, false) => Retime::Fit(n),
+ (None, None, true, false) => Retime::Reverse,
+ (None, None, false, true) => Retime::Pingpong,
+ _ => return Err(anyhow!("say how, with one of --on n, --fit n, --reverse or --pingpong")),
+ };
+ let spec = RetimeSpec {
+ from,
+ to,
+ action,
+ layers: (!layers.is_empty()).then_some(layers),
+ };
+ agent::edit(&bundle, &[Op::Retime(spec)], &output(&flags, from))?;
+ }
+ Command::Timeline {
+ bundle,
+ fps,
+ frames,
+ origin,
+ flags,
+ } => {
+ let origin = origin.as_deref().map(parse_origin).transpose()?;
+ if fps.is_none() && frames.is_none() && origin.is_none() {
+ frames::show_timeline(&Bundle::open(&bundle)?);
+ } else {
+ agent::edit(&bundle, &[Op::Timeline { fps, frames, origin }], &output(&flags, 0))?;
+ }
+ }
+ Command::Clip {
+ bundle,
+ add,
+ set,
+ rm,
+ name,
+ from,
+ to,
+ looping,
+ no_loop,
+ fps,
+ flags,
+ } => {
+ let fps = fps.as_deref().map(parse_clip_fps).transpose()?;
+ let looped = (looping || no_loop).then_some(looping);
+ let edit = match (add, set, rm) {
+ (Some(add), None, None) => {
+ let (Some(from), Some(to)) = (from, to) else {
+ return Err(anyhow!("--add needs --from and --to"));
+ };
+ Some(ClipEdit::Add(klad_core::doc::Clip {
+ fps: fps.flatten(),
+ ..klad_core::doc::Clip::new(&add, from, to, looping)
+ }))
+ }
+ (None, Some(set), None) => Some(ClipEdit::Set {
+ name: set,
+ rename: name,
+ from,
+ to,
+ looping: looped,
+ fps,
+ }),
+ (None, None, Some(rm)) => Some(ClipEdit::Remove { name: rm }),
+ _ => None,
+ };
+ match edit {
+ Some(edit) => agent::edit(&bundle, &[Op::Clip(edit)], &output(&flags, 0))?,
+ None => frames::list_clips(&Bundle::open(&bundle)?, flags.json)?,
+ }
+ }
+ Command::Ls { bundle, frame, json } => agent::ls(&bundle, frame, json)?,
+ Command::Show { bundle, id } => agent::show(&bundle, &id)?,
+ Command::Add {
+ bundle,
+ what,
+ rest,
+ place,
+ flags,
+ } => {
+ let op = match (what.as_str(), rest.split_first()) {
+ ("layer", Some((kind, props))) if kind == "image" => Op::AddLayer {
+ layer: looks::image_layer(&bundle, props)?,
+ place: place.place(),
+ },
+ ("image", _) => Op::AddNode {
+ node: looks::image_node(&bundle, &rest)?,
+ place: place.place(),
+ },
+ _ => agent::add_op(&what, &rest, place.place())?,
+ };
+ agent::edit(&bundle, &[op], &output(&flags, place.frame.unwrap_or(0)))?;
+ }
+ Command::Set {
+ bundle,
+ id,
+ props,
+ frame,
+ flags,
+ } => {
+ let op = Op::Set {
+ id,
+ props: agent::parse_props(&props)?,
+ };
+ agent::edit(&bundle, &[op], &output(&flags, frame))?;
+ }
+ Command::Rm { bundle, ids, flags } => {
+ if ids.is_empty() {
+ return Err(anyhow!("give the ids to remove"));
+ }
+ agent::edit(&bundle, &[Op::Remove { ids }], &output(&flags, 0))?;
+ }
+ Command::Mv {
+ bundle,
+ id,
+ place,
+ flags,
+ } => {
+ let op = Op::Move {
+ id,
+ place: place.place(),
+ };
+ agent::edit(&bundle, &[op], &output(&flags, place.frame.unwrap_or(0)))?;
+ }
+ Command::Apply {
+ bundle,
+ file,
+ frame,
+ flags,
+ } => agent::apply(&bundle, file, &output(&flags, frame))?,
+ Command::Path {
+ bundle,
+ node,
+ move_to,
+ nudge,
+ handle,
+ insert,
+ add,
+ rm,
+ corner,
+ smooth,
+ simplify,
+ convert,
+ flags,
+ } => {
+ let edits = paths::Edits {
+ move_to,
+ nudge,
+ handle,
+ insert,
+ add,
+ rm,
+ corner,
+ smooth,
+ simplify,
+ convert,
+ };
+ paths::run(&bundle, &node, &edits, flags.json, &output(&flags, 0))?;
+ }
+ Command::Transform {
+ bundle,
+ ids,
+ offset,
+ rotate,
+ scale,
+ sx,
+ sy,
+ pivot,
+ flip,
+ frame,
+ flags,
+ } => {
+ if ids.is_empty() {
+ return Err(anyhow!("give the strokes and fills to transform (<cel>:s<id>)"));
+ }
+ let transform = mark_transform(offset, rotate, (scale, sx, sy), pivot, flip.as_deref())?
+ .ok_or_else(|| anyhow!("say how: --move, --rotate, --scale, --sx, --sy or --flip"))?;
+ agent::edit(
+ &bundle,
+ &[Op::Transform { ids, transform }],
+ &output(&flags.edit(), frame),
+ )?;
+ }
+ Command::Lasso {
+ bundle,
+ layer,
+ polygon,
+ cut,
+ offset,
+ rotate,
+ scale,
+ sx,
+ sy,
+ pivot,
+ flip,
+ rm,
+ frame,
+ flags,
+ } => {
+ let polygon = polygon.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>()?;
+ if polygon.len() < 3 {
+ return Err(anyhow!("--polygon needs at least 3 x,y points"));
+ }
+ let transform = mark_transform(offset, rotate, (scale, sx, sy), pivot, flip.as_deref())?;
+ let action = match (rm, transform) {
+ (true, Some(_)) => return Err(anyhow!("--rm deletes; leave out the move, turn, scale and flip")),
+ (true, None) => LassoAction::Remove,
+ (false, Some(t)) => LassoAction::Transform(t),
+ (false, None) => return marks::lassoed(&bundle, &layer, frame, &polygon, flags.json),
+ };
+ let op = Op::Lasso(LassoSpec {
+ layer,
+ frame,
+ polygon,
+ cut,
+ action,
+ });
+ agent::edit(&bundle, &[op], &output(&flags.edit(), frame))?;
+ }
+ Command::Render {
+ bundle,
+ out,
+ frame,
+ scale,
+ region,
+ focus,
+ overlay,
+ depth,
+ no_cache,
+ references,
+ onion,
+ onion_by,
+ onion_layers,
+ no_tint,
+ onion_loop,
+ sheet,
+ drawings,
+ cell,
+ columns,
+ track,
+ } => {
+ let defaults = klad_render::onion::Onion::default();
+ let (before, after) = onion.unwrap_or((defaults.before, defaults.after));
+ let by = match onion_by.as_deref() {
+ None | Some("drawings") => klad_render::onion::By::Drawings,
+ Some("frames") => klad_render::onion::By::Frames,
+ Some(other) => return Err(anyhow!("--onion-by takes drawings or frames, not {other:?}")),
+ };
+ let kinds = match (
+ &overlay,
+ onion.is_some() || onion_layers.is_some() || onion_loop.is_some(),
+ ) {
+ (Some(k), true) if !k.split(',').any(|k| k.trim() == "onion") => Some(format!("{k},onion")),
+ (None, true) => Some("onion".to_string()),
+ _ => overlay,
+ };
+ let kinds = match (kinds, track.is_empty()) {
+ (Some(k), false) if !k.split(',').any(|k| k.trim() == "arcs") => Some(format!("{k},arcs")),
+ (None, false) => Some("arcs".to_string()),
+ (k, _) => k,
+ };
+ let look = Look {
+ kinds,
+ focus,
+ depth,
+ onion: klad_render::onion::Onion {
+ before,
+ after,
+ by,
+ tint: !no_tint,
+ wrap: onion_loop,
+ ..defaults
+ },
+ onion_layers,
+ tracks: track,
+ references,
+ };
+ match sheet {
+ Some(spec) => {
+ if look.focus.is_some() || region.is_some() || scale.is_some() {
+ return Err(anyhow!(
+ "--sheet renders whole frames: use --cell for the size, not --focus, --region or --scale"
+ ));
+ }
+ let args = sheet::Sheet {
+ spec,
+ drawings,
+ cell,
+ columns,
+ };
+ sheet::render(&bundle, &args, &look, out)?
+ }
+ None => render(&bundle, out, frame, (scale, region), &look, !no_cache)?,
+ }
+ }
+ Command::Stroke {
+ bundle,
+ layer,
+ path,
+ points,
+ brush,
+ color,
+ size,
+ opacity,
+ flow,
+ pressure,
+ speed,
+ seed,
+ taper,
+ frame,
+ part,
+ second,
+ flags,
+ } => {
+ let taper = taper
+ .as_deref()
+ .map(|t| {
+ parse_numbers(t)?
+ .try_into()
+ .map_err(|_| anyhow!("--taper takes two lengths: in,out"))
+ })
+ .transpose()?;
+ let spec = StrokeSpec {
+ layer,
+ frame,
+ brush,
+ color,
+ size,
+ opacity,
+ flow,
+ path,
+ points: points.as_deref().map(parse_points).transpose()?,
+ pressure: pressure.as_deref().map(parse_numbers).transpose()?.unwrap_or_default(),
+ tilt: [0.0, 0.0],
+ speed,
+ seed,
+ taper,
+ part,
+ second,
+ };
+ agent::edit(&bundle, &[Op::Stroke(spec)], &output(&flags, frame))?;
+ }
+ Command::Fill {
+ bundle,
+ layer,
+ at,
+ polygon,
+ reference,
+ tolerance,
+ gap,
+ expand,
+ color,
+ opacity,
+ frame,
+ like,
+ frames,
+ shape,
+ part,
+ flags,
+ } => {
+ if let Some(shape) = shape {
+ let spec = FillSpec {
+ at: None,
+ shape: Some(shape),
+ expand,
+ color,
+ opacity,
+ frame,
+ part,
+ ..FillSpec::seeded(&layer_id(&bundle, &layer)?, [0.0, 0.0])
+ };
+ spec.check()?;
+ return agent::edit(&bundle, &[Op::Fill(spec)], &output(&flags, frame));
+ }
+ if like.is_some() {
+ let spec = FillSpec {
+ at: None,
+ like,
+ frames,
+ ..FillSpec::seeded(&layer, [0.0, 0.0])
+ };
+ spec.check()?;
+ return agent::edit(&bundle, &[Op::Fill(spec)], &output(&flags, frame));
+ }
+ let polygon = polygon
+ .as_deref()
+ .map(|p| p.split_whitespace().map(parse_pair).collect::<Result<Vec<_>>>())
+ .transpose()?;
+ let spec = FillSpec {
+ at,
+ polygon,
+ reference,
+ tolerance,
+ gap,
+ expand,
+ color,
+ opacity,
+ frame,
+ part,
+ ..FillSpec::seeded(&layer, [0.0, 0.0])
+ };
+ spec.check()?;
+ agent::edit(&bundle, &[Op::Fill(spec)], &output(&flags, frame))?;
+ }
+ Command::Ink {
+ bundle,
+ layer,
+ from,
+ path,
+ weight,
+ light,
+ break_deg,
+ gap,
+ wobble,
+ taper,
+ brush,
+ color,
+ seed,
+ frame,
+ part,
+ hand,
+ flags,
+ } => {
+ let spec = InkSpec {
+ layer: layer_id(&bundle, &layer)?,
+ from,
+ path,
+ frame,
+ weight,
+ light: light.unwrap_or([-1.0, -1.0]),
+ break_deg,
+ gap,
+ wobble,
+ taper,
+ brush,
+ color,
+ opacity: 1.0,
+ seed,
+ part,
+ hand,
+ };
+ agent::edit(&bundle, &[Op::Ink(spec)], &output(&flags, frame))?;
+ }
+ Command::Light {
+ bundle,
+ from,
+ light,
+ shade,
+ rim,
+ depth,
+ soft,
+ rim_width,
+ shade_color,
+ rim_color,
+ shade_opacity,
+ rim_opacity,
+ frame,
+ lamp,
+ flags,
+ } => {
+ let spec = LightSpec {
+ from,
+ frame,
+ light: light.unwrap_or([-1.0, -1.0]),
+ lamp: lamp
+ .as_deref()
+ .map(|l| -> Result<[f32; 3]> {
+ parse_numbers(l)?
+ .try_into()
+ .map_err(|_| anyhow!("--lamp {l:?} is not x,y,height"))
+ })
+ .transpose()?,
+ shade: shade.map(|l| layer_id(&bundle, &l)).transpose()?,
+ rim: rim.map(|l| layer_id(&bundle, &l)).transpose()?,
+ depth,
+ soft,
+ rim_width,
+ shade_color,
+ rim_color,
+ shade_opacity,
+ rim_opacity,
+ };
+ agent::edit(&bundle, &[Op::Light(spec)], &output(&flags, frame))?;
+ }
+ Command::Hatch {
+ bundle,
+ layer,
+ within,
+ polygon,
+ angle,
+ along,
+ spacing,
+ length,
+ jitter,
+ weight,
+ brush,
+ color,
+ opacity,
+ seed,
+ frame,
+ part,
+ hand,
+ flags,
+ } => {
+ let spec = HatchSpec {
+ layer: layer_id(&bundle, &layer)?,
+ frame,
+ within,
+ polygon: polygon_arg(polygon)?,
+ angle,
+ along,
+ spacing,
+ length,
+ jitter,
+ weight,
+ brush,
+ color,
+ opacity,
+ seed,
+ part,
+ hand,
+ };
+ agent::edit(&bundle, &[Op::Hatch(spec)], &output(&flags, frame))?;
+ }
+ Command::Paint {
+ bundle,
+ layer,
+ within,
+ polygon,
+ brush,
+ bold,
+ color,
+ form,
+ axis,
+ facing,
+ light,
+ elevation,
+ lamp,
+ key,
+ fill,
+ fill_strength,
+ bounce,
+ bounce_strength,
+ core,
+ angle,
+ weight,
+ decisive,
+ vary,
+ hand,
+ opacity,
+ seed,
+ frame,
+ part,
+ flags,
+ } => {
+ let triple = |text: &str, what: &str| -> Result<[f32; 3]> {
+ parse_numbers(text)?
+ .try_into()
+ .map_err(|_| anyhow!("{what} {text:?} is not x,y,z"))
+ };
+ let spec = PaintSpec {
+ layer: layer_id(&bundle, &layer)?,
+ frame,
+ within,
+ polygon: polygon_arg(polygon)?,
+ brush,
+ bold,
+ color,
+ form,
+ axis,
+ facing: triple(&facing, "--facing")?,
+ light,
+ elevation,
+ lamp: lamp.as_deref().map(|l| triple(l, "--lamp")).transpose()?,
+ key,
+ fill,
+ fill_strength,
+ bounce,
+ bounce_strength,
+ core,
+ angle,
+ weight,
+ decisive,
+ vary,
+ hand,
+ opacity,
+ seed,
+ part,
+ };
+ agent::edit(&bundle, &[Op::Paint(spec)], &output(&flags, frame))?;
+ }
+ Command::Prepare { bundle, from, to } => {
+ let bundle_ = Bundle::open(&bundle)?;
+ let last = bundle_.doc.timeline.frames.saturating_sub(1);
+ let (from, to) = (from.unwrap_or(0), to.unwrap_or(last).min(last));
+ let brushes = BrushSet::for_bundle(&bundle_)?;
+ let start = std::time::Instant::now();
+ let done = layers::prepare(&bundle_, &brushes, from, to)?;
+ println!(
+ "frames {from} to {to}: {} drawings, {} replayed, {} already buffered, {} ms",
+ done.replayed + done.updated + done.cached,
+ done.replayed + done.updated,
+ done.cached,
+ start.elapsed().as_millis()
+ );
+ }
+ Command::Scatter {
+ bundle,
+ layer,
+ within,
+ polygon,
+ avoid,
+ mark,
+ count,
+ spacing,
+ size,
+ turn,
+ weight,
+ brush,
+ color,
+ opacity,
+ seed,
+ frame,
+ part,
+ hand,
+ flags,
+ } => {
+ let spec = ScatterSpec {
+ layer: layer_id(&bundle, &layer)?,
+ frame,
+ within,
+ polygon: polygon_arg(polygon)?,
+ avoid,
+ mark,
+ count,
+ spacing,
+ size,
+ turn,
+ weight,
+ brush,
+ color,
+ opacity,
+ seed,
+ part,
+ hand,
+ };
+ agent::edit(&bundle, &[Op::Scatter(spec)], &output(&flags, frame))?;
+ }
+ Command::Gaps {
+ bundle,
+ layer,
+ frame,
+ sheet,
+ reference,
+ gap,
+ tolerance,
+ min,
+ render,
+ json,
+ } => {
+ let ask = colour::GapAsk {
+ layer,
+ frames: sheet.unwrap_or_else(|| {
+ let f = frame.unwrap_or(0);
+ format!("{f}-{f}")
+ }),
+ reference,
+ gap,
+ tolerance,
+ min,
+ };
+ let out = Output {
+ json,
+ render,
+ scale: None,
+ frame: frame.unwrap_or(0),
+ overlay: None,
+ };
+ colour::gaps(&bundle, &ask, &out)?;
+ }
+ Command::Refill {
+ bundle,
+ layer,
+ frame,
+ id,
+ flags,
+ } => fills::refill(&bundle, &layer, frame, id, &output(&flags, frame))?,
+ Command::Palette {
+ bundle,
+ add,
+ name,
+ rm,
+ flags,
+ } => {
+ let edit = match (add, rm) {
+ (Some(color), _) => Some(PaletteEdit::Add {
+ color,
+ name: name.unwrap_or_default(),
+ index: None,
+ }),
+ (_, Some(key)) => Some(PaletteEdit::Remove { key }),
+ _ => None,
+ };
+ match edit {
+ Some(edit) => agent::edit(&bundle, &[Op::Palette(edit)], &output(&flags, 0))?,
+ None => palette(&bundle, flags.json)?,
+ }
+ }
+ Command::Export {
+ bundle,
+ png: _,
+ layer,
+ frame,
+ scale,
+ depth,
+ background,
+ references,
+ sheet,
+ frames,
+ godot,
+ store,
+ padding,
+ max,
+ out,
+ } => {
+ let look = sprites::Look {
+ layer: layer.clone(),
+ scale,
+ depth,
+ background,
+ };
+ let packing = sprites::Packing { padding, max };
+ match (sheet, frames, godot) {
+ (Some(spec), _, _) => sprites::sheet(&bundle, &spec, &look, &packing, out)?,
+ (_, Some(spec), _) => sprites::frames(&bundle, &spec, &look, out)?,
+ (_, _, Some(dir)) => sprites::godot(&bundle, dir.or(out), store, &look, &packing)?,
+ _ => export::run(
+ &bundle,
+ export::Export {
+ layer,
+ frame,
+ scale,
+ depth,
+ background,
+ references,
+ out,
+ },
+ )?,
+ }
+ }
+ Command::Brushes {
+ bundle,
+ show,
+ json,
+ set,
+ picture,
+ } => match (bundle.as_deref(), set, picture) {
+ (Some(b), Some(set), _) => brushes::set(b, &set[0], Path::new(&set[1]))?,
+ (Some(b), None, Some(picture)) => brushes::picture(b, &picture[0], Path::new(&picture[1]))?,
+ (None, Some(_), _) | (None, None, Some(_)) => anyhow::bail!("--set and --picture need a bundle"),
+ (bundle, None, None) => brushes::list(bundle, show.as_deref(), json)?,
+ },
+ Command::Font { bundle, file } => looks::font(&bundle, file.as_deref())?,
+ Command::Atmosphere {
+ bundle,
+ props,
+ off,
+ flags,
+ } => looks::atmosphere(&bundle, &props, off, &output(&flags, 0))?,
+ Command::Effect {
+ bundle,
+ layer,
+ rest,
+ rm,
+ clear,
+ flags,
+ } => {
+ let change = match (rest.split_first(), rm, clear) {
+ (_, _, true) => looks::Change::Clear,
+ (_, Some(i), _) => looks::Change::Remove(i),
+ (Some((kind, props)), None, false) => looks::Change::Add(kind.clone(), props.to_vec()),
+ (None, None, false) => looks::Change::List,
+ };
+ looks::effect(&bundle, &layer, change, &output(&flags, 0))?;
+ }
+ Command::Reshape {
+ bundle,
+ stroke,
+ path,
+ flags,
+ } => {
+ let props: serde_json::Map<String, serde_json::Value> =
+ [("path".to_string(), serde_json::json!(path))].into_iter().collect();
+ agent::edit(&bundle, &[Op::Set { id: stroke, props }], &output(&flags, 0))?;
+ }
+ Command::Undo { bundle, flags } => history::walk(&bundle, Stack::Undo, &output(&flags, 0))?,
+ Command::Redo { bundle, flags } => history::walk(&bundle, Stack::Redo, &output(&flags, 0))?,
+ Command::Log { bundle, limit, json } => history::log(&bundle, limit, json)?,
+ Command::Selection { bundle, json } => history::selection(&bundle, json)?,
+ Command::Notes {
+ bundle,
+ done,
+ all,
+ json,
+ } => history::notes(&bundle, done, all, json)?,
+ Command::Diff {
+ bundle,
+ step,
+ frame,
+ scale,
+ } => history::diff(&bundle, step, frame, scale)?,
+ Command::Info { bundle } => info(&bundle)?,
+ Command::Strokes {
+ bundle,
+ layer,
+ frame,
+ after,
+ json,
+ } => strokes(&bundle, &layer, frame, after, json)?,
+ Command::Hash {
+ bundle,
+ frame,
+ all,
+ no_cache,
+ } => match all {
+ true => hash_all(&bundle, !no_cache)?,
+ false => hash(&bundle, frame, !no_cache)?,
+ },
+ Command::Demo {
+ bundle,
+ size,
+ seed,
+ force,
+ } => {
+ if force && bundle.join("doc.json").exists() {
+ std::fs::remove_dir_all(&bundle)?;
+ }
+ anyhow::ensure!(
+ !bundle.join("doc.json").exists(),
+ "{} exists, use --force",
+ bundle.display()
+ );
+ demo::write(&bundle, size, seed)?;
+ println!("{}", bundle.display());
+ }
+ Command::Stress {
+ bundle,
+ size,
+ layers,
+ strokes,
+ seed,
+ frames,
+ every,
+ } => {
+ edit::stress(&bundle, size, layers, strokes, seed, (frames, every))?;
+ println!("{}", bundle.display());
+ }
+ Command::Scribble {
+ bundle,
+ layer,
+ frame,
+ count,
+ seed,
+ size,
+ color,
+ } => edit::scribble(
+ &bundle,
+ edit::Scribble {
+ layer,
+ frame,
+ count,
+ seed,
+ size,
+ color,
+ },
+ )?,
+ Command::Watch { bundle, poll, seconds } => edit::watch(&bundle, poll, seconds)?,
+ Command::Licences => print!("{}\n{}", klad_core::notices::LICENSE, klad_core::notices::NOTICES),
+ Command::Bench { strokes, size, seed } => bench::run(strokes, size, seed)?,
+ #[cfg(target_os = "macos")]
+ Command::Open { bundle } => klad_app::run(bundle)?,
+ }
+ Ok(())
+}
+
+fn parse_onion_counts(text: &str) -> Result<(u32, u32), String> {
+ let (a, b) = text.split_once(',').ok_or("give before,after, for example 2,2")?;
+ Ok((
+ a.trim().parse().map_err(|e| format!("{e}"))?,
+ b.trim().parse().map_err(|e| format!("{e}"))?,
+ ))
+}
+
+fn parse_span(text: &str) -> Result<(u32, u32), String> {
+ let (a, b) = text.split_once('-').ok_or("give from-to, for example 0-7")?;
+ let span: (u32, u32) = (
+ a.trim().parse().map_err(|e| format!("{e}"))?,
+ b.trim().parse().map_err(|e| format!("{e}"))?,
+ );
+ match span.0 <= span.1 {
+ true => Ok(span),
+ false => Err("the loop must start before it ends".into()),
+ }
+}
+
+fn parse_mark_pair(text: &str) -> Result<[u32; 2]> {
+ let id = |v: &str| {
+ v.trim()
+ .trim_start_matches('s')
+ .parse::<u32>()
+ .map_err(|_| anyhow!("--pair takes s3=s7 (a mark of the first key = one of the second), not {text:?}"))
+ };
+ let (a, b) = text
+ .split_once('=')
+ .ok_or_else(|| anyhow!("--pair takes s3=s7, not {text:?}"))?;
+ Ok([id(a)?, id(b)?])
+}
+
+fn parse_frames_span(text: &str) -> Result<(u32, u32), String> {
+ let (a, b) = text.split_once('-').ok_or("give FROM-TO, for example 0-11")?;
+ Ok((
+ a.trim().parse().map_err(|e| format!("{e}"))?,
+ b.trim().parse().map_err(|e| format!("{e}"))?,
+ ))
+}
+
+fn parse_region(text: &str) -> Result<[i32; 4], String> {
+ let parts: Vec<i32> = text
+ .split(',')
+ .map(|p| p.trim().parse::<i32>().map_err(|e| e.to_string()))
+ .collect::<Result<_, _>>()?;
+ parts.try_into().map_err(|_| "region is x,y,w,h".to_string())
+}
+
+fn render(
+ path: &Path,
+ out: Option<PathBuf>,
+ frame: u32,
+ (scale, region): (Option<f32>, Option<[i32; 4]>),
+ look: &Look,
+ use_cache: bool,
+) -> Result<()> {
+ let start = Instant::now();
+ let bundle = Bundle::open(path)?;
+ let view = match &look.focus {
+ Some(id) => agent::focus_view(&bundle, id, frame, scale)?,
+ None => View {
+ scale: scale.unwrap_or(1.0),
+ region,
+ references: false,
+ },
+ };
+ let done = agent::render_look(&bundle, frame, view, look, out, use_cache)?;
+ println!("{}", done.path.display());
+ eprintln!(
+ "{}x{} hash {:016x} {} {:.0} ms",
+ done.frame.width,
+ done.frame.height,
+ done.frame.hash(),
+ done.note,
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+fn hash_all(path: &Path, use_cache: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let brushes = BrushSet::for_bundle(&bundle)?;
+ (0..bundle.doc.timeline.frames).try_for_each(|frame| {
+ let loaded = layers::load(&bundle, frame, &brushes, use_cache)?;
+ let image = compose(&bundle.doc, frame, &loaded.rasters, View::scaled(1.0))?;
+ println!("frame {frame:<4} {:016x}", image.hash());
+ Ok(())
+ })
+}
+
+fn hash(path: &Path, frame: u32, use_cache: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let loaded = layers::load(&bundle, frame, &BrushSet::for_bundle(&bundle)?, use_cache)?;
+ let image = compose(&bundle.doc, frame, &loaded.rasters, View::scaled(1.0))?;
+ println!("frame {:016x}", image.hash());
+ bundle.doc.paint_content_at(frame).iter().for_each(|(layer, cel)| {
+ if let Some(raster) = loaded.rasters.get(&cel.id) {
+ println!("{:<6} {:016x}", layer.id, raster.hash());
+ }
+ });
+ Ok(())
+}
+
+fn info(path: &Path) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ println!(
+ "{}x{} rev {} {} {} frames at {} fps",
+ doc.canvas.width, doc.canvas.height, doc.rev, doc.format, doc.timeline.frames, doc.timeline.fps
+ );
+ doc.all_layers()
+ .iter()
+ .filter(|l| l.kind() == Kind::Paint)
+ .try_for_each(|layer| {
+ layer.cels().iter().filter(|c| c.link.is_none()).try_for_each(|cel| {
+ let marks = bundle.read_marks(&layer.id, &cel.id)?;
+ let strokes: Vec<_> = strokes_of(&marks).collect();
+ let fills = marks.len() - strokes.len();
+ let bytes = std::fs::metadata(bundle.strokes_path(&layer.id, &cel.id)).map_or(0, |m| m.len());
+ let samples: usize = strokes.iter().map(|s| s.samples.len()).sum();
+ println!(
+ "{:<7} {:<7} {:<14} {} strokes, {fills} fills, {} samples, {} B on disk ({:.0} B per mark)",
+ layer.id,
+ cel.id,
+ layer.name,
+ strokes.len(),
+ samples,
+ bytes,
+ bytes as f64 / marks.len().max(1) as f64
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ })
+}
+
+fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let owner = bundle.doc.layer(layer).ok_or_else(|| anyhow!("no layer {layer}"))?;
+ let cel = owner
+ .content_at(frame)
+ .ok_or_else(|| anyhow!("layer {layer} has no cel at frame {frame}"))?;
+ let marks: Vec<_> = bundle
+ .read_marks(layer, &cel.id)?
+ .into_iter()
+ .filter(|m| m.id() > after)
+ .collect();
+ let strokes: Vec<_> = strokes_of(&marks).collect();
+ let fills: Vec<_> = fills_of(&marks).collect();
+ if as_json {
+ let list: Vec<serde_json::Value> = strokes.iter().map(|s| stroke_json(&cel.id, s, true)).collect();
+ let fills: Vec<serde_json::Value> = fills.iter().map(|f| fill_json(&cel.id, f)).collect();
+ println!(
+ "{}",
+ serde_json::json!({ "cel": cel.id, "strokes": list, "fills": fills, "order": marks.iter().map(|m| m.id()).collect::<Vec<_>>(), "parts": cel.parts })
+ );
+ return Ok(());
+ }
+ println!(
+ "cel {}: address a stroke or fill as {}:s<id>, for example {}:s{}",
+ cel.id,
+ cel.id,
+ cel.id,
+ marks.first().map_or(1, |m| m.id())
+ );
+ if !strokes.is_empty() {
+ println!("id author brush size samples ms Hz pressure tilt bounds");
+ }
+ strokes.iter().for_each(|s| {
+ let part = cel.part_of(s.id).map_or(String::new(), |p| format!(" part {p}"));
+ let ms: u32 = s.samples.iter().map(|v| v.dt_ms as u32).sum();
+ let hz = s.samples.len().saturating_sub(1) as f64 / (ms.max(1) as f64 / 1000.0);
+ let (lo, hi) = s.samples.iter().fold((f32::MAX, 0.0f32), |(lo, hi), v| {
+ (lo.min(v.pressure()), hi.max(v.pressure()))
+ });
+ let tilt = s
+ .samples
+ .iter()
+ .map(|v| v.tilt())
+ .fold(0.0f32, |m, (x, y)| m.max(x.abs()).max(y.abs()));
+ let [x0, y0, x1, y1] = s.bounds().unwrap_or_default();
+ println!(
+ "{:<6} {:<6} {:<7} {:>5.1} {:>8} {:>5} {:>5.0} {lo:.2}-{hi:.2} {tilt:>7.2} {x0:.0},{y0:.0} {:.0}x{:.0}{}{part}",
+ format!("s{}", s.id),
+ s.author.name(),
+ s.brush,
+ s.size,
+ s.samples.len(),
+ ms,
+ hz,
+ x1 - x0,
+ y1 - y0,
+ marks::flags(s.lock, &s.cuts)
+ );
+ });
+ if !fills.is_empty() {
+ println!("fills: id author colour source pixels bounds");
+ }
+ fills.iter().for_each(|f| {
+ let part = cel.part_of(f.id).map_or(String::new(), |p| format!(" part {p}"));
+ let source = match &f.source {
+ FillSource::Seed { seed, reference } => format!(
+ "at {:.0},{:.0} ref {} gap {} tol {}",
+ seed.x,
+ seed.y,
+ reference.name(),
+ seed.gap,
+ seed.tolerance
+ ),
+ FillSource::Polygon(points) => format!("polygon of {} points", points.len()),
+ };
+ let [x0, y0, x1, y1] = f.bounds().unwrap_or_default();
+ println!(
+ " {:<6} {:<6} {} {source:<35} {:>7} {x0:.0},{y0:.0} {:.0}x{:.0}{}{part}",
+ format!("s{}", f.id),
+ f.author.name(),
+ hex8(f.color()),
+ f.coverage.pixels(),
+ x1 - x0,
+ y1 - y0,
+ marks::flags(f.lock, &f.cuts)
+ );
+ });
+ let samples: usize = strokes.iter().map(|s| s.samples.len()).sum();
+ let packed = klad_core::stroke::encode_cel(&marks)?.len();
+ println!(
+ "{} strokes, {} fills, {samples} samples, {packed} B packed together ({:.0} B per mark)",
+ strokes.len(),
+ fills.len(),
+ packed as f64 / marks.len().max(1) as f64,
+ );
+ Ok(())
+}
+
+fn palette(path: &Path, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let palette = &bundle.doc.palette;
+ if as_json {
+ println!("{}", serde_json::to_string_pretty(palette)?);
+ return Ok(());
+ }
+ if palette.is_empty() {
+ println!("the palette is empty: klad palette <bundle> --add '#rrggbb' --name <name>");
+ }
+ palette
+ .iter()
+ .enumerate()
+ .for_each(|(i, s)| println!("{i:<3} {:<10} {}", s.color, s.name));
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ #[test]
+ fn every_command_parses_its_flags() {
+ std::thread::Builder::new()
+ .stack_size(64 << 20)
+ .spawn(flags_parse)
+ .unwrap()
+ .join()
+ .unwrap();
+ }
+
+ fn flags_parse() {
+ Cli::command().debug_assert();
+ let lasso = Cli::try_parse_from([
+ "draw",
+ "lasso",
+ "a.draw",
+ "l1",
+ "--polygon",
+ "0,0 9,0 9,9",
+ "--cut",
+ "--scale",
+ "2",
+ "--render",
+ ])
+ .unwrap();
+ assert!(matches!(
+ lasso.command,
+ Command::Lasso {
+ scale: Some(2.0),
+ cut: true,
+ ..
+ }
+ ));
+ }
+}
diff --git a/crates/cli/src/marks.rs b/crates/cli/src/marks.rs
new file mode 100644
index 0000000..700eac2
--- /dev/null
+++ b/crates/cli/src/marks.rs
@@ -0,0 +1,166 @@
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::Bundle;
+use klad_core::cut::{Cut, Keep};
+use klad_core::doc::Kind;
+use klad_core::fill::{Fill, FillSource};
+use klad_core::markedit::{Side, address, sides};
+use klad_core::stroke::{Mark, Stroke};
+use serde_json::{Value, json};
+use std::path::Path;
+
+pub fn hex8(rgba: [f32; 4]) -> String {
+ let [r, g, b, a] = rgba.map(|c| (c * 255.0).round() as u8);
+ format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
+}
+
+pub fn round4(v: f32) -> f64 {
+ (v as f64 * 1e4).round() / 1e4
+}
+
+pub fn fill_json(cel: &str, f: &Fill) -> Value {
+ let mut value = json!({
+ "id": f.id,
+ "address": address(cel, f.id),
+ "author": f.author.name(),
+ "color": hex8(f.color()),
+ "opacity": round4(f.opacity),
+ "bounds": f.bounds(),
+ "pixels": f.coverage.pixels(),
+ });
+ match &f.source {
+ FillSource::Seed { seed, reference } => {
+ value["at"] = json!([round4(seed.x), round4(seed.y)]);
+ value["ref"] = json!(reference.name());
+ value["tolerance"] = json!(round4(seed.tolerance));
+ value["gap"] = json!(round4(seed.gap));
+ value["expand"] = json!(round4(seed.expand));
+ }
+ FillSource::Polygon(points) => value["polygon"] = json!(points),
+ }
+ flags_json(&mut value, f.lock, &f.cuts);
+ value
+}
+
+pub fn flags(lock: bool, cuts: &[Cut]) -> String {
+ let lock = lock.then_some("lock alpha".to_string());
+ let cuts = cuts.iter().map(|c| {
+ format!(
+ "keeps {} a lasso",
+ if c.keep == Keep::Inside { "inside" } else { "outside" }
+ )
+ });
+ let all: Vec<String> = lock.into_iter().chain(cuts).collect();
+ if all.is_empty() {
+ String::new()
+ } else {
+ format!(" ({})", all.join(", "))
+ }
+}
+
+fn flags_json(value: &mut Value, lock: bool, cuts: &[Cut]) {
+ if lock {
+ value["lockAlpha"] = json!(true);
+ }
+ if !cuts.is_empty() {
+ value["cuts"] = Value::Array(
+ cuts.iter()
+ .map(|c| {
+ json!({
+ "keep": if c.keep == Keep::Inside { "inside" } else { "outside" },
+ "polygon": c.polygon,
+ })
+ })
+ .collect(),
+ );
+ }
+}
+
+pub fn lassoed(path: &Path, layer: &str, frame: u32, polygon: &[[f32; 2]], as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let owner = bundle.doc.find_layer(layer)?;
+ if owner.kind() != Kind::Paint {
+ bail!(
+ "{layer} is a {} layer; the lasso works on paint layers",
+ owner.kind().name()
+ );
+ }
+ let cel = owner
+ .content_at(frame)
+ .ok_or_else(|| anyhow!("layer {layer} has no cel at frame {frame}"))?
+ .id
+ .clone();
+ let marks = bundle.read_marks(&owner.id, &cel)?;
+ let found = sides(&marks, polygon);
+ let pick = |side: Side| -> Vec<String> {
+ found
+ .iter()
+ .filter(|(_, s)| *s == side)
+ .map(|(id, _)| address(&cel, *id))
+ .collect()
+ };
+ let (inside, crossing) = (pick(Side::Inside), pick(Side::Crossing));
+ if as_json {
+ println!("{}", json!({ "cel": cel, "inside": inside, "crossing": crossing }));
+ return Ok(());
+ }
+ println!("inside ({}): {}", inside.len(), inside.join(" "));
+ println!("crossing the edge ({}): {}", crossing.len(), crossing.join(" "));
+ println!("move them with --move, --rotate, --scale or --flip (add --cut to take the crossing parts), or --rm");
+ Ok(())
+}
+
+pub fn stroke_json(cel: &str, s: &Stroke, points: bool) -> Value {
+ let mut value = json!({
+ "id": s.id,
+ "address": address(cel, s.id),
+ "author": s.author.name(),
+ "brush": s.brush,
+ "color": hex8(s.color()),
+ "size": s.size,
+ "opacity": s.opacity,
+ "flow": s.flow,
+ "taper": s.taper,
+ "bounds": s.bounds(),
+ });
+ flags_json(&mut value, s.lock, &s.cuts);
+ if let Some(second) = s.second_color() {
+ value["second"] = json!(hex8(second));
+ }
+ if points {
+ value["points"] = json!(
+ s.samples
+ .iter()
+ .map(|v| {
+ let (x, y) = v.pos();
+ [x, y, v.pressure()]
+ })
+ .collect::<Vec<_>>()
+ );
+ let line: Vec<[f32; 2]> = s
+ .samples
+ .iter()
+ .map(|v| {
+ let (x, y) = v.pos();
+ [x, y]
+ })
+ .collect();
+ let fitted = klad_core::pathedit::fit_polyline(&line, (s.size * 0.12).clamp(1.0, 6.0));
+ value["path"] = json!(klad_core::pathedit::to_d(&[fitted]));
+ }
+ value
+}
+
+pub fn mark_json(cel: &str, mark: &Mark) -> Value {
+ match mark {
+ Mark::Stroke(s) => {
+ let mut value = stroke_json(cel, s, true);
+ value["kind"] = json!("stroke");
+ value
+ }
+ Mark::Fill(f) => {
+ let mut value = fill_json(cel, f);
+ value["kind"] = json!("fill");
+ value
+ }
+ }
+}
diff --git a/crates/cli/src/paths.rs b/crates/cli/src/paths.rs
new file mode 100644
index 0000000..469377a
--- /dev/null
+++ b/crates/cli/src/paths.rs
@@ -0,0 +1,215 @@
+use crate::agent::{self, Output};
+use anyhow::{Result, anyhow, bail};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Item, Shape};
+use klad_core::ops::Op;
+use klad_core::pathedit::{self, Anchor, PathEdit, Side};
+use serde_json::{Value, json};
+use std::path::Path;
+
+pub struct Edits {
+ pub move_to: Option<Vec<String>>,
+ pub nudge: Option<Vec<String>>,
+ pub handle: Option<Vec<String>>,
+ pub insert: Option<String>,
+ pub add: Option<[f32; 2]>,
+ pub rm: Option<String>,
+ pub corner: Option<String>,
+ pub smooth: Option<String>,
+ pub simplify: Option<f32>,
+ pub convert: bool,
+}
+
+fn numbers(text: &str) -> Result<Vec<usize>> {
+ text.split(',')
+ .map(|v| {
+ v.trim()
+ .parse::<usize>()
+ .map_err(|_| anyhow!("{v:?} is not a point number"))
+ })
+ .collect()
+}
+
+fn pair(text: &str) -> Result<[f32; 2]> {
+ let v: Vec<f32> = text
+ .split(',')
+ .map(|v| v.trim().parse::<f32>().map_err(|_| anyhow!("{text:?} is not x,y")))
+ .collect::<Result<_>>()?;
+ v.try_into().map_err(|_| anyhow!("{text:?} is not x,y"))
+}
+
+fn single(text: &str) -> Result<usize> {
+ match numbers(text)?[..] {
+ [one] => Ok(one),
+ _ => bail!("{text:?}: give one point number"),
+ }
+}
+
+pub fn edits(e: &Edits) -> Result<Vec<PathEdit>> {
+ let mut out = Vec::new();
+ if e.convert {
+ out.push(PathEdit::Convert);
+ }
+ if let Some(tolerance) = e.simplify {
+ out.push(PathEdit::Simplify { tolerance });
+ }
+ if let Some(v) = &e.move_to {
+ out.push(PathEdit::MoveTo {
+ point: single(&v[0])?,
+ to: pair(&v[1])?,
+ });
+ }
+ if let Some(v) = &e.nudge {
+ out.push(PathEdit::Move {
+ points: numbers(&v[0])?,
+ by: pair(&v[1])?,
+ });
+ }
+ if let Some(v) = &e.handle {
+ let side = match v[1].as_str() {
+ "in" => Side::In,
+ "out" => Side::Out,
+ other => bail!("--handle takes in or out, not {other:?}"),
+ };
+ out.push(PathEdit::Handle {
+ point: single(&v[0])?,
+ side,
+ to: pair(&v[2])?,
+ free: false,
+ });
+ }
+ if let Some(text) = &e.insert {
+ let (segment, t) = match text.split_once(',') {
+ Some((s, t)) => (
+ single(s)?,
+ t.trim().parse::<f32>().map_err(|_| anyhow!("{t:?} is not a number"))?,
+ ),
+ None => (single(text)?, 0.5),
+ };
+ out.push(PathEdit::Insert { segment, t });
+ }
+ if let Some(at) = e.add {
+ out.push(PathEdit::Add { at });
+ }
+ if let Some(text) = &e.corner {
+ out.push(PathEdit::Corner { points: numbers(text)? });
+ }
+ if let Some(text) = &e.smooth {
+ out.push(PathEdit::Smooth { points: numbers(text)? });
+ }
+ if let Some(text) = &e.rm {
+ out.push(PathEdit::Remove { points: numbers(text)? });
+ }
+ Ok(out)
+}
+
+fn fmt(p: [f32; 2]) -> String {
+ format!("{:.2},{:.2}", p[0], p[1])
+ .replace(".00,", ",")
+ .trim_end_matches(".00")
+ .to_string()
+}
+
+fn point_json(i: usize, a: &Anchor) -> Value {
+ json!({
+ "i": i,
+ "at": a.at,
+ "in": a.has_in().then_some(a.inn),
+ "out": a.has_out().then_some(a.out),
+ "smooth": a.smooth(),
+ })
+}
+
+pub fn list(path: &Path, id: &str, as_json: bool) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let Some(Item::Node(layer, _, node)) = bundle.doc.item(id) else {
+ bail!("{id} is not a shape");
+ };
+ let subs = pathedit::from_shape(&node.shape)?;
+ let converted = !matches!(node.shape, Shape::Path { .. });
+ if as_json {
+ let mut i = 0;
+ let value = json!({
+ "id": node.id,
+ "type": node.type_name(),
+ "layer": layer.id,
+ "transform": node.transform,
+ "subpaths": subs.iter().map(|s| {
+ let points: Vec<Value> = s.anchors.iter().map(|a| { i += 1; point_json(i - 1, a) }).collect();
+ json!({ "closed": s.closed, "points": points })
+ }).collect::<Vec<_>>(),
+ });
+ println!("{}", serde_json::to_string_pretty(&value)?);
+ return Ok(());
+ }
+ let total: usize = subs.iter().map(|s| s.anchors.len()).sum();
+ println!(
+ "{} {}{} in layer {} ({}): {} subpath{}, {total} points",
+ node.type_name(),
+ node.id,
+ if node.name.is_empty() {
+ String::new()
+ } else {
+ format!(" \"{}\"", node.name)
+ },
+ layer.id,
+ layer.name,
+ subs.len(),
+ if subs.len() == 1 { "" } else { "s" }
+ );
+ if converted {
+ println!(
+ "any point edit turns this {} into a path with these points",
+ node.type_name()
+ );
+ }
+ if !node.transform.is_identity() {
+ println!("coordinates are the shape's own, before its transform");
+ }
+ let mut i = 0;
+ subs.iter().enumerate().for_each(|(k, s)| {
+ if subs.len() > 1 {
+ println!("subpath {k}{}", if s.closed { ", closed" } else { "" });
+ } else if s.closed {
+ println!("closed");
+ }
+ s.anchors.iter().for_each(|a| {
+ let kind = if a.smooth() {
+ "smooth"
+ } else if a.has_in() || a.has_out() {
+ "curve"
+ } else {
+ "corner"
+ };
+ let handles = [
+ a.has_in().then(|| format!("in {}", fmt(a.inn))),
+ a.has_out().then(|| format!("out {}", fmt(a.out))),
+ ]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" ");
+ println!("{i:>5} {kind:<6} {:<18} {handles}", fmt(a.at));
+ i += 1;
+ });
+ });
+ Ok(())
+}
+
+pub fn run(path: &Path, id: &str, e: &Edits, as_json: bool, out: &Output) -> Result<()> {
+ let ops: Vec<Op> = edits(e)?
+ .into_iter()
+ .map(|edit| Op::Path {
+ id: id.to_string(),
+ edit,
+ })
+ .collect();
+ if ops.is_empty() {
+ return list(path, id, as_json);
+ }
+ agent::edit(path, &ops, out)?;
+ if !out.json {
+ list(path, id, false)?;
+ }
+ Ok(())
+}
diff --git a/crates/cli/src/shapes.rs b/crates/cli/src/shapes.rs
new file mode 100644
index 0000000..1774ee6
--- /dev/null
+++ b/crates/cli/src/shapes.rs
@@ -0,0 +1,525 @@
+use anyhow::{Context, Result, bail};
+use klad_core::bundle::Bundle;
+use klad_core::color;
+use klad_core::doc::Document;
+use klad_core::ops::{FillSpec, HatchSpec, InkSpec, LightSpec, Op, PaintSpec, ScatterSpec, StrokeSpec, apply_all};
+use klad_render::form::{self, Form, FormRules, Lighting};
+use klad_render::shapes::{self, HatchRules, InkRules, Outline, P, Run, ScatterRules};
+use serde_json::json;
+
+#[allow(clippy::too_many_arguments)]
+fn stroke(
+ layer: &str,
+ frame: u32,
+ brush: &str,
+ color: &str,
+ size: f32,
+ opacity: f32,
+ taper: Option<[f32; 2]>,
+ seed: u32,
+ run: &Run,
+ part: &Option<String>,
+) -> Result<Op> {
+ let mut value = json!({
+ "layer": layer,
+ "frame": frame,
+ "brush": brush,
+ "color": color,
+ "size": size,
+ "opacity": opacity,
+ "points": run,
+ "seed": seed,
+ });
+ if let Some(taper) = taper {
+ value["taper"] = json!(taper);
+ }
+ if let Some(part) = part {
+ value["part"] = json!(part);
+ }
+ let spec: StrokeSpec = serde_json::from_value(value)?;
+ Ok(Op::Stroke(spec))
+}
+
+fn handed(run: &Run, taper: Option<[f32; 2]>, seed: u32, strength: f32, bow: bool) -> (Run, f32, Option<[f32; 2]>) {
+ let mut rng = klad_core::rng::Rng::new(seed as u64 * 2_654_435_761 + 101);
+ let h = shapes::hand(run, &mut rng, strength, bow);
+ let taper = match (taper, strength > 0.0) {
+ (Some([a, b]), true) if a == 0.0 && b == 0.0 => Some(h.taper),
+ (None, true) => Some(h.taper),
+ (given, _) => given,
+ };
+ (h.run, h.width, taper)
+}
+
+fn closed(outlines: &[Outline]) -> Vec<Vec<P>> {
+ outlines
+ .iter()
+ .filter(|o| o.closed && o.points.len() >= 3)
+ .map(|o| o.points.clone())
+ .collect()
+}
+
+fn areas(doc: &Document, within: &[String], polygon: &Option<Vec<[f32; 2]>>, what: &str) -> Result<Vec<Vec<P>>> {
+ let mut found = closed(&shapes::outlines(doc, within)?);
+ found.extend(polygon.clone().filter(|p| p.len() >= 3));
+ if found.is_empty() {
+ bail!("{what} needs \"in\": closed shapes (rects, ellipses, closed paths, groups of them) or \"polygon\"");
+ }
+ Ok(found)
+}
+
+fn ink(doc: &Document, spec: &InkSpec) -> Result<Vec<Op>> {
+ let outlines = match (&spec.path, spec.from.is_empty()) {
+ (Some(d), _) => shapes::path_outlines(d)?,
+ (None, false) => shapes::outlines(doc, &spec.from)?,
+ (None, true) => bail!("ink needs \"from\": the ids of vector shapes, or \"path\": SVG path data"),
+ };
+ let rules = InkRules {
+ weight: spec.weight,
+ light: spec.light,
+ break_deg: spec.break_deg,
+ gap: spec.gap,
+ wobble: spec.wobble,
+ seed: spec.seed,
+ };
+ shapes::ink(&outlines, &rules)
+ .iter()
+ .enumerate()
+ .map(|(i, run)| {
+ let seed = spec.seed.wrapping_mul(1009).wrapping_add(i as u32);
+ let (run, width, taper) = handed(run, spec.taper, seed, spec.hand, false);
+ stroke(
+ &spec.layer,
+ spec.frame,
+ &spec.brush,
+ &spec.color,
+ spec.weight * width,
+ spec.opacity,
+ taper,
+ seed,
+ &run,
+ &spec.part,
+ )
+ })
+ .collect()
+}
+
+fn fill(polygon: Vec<P>, outside: Option<Vec<P>>, base: &FillSpec, opacity: f32) -> Op {
+ Op::Fill(FillSpec {
+ at: None,
+ polygon: Some(polygon),
+ shape: None,
+ outside,
+ opacity,
+ ..base.clone()
+ })
+}
+
+fn light(doc: &Document, spec: &LightSpec) -> Result<Vec<Op>> {
+ if spec.shade.is_none() && spec.rim.is_none() {
+ bail!("light needs \"shade\": a layer for the shade, \"rim\": a layer for the rim light, or both");
+ }
+ let outlines = shapes::outlines(doc, &spec.from)?;
+ if closed(&outlines).is_empty() {
+ bail!("light needs closed shapes in \"from\"");
+ }
+ let base = |layer: &str, color: &str| FillSpec {
+ frame: spec.frame,
+ color: color.to_string(),
+ ..FillSpec::seeded(layer, [0.0, 0.0])
+ };
+ let groups: Vec<(Vec<Outline>, P)> = match spec.lamp {
+ None => vec![(outlines.clone(), spec.light)],
+ Some(at) => outlines
+ .iter()
+ .filter(|o| o.closed && o.points.len() >= 3)
+ .map(|o| {
+ let n = o.points.len() as f32;
+ let c = o
+ .points
+ .iter()
+ .fold([0.0, 0.0], |a, p| [a[0] + p[0] / n, a[1] + p[1] / n]);
+ (vec![o.clone()], [at[0] - c[0], at[1] - c[1]])
+ })
+ .collect(),
+ };
+ let shade: Vec<Op> = spec
+ .shade
+ .iter()
+ .flat_map(|layer| {
+ let base = base(layer, &spec.shade_color);
+ groups
+ .iter()
+ .flat_map(|(group, light)| shapes::shade(group, *light, spec.depth, spec.soft as usize))
+ .map(|c| fill(c.polygon, Some(c.outside), &base, spec.shade_opacity * c.share))
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ let rim: Vec<Op> = spec
+ .rim
+ .iter()
+ .flat_map(|layer| {
+ let base = base(layer, &spec.rim_color);
+ groups
+ .iter()
+ .flat_map(|(group, light)| shapes::rim(group, *light, spec.rim_width))
+ .map(|c| fill(c.polygon, Some(c.outside), &base, spec.rim_opacity))
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ Ok(shade.into_iter().chain(rim).collect())
+}
+
+fn shape_fill(doc: &Document, spec: &FillSpec, id: &str) -> Result<Vec<Op>> {
+ let rings = closed(&shapes::outlines(doc, &[id.to_string()])?);
+ if rings.is_empty() {
+ bail!("{id} has no closed outline to fill");
+ }
+ Ok(rings
+ .into_iter()
+ .map(|ring| {
+ fill(
+ shapes::offset(&ring, spec.expand),
+ spec.outside.clone(),
+ spec,
+ spec.opacity,
+ )
+ })
+ .collect())
+}
+
+fn hatch(doc: &Document, spec: &HatchSpec) -> Result<Vec<Op>> {
+ let found = areas(doc, &spec.within, &spec.polygon, "hatch")?;
+ let rules = HatchRules {
+ angle: spec.angle,
+ along: spec.along,
+ spacing: spec.spacing.max(1.0),
+ length: (spec.length[0], spec.length[1]),
+ jitter: spec.jitter,
+ gap: shapes::HATCH_GAP,
+ seed: spec.seed,
+ };
+ shapes::hatch(&found, &rules)
+ .iter()
+ .enumerate()
+ .map(|(i, run)| {
+ let seed = spec.seed.wrapping_mul(7919).wrapping_add(i as u32);
+ let (run, width, taper) = handed(run, Some([0.0, 0.0]), seed, spec.hand, true);
+ stroke(
+ &spec.layer,
+ spec.frame,
+ &spec.brush,
+ &spec.color,
+ spec.weight * width,
+ spec.opacity,
+ taper,
+ seed,
+ &run,
+ &spec.part,
+ )
+ })
+ .collect()
+}
+
+fn linear(hex: &str) -> Result<[f32; 3]> {
+ Ok(color::to_linear(color::parse_hex(hex)?))
+}
+
+fn form_rules(doc: &Document, spec: &PaintSpec) -> Result<FormRules> {
+ let form = match spec.form.as_str() {
+ "round" => Form::Round,
+ "flat" => Form::Flat { facing: spec.facing },
+ "cylinder" => Form::Cylinder { axis: spec.axis },
+ other => bail!("paint forms are round, flat and cylinder, not {other:?}"),
+ };
+ let light = match spec.lamp {
+ Some(at) => Lighting::Lamp { at },
+ None => Lighting::Direction {
+ toward: [spec.light[0], spec.light[1], spec.elevation],
+ },
+ };
+ let scaled = |hex: &str, k: f32| -> Result<[f32; 3]> { Ok(linear(hex)?.map(|c| c * k)) };
+ Ok(FormRules {
+ form,
+ light,
+ colour: linear(&spec.color)?,
+ key: linear(&spec.key)?,
+ fill: scaled(&spec.fill, spec.fill_strength)?,
+ bounce: scaled(&spec.bounce, spec.bounce_strength)?,
+ core: spec.core,
+ weight: spec.weight,
+ angle: spec.angle,
+ decisive: spec.decisive,
+ vary: spec.vary,
+ seed: spec.seed,
+ spill: doc.layer(&spec.layer).is_some_and(|l| l.clip || l.lock_alpha),
+ })
+}
+
+fn paint(doc: &Document, spec: &PaintSpec) -> Result<Vec<Op>> {
+ let found = areas(doc, &spec.within, &spec.polygon, "paint")?;
+ let rules = form_rules(doc, spec)?;
+ let bow = matches!(rules.form, Form::Flat { .. });
+ form::paint_form(&found, &rules)
+ .iter()
+ .enumerate()
+ .map(|(i, s)| {
+ let seed = spec.seed.wrapping_mul(15_485_863).wrapping_add(i as u32);
+ let (run, width, taper) = handed(&s.run, Some([0.0, 0.0]), seed, spec.hand * s.hand, bow);
+ stroke(
+ &spec.layer,
+ spec.frame,
+ if s.bold { &spec.bold } else { &spec.brush },
+ &color::to_hex(color::from_linear(s.rgb, 1.0)),
+ s.size * width,
+ spec.opacity * s.opacity,
+ taper,
+ seed,
+ &run,
+ &spec.part,
+ )
+ })
+ .collect()
+}
+
+fn scatter(doc: &Document, spec: &ScatterSpec) -> Result<Vec<Op>> {
+ let found = areas(doc, &spec.within, &spec.polygon, "scatter")?;
+ let avoid = closed(&shapes::outlines(doc, &spec.avoid)?);
+ let mark = shapes::mark_lines(&spec.mark).with_context(|| format!("the mark {:?}", spec.mark))?;
+ let rules = ScatterRules {
+ count: spec.count,
+ spacing: spec.spacing,
+ size: (spec.size[0], spec.size[1]),
+ turn: (spec.turn[0], spec.turn[1]),
+ seed: spec.seed,
+ };
+ shapes::scatter(&found, &avoid, &mark, &rules)
+ .iter()
+ .enumerate()
+ .map(|(i, run)| {
+ let seed = spec.seed.wrapping_mul(104_729).wrapping_add(i as u32);
+ let (run, width, taper) = handed(run, Some([0.0, 0.0]), seed, spec.hand, false);
+ stroke(
+ &spec.layer,
+ spec.frame,
+ &spec.brush,
+ &spec.color,
+ spec.weight * width,
+ spec.opacity,
+ taper,
+ seed,
+ &run,
+ &spec.part,
+ )
+ })
+ .collect()
+}
+
+fn shapes_change(op: &Op) -> bool {
+ matches!(
+ op,
+ Op::AddLayer { .. }
+ | Op::AddNode { .. }
+ | Op::Set { .. }
+ | Op::Remove { .. }
+ | Op::Move { .. }
+ | Op::Path { .. }
+ )
+}
+
+pub fn expand(bundle: &Bundle, ops: Vec<Op>) -> Result<Vec<Op>> {
+ let mut doc = bundle.doc.clone();
+ let mut out = Vec::new();
+ ops.into_iter().enumerate().try_for_each(|(i, op)| {
+ let made = match &op {
+ Op::Ink(spec) => Some(ink(&doc, spec)),
+ Op::Light(spec) => Some(light(&doc, spec)),
+ Op::Hatch(spec) => Some(hatch(&doc, spec)),
+ Op::Paint(spec) => Some(paint(&doc, spec)),
+ Op::Scatter(spec) => Some(scatter(&doc, spec)),
+ Op::Fill(spec) => spec.shape.as_ref().map(|id| shape_fill(&doc, spec, id)),
+ _ => None,
+ };
+ match made {
+ Some(made) => {
+ let made = made.with_context(|| format!("op {}", i + 1))?;
+ if made.is_empty() {
+ bail!("op {}: nothing to draw", i + 1);
+ }
+ out.extend(made);
+ }
+ None => {
+ if shapes_change(&op)
+ && let Ok((next, _)) = apply_all(&doc, std::slice::from_ref(&op))
+ {
+ doc = next;
+ }
+ out.push(op);
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Layer;
+ use klad_core::ops::parse_lines;
+ use klad_core::stroke::Mark;
+
+ fn bundle(name: &str) -> (std::path::PathBuf, Bundle) {
+ let dir = std::env::temp_dir().join(format!("draw-shapes-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(400, 300);
+ doc.layers.push(Layer::paint("l1", "flats", "c1"));
+ doc.layers.push(Layer::paint("l2", "shade", "c2"));
+ doc.layers.push(Layer::paint("l3", "lines", "c3"));
+ doc.layers.push(Layer::vector("l4", "sketch", "c4", Vec::new()));
+ doc.next_id = 20;
+ (dir.clone(), Bundle::create(&dir, doc).unwrap())
+ }
+
+ #[test]
+ fn shapes_added_in_a_batch_are_inked_filled_lit_and_textured_in_the_same_batch() {
+ let (dir, mut b) = bundle("batch");
+ let ops = parse_lines(
+ r##"{"op":"add","node":{"id":"body","type":"ellipse","cx":200,"cy":150,"rx":90,"ry":70},"in":"l4","frame":0}
+{"op":"add","node":{"id":"eye","type":"ellipse","cx":230,"cy":130,"rx":12,"ry":12},"in":"l4","frame":0}
+{"op":"ink","layer":"l3","from":["body","eye"],"weight":5}
+{"op":"fill","layer":"l1","shape":"body","color":"#7fa060"}
+{"op":"light","from":["body"],"shade":"l2","light":[-1,-1]}
+{"op":"hatch","layer":"l2","in":["body"],"spacing":9}
+{"op":"scatter","layer":"l1","in":["body"],"avoid":["eye"],"count":12}"##,
+ )
+ .unwrap();
+ let ops = expand(&b, ops).unwrap();
+ let strokes = ops.iter().filter(|o| matches!(o, Op::Stroke(_))).count();
+ let fills = ops.iter().filter(|o| matches!(o, Op::Fill(_))).count();
+ assert!(strokes > 20, "{strokes} strokes");
+ assert_eq!(fills, 1 + 3);
+ let mut ops = ops;
+ crate::agent::resolve_strokes(&b, &mut ops).unwrap();
+ crate::fills::resolve(&b, &mut ops).unwrap();
+ b.apply(&ops).unwrap();
+ let lines = b.read_marks("l3", "c3").unwrap();
+ assert!(lines.iter().filter(|m| matches!(m, Mark::Stroke(_))).count() >= 2);
+ let shade = b.read_marks("l2", "c2").unwrap();
+ assert!(shade.iter().any(|m| m.as_fill().is_some_and(|f| !f.cuts.is_empty())));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_lamp_shades_each_shape_on_the_side_away_from_it() {
+ let (dir, b) = bundle("lamp");
+ let ops = parse_lines(
+ r##"{"op":"add","node":{"id":"near","type":"ellipse","cx":100,"cy":100,"rx":40,"ry":40},"in":"l4","frame":0}
+{"op":"add","node":{"id":"far","type":"ellipse","cx":300,"cy":100,"rx":40,"ry":40},"in":"l4","frame":0}
+{"op":"light","from":["near","far"],"lamp":[200,100,40],"shade":"l2","depth":20}"##,
+ )
+ .unwrap();
+ let fills: Vec<Vec<[f32; 2]>> = expand(&b, ops)
+ .unwrap()
+ .into_iter()
+ .filter_map(|o| match o {
+ Op::Fill(f) => f.polygon,
+ _ => None,
+ })
+ .collect();
+ let middle = |p: &Vec<[f32; 2]>| p.iter().map(|q| q[0]).sum::<f32>() / p.len() as f32;
+ assert!(fills.iter().any(|p| middle(p) < 100.0 && middle(p) > 40.0));
+ assert!(fills.iter().any(|p| middle(p) > 300.0));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn ink_and_hatch_strokes_are_drawn_by_hand_unless_hand_is_zero() {
+ let (dir, b) = bundle("hand");
+ let run = |hand: f32| -> Vec<StrokeSpec> {
+ let text = format!(
+ r##"{{"op":"add","node":{{"id":"box","type":"rect","x":0,"y":0,"w":120,"h":120}},"in":"l4","frame":0}}
+{{"op":"hatch","layer":"l2","in":["box"],"spacing":12,"hand":{hand}}}"##
+ );
+ expand(&b, parse_lines(&text).unwrap())
+ .unwrap()
+ .into_iter()
+ .filter_map(|o| match o {
+ Op::Stroke(s) => Some(s),
+ _ => None,
+ })
+ .collect()
+ };
+ let (handed, even) = (run(1.0), run(0.0));
+ assert!(handed.iter().any(|s| s.size != handed[0].size));
+ assert!(even.iter().all(|s| s.size == even[0].size));
+ assert!(handed.iter().all(|s| s.taper.is_some_and(|t| t[1] > 0.0)));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn paint_paints_a_form_with_tones_from_the_light_and_strokes_drawn_by_hand() {
+ let (dir, b) = bundle("paint");
+ let ops = parse_lines(
+ r##"{"op":"add","node":{"id":"rock","type":"ellipse","cx":200,"cy":150,"rx":120,"ry":90},"in":"l4","frame":0}
+{"op":"paint","layer":"l2","in":["rock"],"color":"#6b7380","weight":10,"light":[-1,-1]}"##,
+ )
+ .unwrap();
+ let ops = expand(&b, ops).unwrap();
+ let strokes: Vec<&StrokeSpec> = ops
+ .iter()
+ .filter_map(|o| match o {
+ Op::Stroke(s) => Some(s),
+ _ => None,
+ })
+ .collect();
+ let tones: std::collections::BTreeSet<&str> = strokes.iter().map(|s| s.color.as_str()).collect();
+ assert!(tones.len() > 30, "{}", tones.len());
+ assert!(strokes.iter().all(|s| s.layer == "l2"));
+ assert!(strokes.iter().any(|s| s.brush == "oil") && strokes.iter().any(|s| s.brush == "oil-load"));
+ let sizes: Vec<f32> = strokes.iter().map(|s| s.size).collect();
+ assert!(sizes.iter().cloned().fold(0.0f32, f32::max) > sizes.iter().cloned().fold(f32::MAX, f32::min) * 3.0);
+ let lamp = expand(
+ &b,
+ parse_lines(
+ r##"{"op":"add","node":{"id":"rock","type":"rect","x":0,"y":0,"w":90,"h":90},"in":"l4","frame":0}
+{"op":"paint","layer":"l2","in":["rock"],"form":"flat","lamp":[-40,40,60]}"##,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ assert!(lamp.iter().filter(|o| matches!(o, Op::Stroke(_))).count() > 10);
+ let refused = format!(
+ "{:#}",
+ expand(
+ &b,
+ parse_lines(
+ r#"{"op":"add","node":{"id":"rock","type":"rect","x":0,"y":0,"w":90,"h":90},"in":"l4","frame":0}
+{"op":"paint","layer":"l2","in":["rock"],"form":"blob"}"#
+ )
+ .unwrap()
+ )
+ .unwrap_err()
+ );
+ assert!(refused.contains("round, flat and cylinder"), "{refused}");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn unexpanded_and_empty_ops_say_what_they_need() {
+ let (dir, b) = bundle("errors");
+ let refused = |line: &str| format!("{:#}", expand(&b, parse_lines(line).unwrap()).unwrap_err());
+ assert!(refused(r#"{"op":"ink","layer":"l3"}"#).contains("op 1"));
+ assert!(refused(r#"{"op":"light","from":["nope"],"shade":"l2"}"#).contains("op 1"));
+ let err = format!(
+ "{:#}",
+ apply_all(
+ &b.doc,
+ &parse_lines(r#"{"op":"ink","layer":"l3","path":"M0 0 L10 10"}"#).unwrap()
+ )
+ .unwrap_err()
+ );
+ assert!(err.contains("klad ink"), "{err}");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/cli/src/sheet.rs b/crates/cli/src/sheet.rs
new file mode 100644
index 0000000..8e4e526
--- /dev/null
+++ b/crates/cli/src/sheet.rs
@@ -0,0 +1,237 @@
+use crate::agent::{Look, onion_layers, render_path};
+use crate::layers::load_cels;
+use anyhow::Result;
+use klad_brush::BrushSet;
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::doc::{Document, Kind};
+use klad_render::onion::{self, Onions};
+use klad_render::sheet::{self, Plan};
+use klad_render::{Frame, View, compose_view};
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+const BATCH_BYTES: usize = 768 << 20;
+
+pub struct Sheet {
+ pub spec: String,
+ pub drawings: bool,
+ pub cell: u32,
+ pub columns: Option<usize>,
+}
+
+pub(crate) type Cels = BTreeSet<(String, String, Kind)>;
+
+pub(crate) fn shown(doc: &Document, frame: u32) -> Vec<String> {
+ doc.all_layers()
+ .iter()
+ .map(|l| l.content_at(frame).map_or(String::new(), |c| c.id.clone()))
+ .collect()
+}
+
+pub(crate) fn frame_cels(doc: &Document, frame: u32, ghosts: &[(String, Vec<onion::Ghost>)]) -> Cels {
+ doc.paint_content_at(frame)
+ .iter()
+ .map(|(l, c)| (l.id.clone(), c.id.clone(), Kind::Paint))
+ .chain(onion::needed(doc, ghosts))
+ .collect()
+}
+
+pub(crate) fn batches(frames: Vec<(u32, Cels)>, cel_bytes: usize) -> Vec<Vec<(u32, Cels)>> {
+ let limit = (BATCH_BYTES / cel_bytes.max(1)).max(1);
+ frames
+ .into_iter()
+ .fold(Vec::<Vec<(u32, Cels)>>::new(), |mut out, (frame, cels)| {
+ let fits = out.last().is_some_and(|batch| {
+ let union: BTreeSet<&(String, String, Kind)> = batch.iter().flat_map(|(_, c)| c).chain(&cels).collect();
+ union.len() <= limit
+ });
+ match out.last_mut() {
+ Some(batch) if fits => batch.push((frame, cels)),
+ _ => out.push(vec![(frame, cels)]),
+ }
+ out
+ })
+}
+
+pub fn render(path: &Path, args: &Sheet, look: &Look, out: Option<PathBuf>) -> Result<()> {
+ let start = Instant::now();
+ let bundle = Bundle::open(path)?;
+ let doc = &bundle.doc;
+ let brushes = BrushSet::for_bundle(&bundle)?;
+ let (from, to) = sheet::range(doc, &args.spec)?;
+ let plan: Plan = sheet::plan(doc, from, to, args.drawings);
+ let with_onion = look.wants_onion()?;
+ let kinds = look.kinds()?;
+ let arcs = match kinds.arcs {
+ true => {
+ let tracks = look.tracks()?;
+ if tracks.is_empty() {
+ anyhow::bail!("--overlay arcs needs --track: a mark (c4:s12), a part (leaf) or a point (x,y)");
+ }
+ crate::arcs::arcs_overlay(&crate::arcs::track(&bundle, &tracks, (from, to))?)
+ }
+ false => Vec::new(),
+ };
+ let parts: BTreeMap<u32, Vec<klad_render::overlay::Mark>> = match kinds.parts {
+ true => (from..=to)
+ .map(|f| Ok((f, crate::arcs::part_marks(&bundle, f)?)))
+ .collect::<Result<_>>()?,
+ false => BTreeMap::new(),
+ };
+ let layers = if with_onion {
+ onion_layers(&bundle, look)?
+ } else {
+ Vec::new()
+ };
+ let ghosts = |frame: u32| match with_onion {
+ true => onion::plan(doc, frame, &layers, &look.onion),
+ false => Vec::new(),
+ };
+ let mut distinct: BTreeMap<Vec<String>, u32> = BTreeMap::new();
+ let picks: Vec<u32> = plan
+ .spots
+ .iter()
+ .map(|s| match with_onion {
+ true => s.from,
+ false => *distinct.entry(shown(doc, s.from)).or_insert(s.from),
+ })
+ .collect();
+ let unique: Vec<u32> = picks.iter().copied().collect::<BTreeSet<_>>().into_iter().collect();
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let scale = args.cell as f32 / w.max(h) as f32;
+ let work: Vec<(u32, Cels)> = unique.iter().map(|&f| (f, frame_cels(doc, f, &ghosts(f)))).collect();
+ let mut images: BTreeMap<u32, Frame> = BTreeMap::new();
+ batches(work, w as usize * h as usize * 8)
+ .into_iter()
+ .try_for_each(|batch| {
+ let needed: Vec<(String, String, Kind)> = batch
+ .iter()
+ .flat_map(|(_, c)| c.iter().cloned())
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ let rasters = load_cels(&bundle, &brushes, &needed)?;
+ let done = batch
+ .par_iter()
+ .map(|(frame, _)| {
+ let plan = ghosts(*frame);
+ let onions: Option<Onions> = with_onion.then(|| onion::build(doc, &plan, &rasters));
+ let overlay = (kinds.arcs || kinds.parts).then(|| klad_render::overlay::Overlay {
+ marks: parts.get(frame).cloned().unwrap_or_default(),
+ boxes: kinds.parts,
+ ids: kinds.parts,
+ arcs: arcs.clone(),
+ frame: Some(*frame),
+ ..Default::default()
+ });
+ let image = compose_view(
+ doc,
+ *frame,
+ &rasters,
+ View::scaled(scale),
+ overlay.as_ref(),
+ onions.as_ref(),
+ )?;
+ Ok((*frame, image))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ images.extend(done);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let refs: Vec<&Frame> = picks.iter().map(|f| &images[f]).collect();
+ let clip = doc.timeline.clip(&args.spec);
+ let heading = format!(
+ "{}frames {from}-{to} at {} fps{}{}",
+ clip.map_or(String::new(), |c| format!(
+ "clip {}{}: ",
+ c.name,
+ if c.looping { " (loops)" } else { "" }
+ )),
+ clip.map_or(doc.timeline.fps, |c| doc.timeline.fps_of(c)),
+ if args.drawings { ", one cell per drawing" } else { "" },
+ if with_onion { ", onion skin" } else { "" }
+ );
+ let columns = args.columns.unwrap_or_else(|| sheet::columns_for(refs.len()));
+ let mut picture = sheet::draw(&plan, &refs, columns, &heading)?;
+ let tag = format!(
+ "-sheet-{}{}{}-{}",
+ args.spec.replace(['/', ' '], "_"),
+ if args.drawings { "-drawings" } else { "" },
+ if with_onion { "-onion" } else { "" },
+ args.cell
+ );
+ let path = out.unwrap_or_else(|| render_path(&bundle, from, View::scaled(1.0), &tag));
+ write_atomic(&path, &picture.png()?)?;
+ println!("{}", path.display());
+ eprintln!(
+ "{}x{} hash {:016x} {} cells, {} frames composed {:.0} ms",
+ picture.width,
+ picture.height,
+ picture.hash(),
+ refs.len(),
+ unique.len(),
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Cel, Layer};
+ use klad_core::stroke::{Stroke, marks};
+
+ #[test]
+ fn batches_keep_their_cels_under_the_budget() {
+ let cel = |i: usize| (format!("l{i}"), format!("c{i}"), Kind::Paint);
+ let frames: Vec<(u32, Cels)> = (0..6)
+ .map(|f| (f, [cel(f as usize), cel(99)].into_iter().collect()))
+ .collect();
+ let sizes = |b: Vec<Vec<(u32, Cels)>>| b.iter().map(Vec::len).collect::<Vec<_>>();
+ assert_eq!(sizes(batches(frames.clone(), BATCH_BYTES / 4)), [3, 3]);
+ assert_eq!(sizes(batches(frames.clone(), BATCH_BYTES)), [1, 1, 1, 1, 1, 1]);
+ assert_eq!(sizes(batches(frames, 1)), [6]);
+ }
+
+ #[test]
+ fn a_sheet_with_onion_renders_and_holds_its_hash() {
+ let dir = std::env::temp_dir().join(format!("klad-cli-sheet-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut doc = Document::new(96, 64);
+ doc.canvas.background = Some("#ffffff".into());
+ doc.timeline.frames = 4;
+ let mut ball = Layer::paint("l1", "ball", "c1");
+ *ball.cels_mut().unwrap() = vec![
+ Cel {
+ hold: Some(2),
+ ..Cel::at("c1", 0)
+ },
+ Cel::at("c2", 2),
+ ];
+ doc.layers = vec![ball];
+ let bundle = Bundle::create(&dir, doc).unwrap();
+ let dot = |x: f32| {
+ marks(vec![
+ Stroke::new(1, "ink", [0.1, 0.1, 0.1, 1.0], 20.0, 1).with_points(&[(x, 32.0, 1.0)], 0.0),
+ ])
+ };
+ bundle.write_marks("l1", "c1", &dot(24.0)).unwrap();
+ bundle.write_marks("l1", "c2", &dot(72.0)).unwrap();
+ let args = Sheet {
+ spec: "all".into(),
+ drawings: false,
+ cell: 48,
+ columns: None,
+ };
+ let out = dir.join("sheet.png");
+ let look = Look::plain(Some("onion".into()));
+ render(&dir, &args, &look, Some(out.clone())).unwrap();
+ let first = std::fs::read(&out).unwrap();
+ assert!(first.starts_with(&[0x89, b'P', b'N', b'G']));
+ render(&dir, &args, &look, Some(out.clone())).unwrap();
+ assert_eq!(std::fs::read(&out).unwrap(), first);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rs
new file mode 100644
index 0000000..711a565
--- /dev/null
+++ b/crates/cli/src/sprites.rs
@@ -0,0 +1,797 @@
+use crate::export::scale_tag;
+use crate::layers::load_cels;
+use crate::sheet::{batches, frame_cels, shown};
+use anyhow::{Context, Result, anyhow, bail};
+use klad_brush::BrushSet;
+use klad_core::bundle::{Bundle, write_atomic};
+use klad_core::ops::Op;
+use klad_render::export::{Options, Target, render};
+use klad_render::sprites::{self, Animation, Pixels, Placed, Rect, Run, Scene, Sheet, SpriteFrames, Texture};
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Component, Path, PathBuf};
+use std::time::Instant;
+
+pub struct Look {
+ pub layer: Option<String>,
+ pub scale: f32,
+ pub depth: u8,
+ pub background: bool,
+}
+
+pub struct Packing {
+ pub padding: u32,
+ pub max: u32,
+}
+
+pub struct Pictures {
+ pub source: (u32, u32),
+ pub trims: Vec<Rect>,
+ pub cut: Vec<Pixels>,
+ pub animations: Vec<(Animation, Vec<Run>)>,
+ pub firsts: Vec<u32>,
+ pub frames: usize,
+ pub composed: usize,
+ pub ms: f64,
+}
+
+struct Name {
+ dir: PathBuf,
+ stem: String,
+}
+
+impl Name {
+ fn file(&self, suffix: &str) -> PathBuf {
+ self.dir.join(format!("{}{suffix}", self.stem))
+ }
+
+ fn page(&self, i: usize) -> PathBuf {
+ match i {
+ 0 => self.file(".png"),
+ _ => self.file(&format!("-{}.png", i + 1)),
+ }
+ }
+}
+
+fn bundle_stem(bundle: &Bundle) -> String {
+ let root = bundle.root.components().collect::<PathBuf>();
+ root.file_stem()
+ .map_or("export".into(), |s| s.to_string_lossy().to_string())
+}
+
+fn bundle_dir(bundle: &Bundle) -> PathBuf {
+ let root = bundle.root.components().collect::<PathBuf>();
+ match root.parent() {
+ Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
+ _ => PathBuf::from("."),
+ }
+}
+
+fn file_safe(text: &str) -> String {
+ text.chars()
+ .map(|c| match c {
+ 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => c,
+ _ => '_',
+ })
+ .collect()
+}
+
+pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Result<Pictures> {
+ let start = Instant::now();
+ let doc = &bundle.doc;
+ let layer = look.layer.as_deref().map(|k| doc.find_layer(k)).transpose()?;
+ let target = layer.map_or(Target::Frame, Target::Layer);
+ let options = Options {
+ scale: look.scale,
+ background: look.background,
+ references: false,
+ };
+ let frames: BTreeSet<u32> = animations.iter().flat_map(|a| a.from..=a.to).collect();
+ let mut firsts: BTreeMap<Vec<String>, u32> = BTreeMap::new();
+ let first_of: BTreeMap<u32, u32> = frames
+ .iter()
+ .map(|&f| (f, *firsts.entry(shown(doc, f)).or_insert(f)))
+ .collect();
+ let unique: Vec<u32> = firsts.values().copied().collect::<BTreeSet<_>>().into_iter().collect();
+ let brushes = BrushSet::for_bundle(bundle)?;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let work: Vec<_> = unique.iter().map(|&f| (f, frame_cels(doc, f, &[]))).collect();
+ let mut made: BTreeMap<u32, (Rect, Pixels)> = BTreeMap::new();
+ batches(work, w as usize * h as usize * 8)
+ .into_iter()
+ .try_for_each(|batch| {
+ let needed: Vec<_> = batch
+ .iter()
+ .flat_map(|(_, c)| c.iter().cloned())
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ let rasters = load_cels(bundle, &brushes, &needed)?;
+ let done = batch
+ .par_iter()
+ .map(|(frame, _)| {
+ let image = render(doc, *frame, &rasters, &target, options)?;
+ let pixels = Pixels::of(&image, look.depth)?;
+ let trim = pixels.trim();
+ Ok((*frame, (trim, pixels.crop(trim))))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ made.extend(done);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let mut by_hash: BTreeMap<(u64, [u32; 4]), usize> = BTreeMap::new();
+ let mut trims = Vec::new();
+ let mut cut = Vec::new();
+ let mut firsts = Vec::new();
+ let index_of: BTreeMap<u32, usize> = made
+ .into_iter()
+ .map(|(frame, (trim, pixels))| {
+ let key = (pixels.hash(), [trim.x, trim.y, trim.w, trim.h]);
+ let index = *by_hash.entry(key).or_insert_with(|| {
+ trims.push(trim);
+ cut.push(pixels);
+ firsts.push(frame);
+ trims.len() - 1
+ });
+ (frame, index)
+ })
+ .collect();
+ let picture = |f: u32| index_of[&first_of[&f]];
+ let animations = animations
+ .into_iter()
+ .map(|a| {
+ let runs = sprites::runs(&a, picture);
+ (a, runs)
+ })
+ .collect();
+ let source = (
+ ((w as f32 * look.scale).round() as u32).max(1),
+ ((h as f32 * look.scale).round() as u32).max(1),
+ );
+ Ok(Pictures {
+ source,
+ trims,
+ cut,
+ animations,
+ firsts,
+ frames: frames.len(),
+ composed: unique.len(),
+ ms: start.elapsed().as_secs_f64() * 1000.0,
+ })
+}
+
+struct Pages {
+ placed: Vec<Placed>,
+ sizes: Vec<(u32, u32)>,
+ files: Vec<PathBuf>,
+ hashes: Vec<u64>,
+}
+
+fn write_pages(name: &Name, pics: &Pictures, packing: &Packing, depth: u8) -> Result<Pages> {
+ let sizes: Vec<(u32, u32)> = pics.trims.iter().map(|t| (t.w, t.h)).collect();
+ let room = packing.max.saturating_sub(2 * packing.padding);
+ if let Some((t, frame)) = pics
+ .trims
+ .iter()
+ .zip(&pics.firsts)
+ .find(|(t, _)| t.w > room || t.h > room)
+ {
+ bail!(
+ "frame {frame} is {}x{} px after trimming, more than a {} px page holds with {} px padding; export at a smaller --scale or raise --max",
+ t.w,
+ t.h,
+ packing.max,
+ packing.padding
+ );
+ }
+ let (placed, pages) = sprites::pack(&sizes, packing.padding, packing.max)?;
+ let encoded = pages
+ .par_iter()
+ .enumerate()
+ .map(|(i, &(w, h))| {
+ let mut page = Pixels::blank(w, h, depth);
+ pics.cut
+ .iter()
+ .zip(&placed)
+ .filter(|(_, at)| at.page == i)
+ .for_each(|(cut, at)| {
+ let all = Rect {
+ x: 0,
+ y: 0,
+ w: cut.width,
+ h: cut.height,
+ };
+ page.blit(cut, all, at.x, at.y);
+ });
+ let hash = page.hash();
+ Ok((page.png()?, hash))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let files: Vec<PathBuf> = (0..pages.len()).map(|i| name.page(i)).collect();
+ files
+ .iter()
+ .zip(&encoded)
+ .try_for_each(|(file, (bytes, _))| write_atomic(file, bytes))?;
+ Ok(Pages {
+ placed,
+ sizes: pages,
+ hashes: encoded.iter().map(|(_, h)| *h).collect(),
+ files,
+ })
+}
+
+fn remove_stale_pages(name: &Name, kept: usize) {
+ (kept..)
+ .map(|i| name.page(i))
+ .take_while(|p| p.exists())
+ .for_each(|page| {
+ let _ = fs::remove_file(&page);
+ let _ = fs::remove_file(page.with_extension("png.import"));
+ });
+}
+
+fn file_name(path: &Path) -> String {
+ path.file_name()
+ .map_or(String::new(), |n| n.to_string_lossy().to_string())
+}
+
+fn summary(pics: &Pictures, pages: &Pages) -> String {
+ let sizes: Vec<String> = pages.sizes.iter().map(|(w, h)| format!("{w}x{h}")).collect();
+ format!(
+ "{} pictures from {} frames ({} composed), {} page{} {}",
+ pics.trims.len(),
+ pics.frames,
+ pics.composed,
+ pages.sizes.len(),
+ if pages.sizes.len() == 1 { "" } else { "s" },
+ sizes.join(" ")
+ )
+}
+
+fn check_look(look: &Look) -> Result<()> {
+ if look.depth != 8 && look.depth != 16 {
+ bail!("--depth takes 8 or 16, not {}", look.depth);
+ }
+ Ok(())
+}
+
+pub fn sheet(path: &Path, spec: &str, look: &Look, packing: &Packing, out: Option<PathBuf>) -> Result<()> {
+ let start = Instant::now();
+ check_look(look)?;
+ let bundle = Bundle::open(path)?;
+ let animations = sprites::animations(&bundle.doc, spec)?;
+ let stem = bundle_stem(&bundle);
+ let name = match out {
+ Some(out) => Name {
+ dir: out.parent().map_or(PathBuf::from("."), Path::to_path_buf),
+ stem: file_name(&out).trim_end_matches(".png").to_string(),
+ },
+ None => Name {
+ dir: bundle_dir(&bundle),
+ stem: format!(
+ "{stem}-{}{}",
+ if spec == "all" { "sheet".into() } else { file_safe(spec) },
+ scale_tag(look.scale)
+ ),
+ },
+ };
+ let pics = pictures(&bundle, animations, look)?;
+ let pages = write_pages(&name, &pics, packing, look.depth)?;
+ remove_stale_pages(&name, pages.files.len());
+ let images: Vec<String> = pages.files.iter().map(|f| file_name(f)).collect();
+ let json = sprites::aseprite(&Sheet {
+ stem: &stem,
+ source: pics.source,
+ trims: &pics.trims,
+ placed: &pages.placed,
+ pages: &pages.sizes,
+ images: &images,
+ animations: &pics.animations,
+ scale: look.scale,
+ depth: look.depth,
+ });
+ let text = serde_json::to_string_pretty(&json)? + "\n";
+ let json_path = name.file(".json");
+ write_atomic(&json_path, text.as_bytes())?;
+ pages.files.iter().for_each(|f| println!("{}", f.display()));
+ println!("{}", json_path.display());
+ eprintln!("{}", summary(&pics, &pages));
+ pages
+ .files
+ .iter()
+ .zip(&pages.hashes)
+ .for_each(|(f, h)| eprintln!("hash {h:016x} {}", file_name(f)));
+ eprintln!(
+ "hash {:016x} {}",
+ klad_core::rng::fnv(klad_core::rng::FNV_OFFSET, text.as_bytes()),
+ file_name(&json_path)
+ );
+ eprintln!(
+ "pictures {:.0} ms, {:.0} ms in all",
+ pics.ms,
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+pub fn frames(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Result<()> {
+ let start = Instant::now();
+ check_look(look)?;
+ let bundle = Bundle::open(path)?;
+ let animations = sprites::animations(&bundle.doc, spec)?;
+ let stem = bundle_stem(&bundle);
+ let prefix = match spec {
+ "all" => stem.clone(),
+ other => file_safe(other),
+ };
+ let dir = out.unwrap_or_else(|| {
+ let tag = if spec == "all" {
+ "frames".into()
+ } else {
+ file_safe(spec)
+ };
+ bundle_dir(&bundle).join(format!("{stem}-{tag}{}", scale_tag(look.scale)))
+ });
+ fs::create_dir_all(&dir).with_context(|| format!("making {}", dir.display()))?;
+ let pics = pictures(&bundle, animations, look)?;
+ let (sw, sh) = pics.source;
+ let encoded = pics
+ .cut
+ .par_iter()
+ .zip(&pics.trims)
+ .map(|(cut, trim)| {
+ let mut full = Pixels::blank(sw, sh, look.depth);
+ let all = Rect {
+ x: 0,
+ y: 0,
+ w: cut.width,
+ h: cut.height,
+ };
+ full.blit(cut, all, trim.x, trim.y);
+ full.png()
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let sequence: Vec<usize> = pics
+ .animations
+ .iter()
+ .flat_map(|(_, runs)| {
+ runs.iter()
+ .flat_map(|r| std::iter::repeat_n(r.picture, r.frames as usize))
+ })
+ .collect();
+ sequence
+ .iter()
+ .enumerate()
+ .try_for_each(|(i, &p)| write_atomic(&dir.join(format!("{prefix}-{i:04}.png")), &encoded[p]))?;
+ println!("{}", dir.display());
+ eprintln!(
+ "{} frames as {prefix}-0000.png to {prefix}-{:04}.png, {} pictures ({} composed), {:.0} ms",
+ sequence.len(),
+ sequence.len().saturating_sub(1),
+ pics.trims.len(),
+ pics.composed,
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+pub fn relative(from: &Path, to: &Path) -> PathBuf {
+ let a: Vec<Component> = from.components().collect();
+ let b: Vec<Component> = to.components().collect();
+ let common = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
+ let ups = std::iter::repeat_n(Component::ParentDir, a.len() - common);
+ let path: PathBuf = ups.chain(b[common..].iter().copied()).collect();
+ match path.as_os_str().is_empty() {
+ true => PathBuf::from("."),
+ false => path,
+ }
+}
+
+fn read(path: &Path) -> Option<String> {
+ fs::read_to_string(path).ok()
+}
+
+pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packing: &Packing) -> Result<()> {
+ let start = Instant::now();
+ check_look(look)?;
+ let mut bundle = Bundle::open(path)?;
+ let home = bundle_dir(&bundle);
+ let stored = bundle.doc.export.godot.clone();
+ let target = match (&dir, &stored) {
+ (Some(d), _) => d.clone(),
+ (None, Some(s)) => home.join(s),
+ (None, None) => bail!(
+ "this document has no Godot folder yet: give one with --godot <folder> (it is kept in the document for the next export and the editor's button)"
+ ),
+ };
+ fs::create_dir_all(&target).with_context(|| format!("making {}", target.display()))?;
+ let target = target.canonicalize()?;
+ let rel = relative(&home.canonicalize()?, &target).to_string_lossy().to_string();
+ let keep = match (&dir, &stored) {
+ (Some(_), None) => true,
+ (Some(_), Some(s)) => store && *s != rel,
+ _ => false,
+ };
+ if keep {
+ bundle.apply(&[Op::Export {
+ godot: Some(rel.clone()),
+ }])?;
+ bundle.stamp("cli")?;
+ eprintln!("kept {rel} as this document's Godot folder (export.godot)");
+ } else if let (Some(_), Some(s)) = (&dir, &stored)
+ && *s != rel
+ {
+ eprintln!("exported to {rel}; the document's Godot folder stays {s} (add --store to replace it)");
+ }
+ let doc = &bundle.doc;
+ let animations = sprites::animations(doc, "all")?;
+ let stem = file_safe(&bundle_stem(&bundle));
+ let name = Name {
+ dir: target.clone(),
+ stem: stem.clone(),
+ };
+ let pics = pictures(&bundle, animations, look)?;
+ let pages = write_pages(&name, &pics, packing, look.depth)?;
+ remove_stale_pages(&name, pages.files.len());
+ let textures: Vec<Texture> = pages
+ .files
+ .iter()
+ .map(|f| Texture {
+ path: file_name(f),
+ uid: read(&f.with_extension("png.import")).and_then(|t| sprites::import_uid(&t)),
+ })
+ .collect();
+ let (tres, tscn) = (name.file(".tres"), name.file(".tscn"));
+ let uid = |file: &Path| {
+ read(file)
+ .and_then(|t| sprites::header_uid(&t))
+ .unwrap_or_else(|| sprites::uid_for(&file.to_string_lossy()))
+ };
+ let (frames_uid, scene_uid) = (uid(&tres), uid(&tscn));
+ let frames_text = sprites::sprite_frames(&SpriteFrames {
+ uid: &frames_uid,
+ textures: &textures,
+ source: pics.source,
+ trims: &pics.trims,
+ placed: &pages.placed,
+ animations: &pics.animations,
+ });
+ let (w, h) = (doc.canvas.width as f32, doc.canvas.height as f32);
+ let [ox, oy] = doc.timeline.origin.unwrap_or([w / 2.0, h / 2.0]);
+ let (sx, sy) = (pics.source.0 as f32 / w, pics.source.1 as f32 / h);
+ let first = pics
+ .animations
+ .first()
+ .map(|(a, _)| a.name.clone())
+ .ok_or_else(|| anyhow!("nothing to export"))?;
+ let scene_text = sprites::scene(&Scene {
+ uid: &scene_uid,
+ node: &sprites::node_name(&bundle_stem(&bundle)),
+ frames_path: &file_name(&tres),
+ frames_uid: &frames_uid,
+ animation: &first,
+ origin: [ox * sx, oy * sy],
+ });
+ write_atomic(&tres, frames_text.as_bytes())?;
+ write_atomic(&tscn, scene_text.as_bytes())?;
+ pages
+ .files
+ .iter()
+ .chain([&tres, &tscn])
+ .for_each(|f| println!("{}", f.display()));
+ let names: Vec<String> = pics
+ .animations
+ .iter()
+ .map(|(a, runs)| {
+ format!(
+ "{} ({} frames, {} entries, {} fps{})",
+ a.name,
+ a.to - a.from + 1,
+ runs.len(),
+ a.fps,
+ if a.looping { ", loops" } else { "" }
+ )
+ })
+ .collect();
+ eprintln!("{}", summary(&pics, &pages));
+ eprintln!("animations: {}", names.join(", "));
+ eprintln!(
+ "pictures {:.0} ms, {:.0} ms in all",
+ pics.ms,
+ start.elapsed().as_secs_f64() * 1000.0
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Cel, Clip, Document, Layer};
+ use klad_core::stroke::{Stroke, marks};
+ use serde_json::Value;
+ use std::process::Command;
+
+ const CHECK: &str = r#"extends SceneTree
+
+func _init():
+ var args = OS.get_cmdline_user_args()
+ var frames: SpriteFrames = load("res://art/hop.tres")
+ var out = {"animations": {}}
+ for anim in frames.get_animation_names():
+ var list = []
+ for i in frames.get_frame_count(anim):
+ var t: AtlasTexture = frames.get_frame_texture(anim, i)
+ list.append([frames.get_frame_duration(anim, i), t.get_width(), t.get_height(), t.region.position.x, t.region.position.y, t.margin.position.x, t.margin.position.y])
+ out["animations"][anim] = {"speed": frames.get_animation_speed(anim), "loop": frames.get_animation_loop(anim), "frames": list}
+ var node = load("res://art/hop.tscn").instantiate()
+ out["scene"] = [node.get_class(), String(node.animation), node.centered, node.offset.x, node.offset.y]
+ node.free()
+ out["uids"] = []
+ for uid in args:
+ var res = load(uid)
+ out["uids"].append(res.resource_path if res else "")
+ print("RESULT ", JSON.stringify(out))
+ quit()
+"#;
+
+ fn godot_binary() -> Option<String> {
+ let binary = std::env::var("GODOT").unwrap_or_else(|_| "godot".into());
+ let ok = Command::new(&binary)
+ .arg("--version")
+ .output()
+ .is_ok_and(|o| o.status.success());
+ ok.then_some(binary)
+ }
+
+ fn godot_run(binary: &str, project: &Path, args: &[&str]) -> String {
+ let out = Command::new(binary)
+ .args(["--headless", "--path"])
+ .arg(project)
+ .args(args)
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&out.stdout).to_string() + &String::from_utf8_lossy(&out.stderr)
+ }
+
+ fn hop(dir: &Path) -> PathBuf {
+ let mut doc = Document::new(64, 48);
+ doc.timeline.frames = 10;
+ doc.timeline.origin = Some([20.0, 40.0]);
+ doc.timeline.clips = vec![
+ Clip::new("idle", 0, 3, true),
+ Clip {
+ fps: Some(24),
+ ..Clip::new("hop", 4, 9, false)
+ },
+ ];
+ let mut ball = Layer::paint("l1", "ball", "c1");
+ *ball.cels_mut().unwrap() = vec![
+ Cel {
+ hold: Some(3),
+ ..Cel::at("c1", 0)
+ },
+ Cel::at("c2", 3),
+ Cel::at("c3", 4),
+ Cel {
+ hold: Some(2),
+ ..Cel::at("c4", 5)
+ },
+ Cel {
+ link: Some("c1".into()),
+ ..Cel::at("c5", 7)
+ },
+ ];
+ doc.layers = vec![ball];
+ let path = dir.join("hop.draw");
+ let bundle = Bundle::create(&path, doc).unwrap();
+ let dot = |x: f32, y: f32| {
+ marks(vec![
+ Stroke::new(1, "ink", [0.8, 0.2, 0.1, 1.0], 10.0, 1).with_points(&[(x, y, 1.0)], 0.0),
+ ])
+ };
+ [
+ ("c1", 20.0, 36.0),
+ ("c2", 22.0, 28.0),
+ ("c3", 24.0, 16.0),
+ ("c4", 26.0, 24.0),
+ ]
+ .iter()
+ .for_each(|(cel, x, y)| {
+ bundle.write_marks("l1", cel, &dot(*x, *y)).unwrap();
+ });
+ path
+ }
+
+ fn look(scale: f32) -> Look {
+ Look {
+ layer: None,
+ scale,
+ depth: 8,
+ background: false,
+ }
+ }
+
+ const PACKING: Packing = Packing { padding: 2, max: 4096 };
+
+ #[test]
+ fn godot_imports_the_export_with_its_clips_timing_origin_and_uids() {
+ let Some(binary) = godot_binary() else {
+ eprintln!("no godot on PATH (or $GODOT): skipping the import check");
+ return;
+ };
+ let dir = std::env::temp_dir().join(format!("draw-godot-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let project = dir.join("game");
+ fs::create_dir_all(project.join("art")).unwrap();
+ fs::write(
+ project.join("project.godot"),
+ "config_version=5\n\n[application]\n\nconfig/name=\"klad check\"\n",
+ )
+ .unwrap();
+ fs::write(project.join("check.gd"), CHECK).unwrap();
+ let path = hop(&dir);
+ godot(&path, Some(project.join("art")), false, &look(2.0), &PACKING).unwrap();
+ assert_eq!(
+ Bundle::open(&path).unwrap().doc.export.godot.as_deref(),
+ Some("game/art")
+ );
+ let tres = project.join("art/hop.tres");
+ let tscn = project.join("art/hop.tscn");
+ let uids = |p: &Path| sprites::header_uid(&fs::read_to_string(p).unwrap()).unwrap();
+ let (frames_uid, scene_uid) = (uids(&tres), uids(&tscn));
+ godot_run(&binary, &project, &["--import"]);
+ let result = |text: &str| -> Value {
+ let line = text
+ .lines()
+ .find_map(|l| l.strip_prefix("RESULT "))
+ .unwrap_or_else(|| panic!("no result from godot:\n{text}"));
+ serde_json::from_str(line).unwrap()
+ };
+ let first = result(&godot_run(&binary, &project, &["--script", "res://check.gd"]));
+ let anims = &first["animations"];
+ let idle = &anims["idle"];
+ assert_eq!(
+ (idle["speed"].as_f64(), idle["loop"].as_bool()),
+ (Some(12.0), Some(true))
+ );
+ let durations = |a: &Value| -> Vec<f64> {
+ a["frames"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|f| f[0].as_f64().unwrap())
+ .collect()
+ };
+ assert_eq!(durations(idle), [3.0, 1.0]);
+ let hop_anim = &anims["hop"];
+ assert_eq!(
+ (hop_anim["speed"].as_f64(), hop_anim["loop"].as_bool()),
+ (Some(24.0), Some(false))
+ );
+ assert_eq!(durations(hop_anim), [1.0, 2.0, 3.0]);
+ assert!(anims.get("default").is_none());
+ hop_anim["frames"].as_array().unwrap().iter().for_each(|f| {
+ assert_eq!(
+ (f[1].as_f64(), f[2].as_f64()),
+ (Some(128.0), Some(96.0)),
+ "full canvas size at 2x"
+ );
+ });
+ let idle_first = &idle["frames"][0];
+ let hop_last = &hop_anim["frames"][2];
+ assert_eq!(
+ idle_first.as_array().unwrap()[3..],
+ hop_last.as_array().unwrap()[3..],
+ "a link shares its picture"
+ );
+ assert_eq!(
+ first["scene"],
+ serde_json::json!(["AnimatedSprite2D", "idle", false, -40.0, -80.0])
+ );
+ let png = project.join("art/hop.png.import");
+ let texture_uid = sprites::import_uid(&fs::read_to_string(&png).unwrap()).unwrap();
+ let bundle = Bundle::open(&path).unwrap();
+ let moved = marks(vec![
+ Stroke::new(1, "ink", [0.1, 0.3, 0.9, 1.0], 12.0, 1).with_points(&[(40.0, 10.0, 1.0)], 0.0),
+ ]);
+ bundle.write_marks("l1", "c3", &moved).unwrap();
+ godot(&path, None, false, &look(2.0), &PACKING).unwrap();
+ assert_eq!((uids(&tres), uids(&tscn)), (frames_uid.clone(), scene_uid.clone()));
+ let text = fs::read_to_string(&tres).unwrap();
+ assert!(
+ text.contains(&format!("uid=\"{texture_uid}\" path=\"hop.png\"")),
+ "{text}"
+ );
+ godot_run(&binary, &project, &["--import"]);
+ let second = result(&godot_run(
+ &binary,
+ &project,
+ &["--script", "res://check.gd", "--", &frames_uid, &scene_uid],
+ ));
+ assert_eq!(
+ second["uids"],
+ serde_json::json!(["res://art/hop.tres", "res://art/hop.tscn"]),
+ "the uids Godot knew still load the files"
+ );
+ assert_ne!(
+ second["animations"]["hop"]["frames"][0],
+ first["animations"]["hop"]["frames"][0]
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn sheets_and_frames_land_next_to_the_bundle_and_add_up_to_each_clip() {
+ let dir = std::env::temp_dir().join(format!("draw-sprites-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let path = hop(&dir);
+ sheet(&path, "all", &look(1.0), &PACKING, None).unwrap();
+ let json: Value = serde_json::from_str(&fs::read_to_string(dir.join("hop-sheet.json")).unwrap()).unwrap();
+ let frames = json["frames"].as_array().unwrap();
+ let tags = json["meta"]["frameTags"].as_array().unwrap();
+ let ms = |tag: &Value| -> u64 {
+ let (a, b) = (
+ tag["from"].as_u64().unwrap() as usize,
+ tag["to"].as_u64().unwrap() as usize,
+ );
+ frames[a..=b].iter().map(|f| f["duration"].as_u64().unwrap()).sum()
+ };
+ assert_eq!(
+ (tags[0]["name"].as_str(), ms(&tags[0])),
+ (Some("idle"), 333),
+ "4 frames at 12 fps"
+ );
+ assert_eq!(
+ (tags[1]["name"].as_str(), ms(&tags[1])),
+ (Some("hop"), 250),
+ "6 frames at 24 fps"
+ );
+ assert_eq!(frames.len(), 5);
+ let rects: BTreeSet<String> = frames.iter().map(|f| f["frame"].to_string()).collect();
+ assert_eq!(rects.len(), 4, "the link back to c1 reuses its picture");
+ assert!(
+ frames
+ .iter()
+ .all(|f| f["trimmed"] == true && f["sourceSize"] == serde_json::json!({"w": 64, "h": 48}))
+ );
+ let png = fs::read(dir.join("hop-sheet.png")).unwrap();
+ sheet(&path, "all", &look(1.0), &PACKING, None).unwrap();
+ assert_eq!(
+ fs::read(dir.join("hop-sheet.png")).unwrap(),
+ png,
+ "exports repeat exactly"
+ );
+ sheet(&path, "hop", &look(0.5), &PACKING, None).unwrap();
+ assert!(dir.join("[email protected]").exists() && dir.join("[email protected]").exists());
+ frames_out(&path, &dir);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ fn frames_out(path: &Path, dir: &Path) {
+ frames(path, "hop", &look(1.0), None).unwrap();
+ let out = dir.join("hop-hop");
+ let names: Vec<String> = fs::read_dir(&out)
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ assert_eq!(names.len(), 6);
+ assert_eq!((names[0].as_str(), names[5].as_str()), ("hop-0000.png", "hop-0005.png"));
+ let read = |n: usize| fs::read(out.join(&names[n])).unwrap();
+ assert_eq!(read(1), read(2), "a held frame is the same picture");
+ assert_ne!(read(0), read(1));
+ assert_eq!(u32::from_be_bytes(read(0)[16..20].try_into().unwrap()), 64);
+ }
+
+ #[test]
+ fn relative_folders_walk_up_and_down() {
+ let rel = |a: &str, b: &str| relative(Path::new(a), Path::new(b)).to_string_lossy().to_string();
+ assert_eq!(rel("/work/art", "/work/game/sprites"), "../game/sprites");
+ assert_eq!(rel("/work/art", "/work/art/godot"), "godot");
+ assert_eq!(rel("/work/art", "/work/art"), ".");
+ assert_eq!(rel("/a/b/c", "/x"), "../../../x");
+ }
+}
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
new file mode 100644
index 0000000..bc2dc91
--- /dev/null
+++ b/crates/cli/tests/binary.rs
@@ -0,0 +1,44 @@
+use std::process::Command;
+
+#[test]
+fn the_binary_runs() {
+ let out = Command::new(env!("CARGO_BIN_EXE_klad"))
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert!(out.status.success());
+ assert!(String::from_utf8_lossy(&out.stdout).starts_with("klad"));
+}
+
+#[test]
+fn a_drawing_moves_and_a_layer_duplicates_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-move-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = dir.join("a.draw");
+ let draw = |args: &[&str]| {
+ let out = Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let path = bundle.to_str().unwrap();
+ draw(&["new", path, "--width", "200", "--height", "100", "--frames", "12"]);
+ draw(&["stroke", path, "l1", "--path", "M10 10 L190 90", "--size", "4"]);
+ draw(&["cel", path, "dup", "c2", "--frame", "8", "--hold", "2"]);
+ draw(&["cel", path, "move", "c2", "--frame", "2"]);
+ assert!(draw(&["duplicate", path, "paint 1"]).contains("added"));
+ let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(bundle.join("doc.json")).unwrap()).unwrap();
+ let layers = doc["layers"].as_array().unwrap();
+ assert_eq!(layers.len(), 2);
+ assert_eq!(layers[1]["name"], "paint 1 copy");
+ let starts = |l: &serde_json::Value| -> Vec<u64> {
+ l["cels"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| c["frame"].as_u64().unwrap())
+ .collect()
+ };
+ assert_eq!(starts(&layers[0]), [2, 10]);
+ assert_eq!(starts(&layers[1]), [2, 10]);
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml
new file mode 100644
index 0000000..74fd42a
--- /dev/null
+++ b/crates/core/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "klad-core"
+version.workspace = true
+edition.workspace = true
+license-file.workspace = true
+publish.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+half = "2.7.1"
+libm = "0.2.16"
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = { version = "1.0.154", features = ["float_roundtrip"] }
+zstd = "0.14.3"
diff --git a/crates/core/brushes/library/airbrush.json b/crates/core/brushes/library/airbrush.json
new file mode 100644
index 0000000..2d0d3c7
--- /dev/null
+++ b/crates/core/brushes/library/airbrush.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Airbrush",
+ "tip": { "round": { "hardness": 0.0 } },
+ "spacing": 0.05,
+ "flow": 0.05,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.7 } },
+ "flow": { "pressure": { "min": 0.05, "gamma": 1.8 } }
+ },
+ "smoothing": 20
+}
diff --git a/crates/core/brushes/library/blender.json b/crates/core/brushes/library/blender.json
new file mode 100644
index 0000000..e6aa48c
--- /dev/null
+++ b/crates/core/brushes/library/blender.json
@@ -0,0 +1,8 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Blender",
+ "tip": { "round": { "hardness": 0.1 } },
+ "spacing": 0.08,
+ "flow": 0.6,
+ "paint": { "blend": { "strength": 0.5 } }
+}
diff --git a/crates/core/brushes/library/chalk.json b/crates/core/brushes/library/chalk.json
new file mode 100644
index 0000000..bb471c7
--- /dev/null
+++ b/crates/core/brushes/library/chalk.json
@@ -0,0 +1,14 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Chalk",
+ "tip": { "chalk": { "seed": 7 } },
+ "spacing": 0.15,
+ "angle": "follow",
+ "flow": 0.7,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.7 } },
+ "flow": { "pressure": { "min": 0.3 } }
+ },
+ "jitter": { "size": 0.1, "angle": 0.5, "scatter": 0.05 },
+ "grain": { "paper": { "seed": 23, "feature": 4 }, "strength": 0.45 }
+}
diff --git a/crates/core/brushes/library/dry-brush.json b/crates/core/brushes/library/dry-brush.json
new file mode 100644
index 0000000..c0f75c4
--- /dev/null
+++ b/crates/core/brushes/library/dry-brush.json
@@ -0,0 +1,10 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Dry brush",
+ "tip": { "round": { "hardness": 0.8 } },
+ "spacing": 0.08,
+ "angle": "follow",
+ "dynamics": { "flow": { "pressure": { "min": 0.4 } } },
+ "dual": { "tip": { "image": { "image": "bristle-round" } }, "size": 0.6, "scatter": 0.6 },
+ "grain": { "paper": { "seed": 53, "feature": 4 }, "strength": 0.3, "pressure": 0.5 }
+}
diff --git a/crates/core/brushes/library/eraser.json b/crates/core/brushes/library/eraser.json
new file mode 100644
index 0000000..8f16da0
--- /dev/null
+++ b/crates/core/brushes/library/eraser.json
@@ -0,0 +1,10 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Eraser",
+ "tip": { "round": { "hardness": 0.85 } },
+ "spacing": 0.06,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.4 } }
+ },
+ "blend": "erase"
+}
diff --git a/crates/core/brushes/library/flat-bristle.json b/crates/core/brushes/library/flat-bristle.json
new file mode 100644
index 0000000..4e2e9d6
--- /dev/null
+++ b/crates/core/brushes/library/flat-bristle.json
@@ -0,0 +1,14 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Flat bristle",
+ "tip": { "image": { "image": "bristle-flat" } },
+ "spacing": 0.05,
+ "angle": "follow",
+ "flow": 0.8,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.6 } },
+ "flow": { "pressure": { "min": 0.35 } }
+ },
+ "jitter": { "angle": 0.05 },
+ "grain": { "paper": { "seed": 31, "feature": 3 }, "strength": 0.25, "pressure": 0.6 }
+}
diff --git a/crates/core/brushes/library/fog.json b/crates/core/brushes/library/fog.json
new file mode 100644
index 0000000..b043ccb
--- /dev/null
+++ b/crates/core/brushes/library/fog.json
@@ -0,0 +1,25 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Fog",
+ "tip": {
+ "round": {
+ "hardness": 0.0
+ }
+ },
+ "spacing": 0.1,
+ "flow": 0.15,
+ "dynamics": {
+ "size": {
+ "pressure": {
+ "min": 0.8
+ }
+ }
+ },
+ "grain": {
+ "paper": {
+ "seed": 41,
+ "feature": 32
+ },
+ "strength": 0.06
+ }
+}
diff --git a/crates/core/brushes/library/grass.json b/crates/core/brushes/library/grass.json
new file mode 100644
index 0000000..2e38633
--- /dev/null
+++ b/crates/core/brushes/library/grass.json
@@ -0,0 +1,8 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Grass",
+ "tip": { "image": { "image": "grass" } },
+ "spacing": 0.35,
+ "jitter": { "size": 0.3, "angle": 0.2, "scatter": 0.3 },
+ "color": { "hue": 6.0, "value": 0.12 }
+}
diff --git a/crates/core/brushes/library/ink.json b/crates/core/brushes/library/ink.json
new file mode 100644
index 0000000..a4a93ca
--- /dev/null
+++ b/crates/core/brushes/library/ink.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Inking pen",
+ "tip": { "round": { "hardness": 0.92 } },
+ "spacing": 0.04,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.06, "gamma": 1.5 } }
+ },
+ "taper": [10, 24],
+ "stabilizer": 24,
+ "smoothing": 12
+}
diff --git a/crates/core/brushes/library/leaves.json b/crates/core/brushes/library/leaves.json
new file mode 100644
index 0000000..23aaa75
--- /dev/null
+++ b/crates/core/brushes/library/leaves.json
@@ -0,0 +1,9 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Leaves",
+ "tip": { "image": { "image": "leaf" } },
+ "spacing": 0.6,
+ "angle": "follow",
+ "jitter": { "size": 0.5, "angle": 1.2, "scatter": 1.2 },
+ "color": { "hue": 8.0, "saturation": 0.1, "value": 0.15, "strokeValue": 0.05 }
+}
diff --git a/crates/core/brushes/library/marker.json b/crates/core/brushes/library/marker.json
new file mode 100644
index 0000000..5cb5ebe
--- /dev/null
+++ b/crates/core/brushes/library/marker.json
@@ -0,0 +1,15 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Marker",
+ "tip": { "round": { "hardness": 0.75 } },
+ "spacing": 0.05,
+ "roundness": 0.45,
+ "angle": { "fixed": -0.6 },
+ "opacity": 0.7,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.85 } },
+ "opacity": { "pressure": { "min": 0.55 } }
+ },
+ "stabilizer": 8,
+ "smoothing": 8
+}
diff --git a/crates/core/brushes/library/oil-load.json b/crates/core/brushes/library/oil-load.json
new file mode 100644
index 0000000..036cec9
--- /dev/null
+++ b/crates/core/brushes/library/oil-load.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Loaded oil",
+ "tip": {"round": {"hardness": 0.78}},
+ "spacing": 0.04,
+ "roundness": 0.65,
+ "angle": "follow",
+ "opacity": 1.0,
+ "dynamics": {"size": {"pressure": {"min": 0.15}}, "opacity": {"pressure": {"min": 0.65}}},
+ "jitter": {"size": 0.05},
+ "grain": {"paper": {"seed": 29, "feature": 2}, "strength": 0.28}
+}
diff --git a/crates/core/brushes/library/oil.json b/crates/core/brushes/library/oil.json
new file mode 100644
index 0000000..815c8c5
--- /dev/null
+++ b/crates/core/brushes/library/oil.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Oil",
+ "tip": {"round": {"hardness": 0.55}},
+ "spacing": 0.05,
+ "roundness": 0.75,
+ "angle": "follow",
+ "opacity": 1.0,
+ "dynamics": {"size": {"pressure": {"min": 0.12}}, "opacity": {"pressure": {"min": 0.5}}},
+ "jitter": {"size": 0.04},
+ "grain": {"paper": {"seed": 11, "feature": 3}, "strength": 0.12}
+}
diff --git a/crates/core/brushes/library/pencil.json b/crates/core/brushes/library/pencil.json
new file mode 100644
index 0000000..d1d22bc
--- /dev/null
+++ b/crates/core/brushes/library/pencil.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Pencil",
+ "tip": { "round": { "hardness": 0.6 } },
+ "spacing": 0.1,
+ "flow": 0.55,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.5 } },
+ "flow": { "pressure": { "min": 0.15, "gamma": 1.3 } }
+ },
+ "grain": { "paper": { "seed": 11, "feature": 2 }, "strength": 0.55 }
+}
diff --git a/crates/core/brushes/library/round-bristle.json b/crates/core/brushes/library/round-bristle.json
new file mode 100644
index 0000000..8b5d140
--- /dev/null
+++ b/crates/core/brushes/library/round-bristle.json
@@ -0,0 +1,35 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Round bristle",
+ "tip": {
+ "image": {
+ "image": "bristle-round"
+ }
+ },
+ "spacing": 0.12,
+ "angle": "follow",
+ "flow": 0.4,
+ "dynamics": {
+ "size": {
+ "pressure": {
+ "min": 0.5
+ }
+ },
+ "flow": {
+ "pressure": {
+ "min": 0.3
+ }
+ }
+ },
+ "color": {
+ "value": 0.03
+ },
+ "grain": {
+ "paper": {
+ "seed": 43,
+ "feature": 2
+ },
+ "strength": 0.15,
+ "pressure": 0.5
+ }
+}
diff --git a/crates/core/brushes/library/smudge.json b/crates/core/brushes/library/smudge.json
new file mode 100644
index 0000000..4f11788
--- /dev/null
+++ b/crates/core/brushes/library/smudge.json
@@ -0,0 +1,8 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Smudge",
+ "tip": { "round": { "hardness": 0.3 } },
+ "spacing": 0.05,
+ "dynamics": { "flow": { "pressure": { "min": 0.3 } } },
+ "paint": { "smudge": { "strength": 0.8 } }
+}
diff --git a/crates/core/brushes/library/soft.json b/crates/core/brushes/library/soft.json
new file mode 100644
index 0000000..6f6c5ed
--- /dev/null
+++ b/crates/core/brushes/library/soft.json
@@ -0,0 +1,10 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Soft",
+ "tip": { "round": { "hardness": 0.0 } },
+ "spacing": 0.08,
+ "flow": 0.08,
+ "dynamics": {
+ "flow": { "pressure": { "min": 0.2, "gamma": 1.5 } }
+ }
+}
diff --git a/crates/core/brushes/library/splatter.json b/crates/core/brushes/library/splatter.json
new file mode 100644
index 0000000..69b82f8
--- /dev/null
+++ b/crates/core/brushes/library/splatter.json
@@ -0,0 +1,7 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Splatter",
+ "tip": { "image": { "image": "splatter" } },
+ "spacing": 1.2,
+ "jitter": { "size": 0.5, "angle": 3.14, "scatter": 0.8 }
+}
diff --git a/crates/core/brushes/library/sponge.json b/crates/core/brushes/library/sponge.json
new file mode 100644
index 0000000..5338b43
--- /dev/null
+++ b/crates/core/brushes/library/sponge.json
@@ -0,0 +1,9 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Sponge",
+ "tip": { "image": { "image": "sponge" } },
+ "spacing": 0.2,
+ "flow": 0.6,
+ "dynamics": { "flow": { "pressure": { "min": 0.2 } } },
+ "jitter": { "size": 0.2, "angle": 3.14, "scatter": 0.15 }
+}
diff --git a/crates/core/brushes/library/two-tone.json b/crates/core/brushes/library/two-tone.json
new file mode 100644
index 0000000..3c994b0
--- /dev/null
+++ b/crates/core/brushes/library/two-tone.json
@@ -0,0 +1,8 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Two tone",
+ "tip": { "round": { "hardness": 0.8 } },
+ "spacing": 0.05,
+ "dynamics": { "size": { "pressure": { "min": 0.4 } } },
+ "color": { "pressure": { "min": 0.0 } }
+}
diff --git a/crates/core/brushes/library/wet.json b/crates/core/brushes/library/wet.json
new file mode 100644
index 0000000..5c63d2e
--- /dev/null
+++ b/crates/core/brushes/library/wet.json
@@ -0,0 +1,9 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Wet round",
+ "tip": { "round": { "hardness": 0.5 } },
+ "spacing": 0.05,
+ "flow": 0.5,
+ "dynamics": { "flow": { "pressure": { "min": 0.2 } } },
+ "paint": { "wet": { "wetness": 0.7, "pickup": 0.6, "dilution": 0.25 } }
+}
diff --git a/crates/core/brushes/m1/chalk.json b/crates/core/brushes/m1/chalk.json
new file mode 100644
index 0000000..bb471c7
--- /dev/null
+++ b/crates/core/brushes/m1/chalk.json
@@ -0,0 +1,14 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Chalk",
+ "tip": { "chalk": { "seed": 7 } },
+ "spacing": 0.15,
+ "angle": "follow",
+ "flow": 0.7,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.7 } },
+ "flow": { "pressure": { "min": 0.3 } }
+ },
+ "jitter": { "size": 0.1, "angle": 0.5, "scatter": 0.05 },
+ "grain": { "paper": { "seed": 23, "feature": 4 }, "strength": 0.45 }
+}
diff --git a/crates/core/brushes/m1/eraser.json b/crates/core/brushes/m1/eraser.json
new file mode 100644
index 0000000..8f16da0
--- /dev/null
+++ b/crates/core/brushes/m1/eraser.json
@@ -0,0 +1,10 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Eraser",
+ "tip": { "round": { "hardness": 0.85 } },
+ "spacing": 0.06,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.4 } }
+ },
+ "blend": "erase"
+}
diff --git a/crates/core/brushes/m1/ink.json b/crates/core/brushes/m1/ink.json
new file mode 100644
index 0000000..ddb5726
--- /dev/null
+++ b/crates/core/brushes/m1/ink.json
@@ -0,0 +1,9 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Ink (M1)",
+ "tip": { "round": { "hardness": 0.92 } },
+ "spacing": 0.04,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.06, "gamma": 1.5 } }
+ }
+}
diff --git a/crates/core/brushes/m1/pencil.json b/crates/core/brushes/m1/pencil.json
new file mode 100644
index 0000000..d1d22bc
--- /dev/null
+++ b/crates/core/brushes/m1/pencil.json
@@ -0,0 +1,12 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Pencil",
+ "tip": { "round": { "hardness": 0.6 } },
+ "spacing": 0.1,
+ "flow": 0.55,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.5 } },
+ "flow": { "pressure": { "min": 0.15, "gamma": 1.3 } }
+ },
+ "grain": { "paper": { "seed": 11, "feature": 2 }, "strength": 0.55 }
+}
diff --git a/crates/core/brushes/m1/soft.json b/crates/core/brushes/m1/soft.json
new file mode 100644
index 0000000..6f6c5ed
--- /dev/null
+++ b/crates/core/brushes/m1/soft.json
@@ -0,0 +1,10 @@
+{
+ "format": "draw-anything-brush/1",
+ "name": "Soft",
+ "tip": { "round": { "hardness": 0.0 } },
+ "spacing": 0.08,
+ "flow": 0.08,
+ "dynamics": {
+ "flow": { "pressure": { "min": 0.2, "gamma": 1.5 } }
+ }
+}
diff --git a/crates/core/src/brushes.rs b/crates/core/src/brushes.rs
new file mode 100644
index 0000000..b279dd3
--- /dev/null
+++ b/crates/core/src/brushes.rs
@@ -0,0 +1,579 @@
+use crate::doc::valid_id;
+use crate::rng::{FNV_OFFSET, fnv};
+use anyhow::{Result, bail};
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+pub const BRUSH_FORMAT: &str = "draw-anything-brush/1";
+pub const SPEED_FULL: f32 = 5.0;
+
+const LIBRARY: &[(&str, &str)] = &[
+ ("ink", include_str!("../brushes/library/ink.json")),
+ ("pencil", include_str!("../brushes/library/pencil.json")),
+ ("marker", include_str!("../brushes/library/marker.json")),
+ ("airbrush", include_str!("../brushes/library/airbrush.json")),
+ ("soft", include_str!("../brushes/library/soft.json")),
+ ("chalk", include_str!("../brushes/library/chalk.json")),
+ ("eraser", include_str!("../brushes/library/eraser.json")),
+ ("flat-bristle", include_str!("../brushes/library/flat-bristle.json")),
+ ("round-bristle", include_str!("../brushes/library/round-bristle.json")),
+ ("sponge", include_str!("../brushes/library/sponge.json")),
+ ("fog", include_str!("../brushes/library/fog.json")),
+ ("leaves", include_str!("../brushes/library/leaves.json")),
+ ("grass", include_str!("../brushes/library/grass.json")),
+ ("splatter", include_str!("../brushes/library/splatter.json")),
+ ("wet", include_str!("../brushes/library/wet.json")),
+ ("smudge", include_str!("../brushes/library/smudge.json")),
+ ("blender", include_str!("../brushes/library/blender.json")),
+ ("dry-brush", include_str!("../brushes/library/dry-brush.json")),
+ ("two-tone", include_str!("../brushes/library/two-tone.json")),
+ ("oil", include_str!("../brushes/library/oil.json")),
+ ("oil-load", include_str!("../brushes/library/oil-load.json")),
+];
+
+const M1: &[(&str, &str)] = &[
+ ("pencil", include_str!("../brushes/m1/pencil.json")),
+ ("ink", include_str!("../brushes/m1/ink.json")),
+ ("soft", include_str!("../brushes/m1/soft.json")),
+ ("chalk", include_str!("../brushes/m1/chalk.json")),
+ ("eraser", include_str!("../brushes/m1/eraser.json")),
+];
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct BrushDef {
+ #[serde(default = "brush_format")]
+ pub format: String,
+ pub name: String,
+ pub tip: TipDef,
+ pub spacing: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub roundness: f32,
+ #[serde(default, skip_serializing_if = "AngleDef::is_default")]
+ pub angle: AngleDef,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub flow: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub opacity: f32,
+ #[serde(default, skip_serializing_if = "Dynamics::is_empty")]
+ pub dynamics: Dynamics,
+ #[serde(default, skip_serializing_if = "Jitter::is_zero")]
+ pub jitter: Jitter,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub grain: Option<GrainDef>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub dual: Option<DualDef>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub color: Option<ColorDef>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub paint: Option<PaintDef>,
+ #[serde(default, skip_serializing_if = "BrushBlend::is_normal")]
+ pub blend: BrushBlend,
+ #[serde(default, skip_serializing_if = "is_untapered")]
+ pub taper: [f32; 2],
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub stabilizer: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub smoothing: f32,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase", deny_unknown_fields)]
+pub enum TipDef {
+ Round { hardness: f32 },
+ Chalk { seed: u32 },
+ Image { image: String },
+}
+
+pub const TIP_IMAGES: [&str; 6] = ["bristle-flat", "bristle-round", "sponge", "leaf", "grass", "splatter"];
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct DualDef {
+ pub tip: TipDef,
+ #[serde(default = "half", skip_serializing_if = "is_half")]
+ pub size: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub scatter: f32,
+ #[serde(default = "three", skip_serializing_if = "is_three")]
+ pub count: u32,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ColorDef {
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub hue: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub saturation: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub value: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub stroke_hue: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub stroke_saturation: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub stroke_value: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pressure: Option<Curve>,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub along: f32,
+}
+
+impl ColorDef {
+ pub fn uses_second(&self) -> bool {
+ self.pressure.is_some() || self.along > 0.0
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase", deny_unknown_fields)]
+pub enum PaintDef {
+ Wet { wetness: f32, pickup: f32, dilution: f32 },
+ Smudge { strength: f32 },
+ Blend { strength: f32 },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum AngleDef {
+ Fixed(f32),
+ Follow,
+ Tilt,
+}
+
+impl Default for AngleDef {
+ fn default() -> Self {
+ AngleDef::Fixed(0.0)
+ }
+}
+
+impl AngleDef {
+ fn is_default(&self) -> bool {
+ *self == Self::default()
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Dynamics {
+ #[serde(default, skip_serializing_if = "Channel::is_empty")]
+ pub size: Channel,
+ #[serde(default, skip_serializing_if = "Channel::is_empty")]
+ pub flow: Channel,
+ #[serde(default, skip_serializing_if = "Channel::is_empty")]
+ pub opacity: Channel,
+}
+
+impl Dynamics {
+ fn is_empty(&self) -> bool {
+ self.size.is_empty() && self.flow.is_empty() && self.opacity.is_empty()
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Channel {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pressure: Option<Curve>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tilt: Option<Curve>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub speed: Option<Curve>,
+}
+
+impl Channel {
+ fn is_empty(&self) -> bool {
+ self.pressure.is_none() && self.tilt.is_none() && self.speed.is_none()
+ }
+
+ pub fn at(&self, pressure: f32, tilt: f32, speed: f32) -> f32 {
+ [(self.pressure, pressure), (self.tilt, tilt), (self.speed, speed)]
+ .iter()
+ .filter_map(|(curve, x)| curve.map(|c| c.at(*x)))
+ .fold(1.0, |acc, v| acc * v)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Curve {
+ #[serde(default)]
+ pub min: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub max: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub gamma: f32,
+}
+
+impl Curve {
+ pub fn at(&self, x: f32) -> f32 {
+ self.min + (self.max - self.min) * libm::powf(x, self.gamma)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Jitter {
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub size: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub angle: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub scatter: f32,
+}
+
+impl Jitter {
+ fn is_zero(&self) -> bool {
+ *self == Self::default()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GrainDef {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub paper: Option<Paper>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub image: Option<String>,
+ pub strength: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub scale: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub contrast: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub pressure: f32,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Paper {
+ pub seed: u32,
+ pub feature: usize,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum BrushBlend {
+ #[default]
+ Normal,
+ Erase,
+}
+
+impl BrushBlend {
+ fn is_normal(&self) -> bool {
+ *self == BrushBlend::Normal
+ }
+}
+
+fn brush_format() -> String {
+ BRUSH_FORMAT.to_string()
+}
+
+fn one() -> f32 {
+ 1.0
+}
+
+fn is_one(v: &f32) -> bool {
+ *v == 1.0
+}
+
+fn half() -> f32 {
+ 0.5
+}
+
+fn is_half(v: &f32) -> bool {
+ *v == 0.5
+}
+
+fn three() -> u32 {
+ 3
+}
+
+fn is_three(v: &u32) -> bool {
+ *v == 3
+}
+
+fn is_zero(v: &f32) -> bool {
+ *v == 0.0
+}
+
+fn is_untapered(v: &[f32; 2]) -> bool {
+ *v == [0.0, 0.0]
+}
+
+fn within(what: &str, v: f32, lo: f32, hi: f32) -> Result<()> {
+ if !(lo..=hi).contains(&v) {
+ bail!("{what} {v} is outside {lo}..{hi}");
+ }
+ Ok(())
+}
+
+pub fn valid_image(name: &str) -> Result<()> {
+ if name.is_empty() || name.len() > 64 || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
+ bail!("image name {name:?}: letters, digits, - and _ only");
+ }
+ Ok(())
+}
+
+impl TipDef {
+ fn validate(&self, what: &str) -> Result<()> {
+ match self {
+ TipDef::Round { hardness } => within(&format!("{what} hardness"), *hardness, 0.0, 1.0),
+ TipDef::Chalk { .. } => Ok(()),
+ TipDef::Image { image } => valid_image(image),
+ }
+ }
+}
+
+impl Curve {
+ fn validate(&self, what: &str) -> Result<()> {
+ within(&format!("{what} min"), self.min, 0.0, 4.0)?;
+ within(&format!("{what} max"), self.max, 0.0, 4.0)?;
+ within(&format!("{what} gamma"), self.gamma, 0.05, 10.0)
+ }
+}
+
+impl Channel {
+ fn validate(&self, what: &str) -> Result<()> {
+ [("pressure", self.pressure), ("tilt", self.tilt), ("speed", self.speed)]
+ .iter()
+ .filter_map(|(input, curve)| curve.map(|c| (input, c)))
+ .try_for_each(|(input, curve)| curve.validate(&format!("{what} {input}")))
+ }
+}
+
+impl BrushDef {
+ pub fn parse(text: &str) -> Result<Self> {
+ let def: BrushDef = serde_json::from_str(text)?;
+ def.validate()?;
+ Ok(def)
+ }
+
+ pub fn validate(&self) -> Result<()> {
+ if self.format != BRUSH_FORMAT {
+ bail!("brush format {} is not {BRUSH_FORMAT}", self.format);
+ }
+ self.tip.validate("tip")?;
+ if let Some(dual) = &self.dual {
+ dual.tip.validate("dual tip")?;
+ within("dual size", dual.size, 0.05, 2.0)?;
+ within("dual scatter", dual.scatter, 0.0, 4.0)?;
+ within("dual count", dual.count as f32, 1.0, 8.0)?;
+ }
+ if let Some(color) = &self.color {
+ within("hue jitter", color.hue, 0.0, 180.0)?;
+ within("stroke hue jitter", color.stroke_hue, 0.0, 180.0)?;
+ [
+ ("saturation jitter", color.saturation),
+ ("value jitter", color.value),
+ ("stroke saturation jitter", color.stroke_saturation),
+ ("stroke value jitter", color.stroke_value),
+ ]
+ .iter()
+ .try_for_each(|(what, v)| within(what, *v, 0.0, 1.0))?;
+ if let Some(curve) = &color.pressure {
+ curve.validate("colour pressure")?;
+ }
+ within("colour along", color.along, 0.0, 100_000.0)?;
+ }
+ match self.paint {
+ Some(PaintDef::Wet {
+ wetness,
+ pickup,
+ dilution,
+ }) => {
+ within("wetness", wetness, 0.0, 1.0)?;
+ within("pickup", pickup, 0.0, 1.0)?;
+ within("dilution", dilution, 0.0, 1.0)?;
+ }
+ Some(PaintDef::Smudge { strength } | PaintDef::Blend { strength }) => {
+ within("strength", strength, 0.0, 1.0)?
+ }
+ None => {}
+ }
+ within("spacing", self.spacing, 0.01, 10.0)?;
+ within("roundness", self.roundness, 0.05, 1.0)?;
+ within("flow", self.flow, 0.001, 1.0)?;
+ within("opacity", self.opacity, 0.001, 1.0)?;
+ self.dynamics.size.validate("size")?;
+ self.dynamics.flow.validate("flow")?;
+ self.dynamics.opacity.validate("opacity")?;
+ within("size jitter", self.jitter.size, 0.0, 1.0)?;
+ within("angle jitter", self.jitter.angle, 0.0, 7.0)?;
+ within("scatter", self.jitter.scatter, 0.0, 10.0)?;
+ if let Some(grain) = &self.grain {
+ within("grain strength", grain.strength, 0.0, 1.0)?;
+ match (&grain.paper, &grain.image) {
+ (Some(paper), None) => within("grain feature", paper.feature as f32, 1.0, 512.0)?,
+ (None, Some(image)) => valid_image(image)?,
+ _ => bail!("a grain is either paper or an image"),
+ }
+ within("grain scale", grain.scale, 0.05, 20.0)?;
+ within("grain contrast", grain.contrast, 0.0, 8.0)?;
+ within("grain pressure", grain.pressure, 0.0, 1.0)?;
+ }
+ within("taper in", self.taper[0], 0.0, 10_000.0)?;
+ within("taper out", self.taper[1], 0.0, 10_000.0)?;
+ within("stabilizer", self.stabilizer, 0.0, 500.0)?;
+ within("smoothing", self.smoothing, 0.0, 500.0)
+ }
+
+ pub fn to_json(&self) -> Result<String> {
+ let mut text = serde_json::to_string_pretty(self)?;
+ text.push('\n');
+ Ok(text)
+ }
+
+ pub fn hardness(&self) -> Option<f32> {
+ match self.tip {
+ TipDef::Round { hardness } => Some(hardness),
+ _ => None,
+ }
+ }
+
+ pub fn images(&self) -> Vec<&str> {
+ fn tip(t: &TipDef) -> Option<&str> {
+ match t {
+ TipDef::Image { image } => Some(image.as_str()),
+ _ => None,
+ }
+ }
+ tip(&self.tip)
+ .into_iter()
+ .chain(self.dual.as_ref().and_then(|d| tip(&d.tip)))
+ .chain(self.grain.as_ref().and_then(|g| g.image.as_deref()))
+ .filter(|name| !TIP_IMAGES.contains(name))
+ .collect()
+ }
+
+ pub fn reads_pixels(&self) -> bool {
+ self.paint.is_some()
+ }
+
+ pub fn fingerprint(&self) -> u64 {
+ fnv(FNV_OFFSET, &serde_json::to_vec(self).unwrap_or_default())
+ }
+}
+
+fn parse_set(set: &[(&str, &str)], id: &str) -> Option<BrushDef> {
+ set.iter()
+ .find(|(name, _)| *name == id)
+ .and_then(|(_, text)| BrushDef::parse(text).ok())
+}
+
+pub fn library_ids() -> Vec<&'static str> {
+ LIBRARY.iter().map(|(id, _)| *id).collect()
+}
+
+pub fn library(id: &str) -> Option<BrushDef> {
+ parse_set(LIBRARY, id)
+}
+
+pub fn legacy_m1(id: &str) -> Option<BrushDef> {
+ parse_set(M1, id)
+}
+
+fn base_of(id: &str) -> &str {
+ match id.rsplit_once('-') {
+ Some((base, tail)) if tail.len() == 6 && tail.chars().all(|c| c.is_ascii_hexdigit()) => base,
+ _ => id,
+ }
+}
+
+pub fn pick_id(base: &str, def: &BrushDef, embedded: &BTreeMap<String, BrushDef>) -> String {
+ let base = base_of(base);
+ let fits = |id: &str| match embedded.get(id) {
+ Some(known) => known == def,
+ None => library(id).is_none_or(|known| &known == def),
+ };
+ if valid_id(base) && fits(base) {
+ return base.to_string();
+ }
+ let print = def.fingerprint();
+ let short = format!("{base}-{:06x}", print & 0xff_ffff);
+ if fits(&short) {
+ return short;
+ }
+ format!("{base}-{print:016x}")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_built_in_brush_parses_and_round_trips() {
+ LIBRARY.iter().chain(M1).for_each(|(id, text)| {
+ let def = BrushDef::parse(text).unwrap_or_else(|e| panic!("{id}: {e:#}"));
+ let back = BrushDef::parse(&def.to_json().unwrap()).unwrap();
+ assert_eq!(back, def, "{id}");
+ });
+ assert_eq!(library_ids().len(), 21);
+ assert!(library("ink").unwrap().taper[1] > 0.0);
+ assert_eq!(legacy_m1("ink").unwrap().taper, [0.0, 0.0]);
+ assert!(legacy_m1("marker").is_none());
+ }
+
+ #[test]
+ fn curves_follow_min_max_and_gamma() {
+ let curve = Curve {
+ min: 0.2,
+ max: 1.0,
+ gamma: 2.0,
+ };
+ assert_eq!(curve.at(0.0), 0.2);
+ assert_eq!(curve.at(1.0), 1.0);
+ assert!((curve.at(0.5) - 0.4).abs() < 1e-6);
+ let channel = Channel {
+ pressure: Some(curve),
+ tilt: None,
+ speed: Some(Curve {
+ min: 1.0,
+ max: 0.5,
+ gamma: 1.0,
+ }),
+ };
+ assert!((channel.at(1.0, 0.3, 1.0) - 0.5).abs() < 1e-6);
+ assert_eq!(Channel::default().at(0.1, 0.2, 0.3), 1.0);
+ }
+
+ #[test]
+ fn bad_brushes_are_rejected() {
+ let ink = library("ink").unwrap();
+ let broken = |f: fn(&mut BrushDef)| {
+ let mut def = ink.clone();
+ f(&mut def);
+ def.validate().unwrap_err().to_string()
+ };
+ assert!(broken(|d| d.spacing = 0.0).contains("spacing"));
+ assert!(broken(|d| d.tip = TipDef::Round { hardness: 2.0 }).contains("hardness"));
+ assert!(
+ broken(|d| d.dynamics.size.pressure = Some(Curve {
+ min: 0.0,
+ max: 1.0,
+ gamma: 0.0
+ }))
+ .contains("gamma")
+ );
+ assert!(BrushDef::parse(r#"{"name":"x","tip":{"round":{"hardness":1}},"spacing":0.1,"sise":3}"#).is_err());
+ }
+
+ #[test]
+ fn ids_stay_put_until_a_brush_differs() {
+ let ink = library("ink").unwrap();
+ let none = BTreeMap::new();
+ assert_eq!(pick_id("ink", &ink, &none), "ink");
+ let mut harder = ink.clone();
+ harder.tip = TipDef::Round { hardness: 1.0 };
+ let variant = pick_id("ink", &harder, &none);
+ assert!(variant.starts_with("ink-") && variant.len() == 10, "{variant}");
+ assert_eq!(pick_id(&variant, &harder, &none), variant);
+ let old = BTreeMap::from([("ink".to_string(), legacy_m1("ink").unwrap())]);
+ assert_ne!(pick_id("ink", &ink, &old), "ink");
+ assert_eq!(pick_id("ink", &legacy_m1("ink").unwrap(), &old), "ink");
+ let mut custom = ink.clone();
+ custom.name = "Mine".into();
+ assert!(pick_id("mine", &custom, &none) == "mine");
+ }
+}
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
new file mode 100644
index 0000000..ea39cdf
--- /dev/null
+++ b/crates/core/src/bundle.rs
@@ -0,0 +1,1097 @@
+use crate::brushes::{self, BrushDef};
+use crate::doc::{Document, Layer, Loc};
+use crate::history::checkpoint;
+use crate::markedit::{self, LassoAction, MarkChange};
+use crate::migrate::migrate;
+use crate::ops::{Applied, ClipEdit, FillSpec, Op, PendingMarks, apply_all};
+use crate::stroke::{Mark, Stroke, decode_cel, encode_cel, strokes_of};
+use crate::timing::{CelAction, FrameSpec};
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncStamp {
+ pub rev: u64,
+ pub author: String,
+ pub at_ms: u64,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Blank {
+ pub width: u32,
+ pub height: u32,
+ pub layers: usize,
+ pub background: Option<String>,
+ pub fps: u32,
+ pub frames: u32,
+ pub sketch: bool,
+}
+
+impl Default for Blank {
+ fn default() -> Self {
+ Self {
+ width: 2048,
+ height: 2048,
+ layers: 1,
+ background: None,
+ fps: 12,
+ frames: 1,
+ sketch: false,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Changed {
+ pub disk: u64,
+ pub here: u64,
+}
+
+impl std::fmt::Display for Changed {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "the document changed while this edit was being made (rev {} on disk, {} when it started); nothing was written, run it again",
+ self.disk, self.here
+ )
+ }
+}
+
+impl std::error::Error for Changed {}
+
+pub fn disk_rev(root: &Path) -> Option<u64> {
+ let path = root.join("doc.json");
+ let mut head = vec![0u8; 4096];
+ let read = {
+ use std::io::Read;
+ fs::File::open(&path).ok()?.read(&mut head).ok()?
+ };
+ let text = String::from_utf8_lossy(&head[..read]);
+ let quick = text.find("\"rev\"").and_then(|at| {
+ let rest = text[at + 5..].trim_start().strip_prefix(':')?.trim_start();
+ let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
+ let end = rest[digits.len()..].chars().next()?;
+ (!digits.is_empty() && matches!(end, ',' | '\n' | ' ' | '\r' | '}')).then(|| digits.parse().ok())?
+ });
+ quick.or_else(|| {
+ let text = fs::read_to_string(&path).ok()?;
+ serde_json::from_str::<serde_json::Value>(&text).ok()?["rev"].as_u64()
+ })
+}
+
+pub fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_or(0, |d| d.as_millis() as u64)
+}
+
+pub struct Bundle {
+ pub root: PathBuf,
+ pub doc: Document,
+}
+
+fn name_parts(doc: &mut Document, pending: &[PendingMarks]) {
+ let source_part = |doc: &Document, cel: &str, id: u32| -> Option<String> {
+ match doc.locate(cel) {
+ Some(Loc::Cel(path, c)) => doc.layer_at(&path).cels()[c].part_of(id).map(String::from),
+ _ => None,
+ }
+ };
+ pending.iter().for_each(|p| {
+ let named: Vec<(String, Vec<u32>)> = p
+ .changes
+ .iter()
+ .flat_map(|change| match change {
+ MarkChange::Part { name, ids, .. } => vec![(name.clone(), ids.clone())],
+ MarkChange::Paste { made, .. } => made
+ .iter()
+ .filter_map(|c| source_part(doc, &c.cel, c.from).map(|name| (name, vec![c.to])))
+ .collect(),
+ _ => Vec::new(),
+ })
+ .collect();
+ if named.is_empty() {
+ return;
+ }
+ if let Some(Loc::Cel(path, c)) = doc.locate(&p.cel)
+ && let Some(cels) = doc.layer_at_mut(&path).cels_mut()
+ {
+ named.iter().for_each(|(name, ids)| cels[c].set_part(name, ids));
+ }
+ });
+}
+
+impl Bundle {
+ pub fn open(root: impl AsRef<Path>) -> Result<Self> {
+ let root = root.as_ref().to_path_buf();
+ remember(&root);
+ let path = root.join("doc.json");
+ let text = fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
+ let raw: serde_json::Value =
+ serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
+ let migrated = migrate(raw).with_context(|| format!("upgrading {}", path.display()))?;
+ let doc: Document =
+ serde_json::from_value(migrated.value.clone()).with_context(|| format!("reading {}", path.display()))?;
+ doc.validate().with_context(|| format!("checking {}", path.display()))?;
+ let mut bundle = Self { root, doc };
+ if migrated.changed() {
+ migrated.moves.iter().try_for_each(|m| {
+ let from = bundle.root.join(&m.from);
+ if from.exists() {
+ write_atomic(&bundle.root.join(&m.to), &fs::read(&from)?)?;
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ if migrated.embed_m1_brushes {
+ bundle.embed_m1_brushes()?;
+ }
+ bundle.save()?;
+ migrated.moves.iter().for_each(|m| {
+ let _ = fs::remove_file(bundle.root.join(&m.from));
+ });
+ eprintln!("upgraded {} to {}", bundle.root.display(), bundle.doc.format);
+ }
+ Ok(bundle)
+ }
+
+ pub fn brush_path(&self, id: &str) -> PathBuf {
+ self.root.join("brushes").join(format!("{id}.json"))
+ }
+
+ pub fn brushes(&self) -> Result<BTreeMap<String, BrushDef>> {
+ let dir = self.root.join("brushes");
+ if !dir.exists() {
+ return Ok(BTreeMap::new());
+ }
+ fs::read_dir(&dir)?
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .filter(|p| p.extension().is_some_and(|x| x == "json"))
+ .map(|path| {
+ let id = path.file_stem().unwrap_or_default().to_string_lossy().to_string();
+ let text = fs::read_to_string(&path)?;
+ let def = BrushDef::parse(&text).with_context(|| format!("brush {}", path.display()))?;
+ Ok((id, def))
+ })
+ .collect()
+ }
+
+ pub fn brush(&self, id: &str) -> Result<Option<BrushDef>> {
+ let path = self.brush_path(id);
+ if path.exists() {
+ let def = BrushDef::parse(&fs::read_to_string(&path)?).with_context(|| format!("brush {id}"))?;
+ return Ok(Some(def));
+ }
+ Ok(brushes::library(id))
+ }
+
+ pub fn embed_brush(&self, id: &str, def: &BrushDef) -> Result<bool> {
+ let path = self.brush_path(id);
+ if path.exists() {
+ return Ok(false);
+ }
+ if !crate::doc::valid_id(id) {
+ bail!("brush id {id:?} may only use letters, digits, - and _");
+ }
+ def.validate().with_context(|| format!("brush {id}"))?;
+ write_atomic(&path, def.to_json()?.as_bytes())?;
+ Ok(true)
+ }
+
+ pub fn brush_ids(&self) -> Result<Vec<String>> {
+ let embedded = self.brushes()?;
+ let mut ids: Vec<String> = embedded.keys().cloned().collect();
+ ids.extend(
+ brushes::library_ids()
+ .into_iter()
+ .filter(|id| !embedded.contains_key(*id))
+ .map(String::from),
+ );
+ Ok(ids)
+ }
+
+ fn used_brushes(&self) -> Result<BTreeSet<String>> {
+ self.doc
+ .paint_cels()
+ .iter()
+ .try_fold(BTreeSet::new(), |mut used, (layer, cel)| {
+ used.extend(self.read_strokes(&layer.id, &cel.id)?.into_iter().map(|s| s.brush));
+ Ok(used)
+ })
+ }
+
+ fn embed_m1_brushes(&self) -> Result<()> {
+ self.used_brushes()?.iter().try_for_each(|id| {
+ match brushes::legacy_m1(id).or_else(|| brushes::library(id)) {
+ Some(def) => {
+ self.embed_brush(id, &def)?;
+ }
+ None => eprintln!("{}: strokes use unknown brush {id:?}", self.root.display()),
+ }
+ Ok(())
+ })
+ }
+
+ pub fn embed_brushes_of(&self, marks: &[Mark]) -> Result<()> {
+ self.embed_library(strokes_of(marks).map(|s| s.brush.as_str()))
+ }
+
+ fn embed_library<'a>(&self, ids: impl Iterator<Item = &'a str>) -> Result<()> {
+ let wanted: BTreeSet<&str> = ids.collect();
+ let missing = wanted
+ .into_iter()
+ .filter(|id| !self.brush_path(id).exists())
+ .map(|id| match brushes::library(id) {
+ Some(def) => Ok((id, def)),
+ None => bail!("unknown brush {id:?}: brushes are {}", self.brush_ids()?.join(", ")),
+ })
+ .collect::<Result<Vec<_>>>()?;
+ missing
+ .iter()
+ .try_for_each(|(id, def)| self.embed_brush(id, def).map(|_| ()))
+ }
+
+ pub fn create(root: impl AsRef<Path>, doc: Document) -> Result<Self> {
+ doc.validate()?;
+ let root = root.as_ref().to_path_buf();
+ remember(&root);
+ fs::create_dir_all(&root)?;
+ write_atomic(&root.join(".gitignore"), b".cache/\n")?;
+ let mut bundle = Self { root, doc };
+ bundle.save()?;
+ Ok(bundle)
+ }
+
+ pub fn blank(root: impl AsRef<Path>, blank: &Blank, author: &str) -> Result<Self> {
+ let root = root.as_ref();
+ if root.join("doc.json").exists() {
+ bail!("{} already exists", root.display());
+ }
+ let mut doc = Document::new(blank.width, blank.height);
+ doc.canvas.background = blank.background.clone();
+ doc.timeline.fps = blank.fps;
+ doc.timeline.frames = blank.frames;
+ doc.layers = (1..=blank.layers)
+ .map(|i| {
+ let (layer, cel) = (doc.alloc_id('l'), doc.alloc_id('c'));
+ Layer::paint(&layer, &format!("paint {i}"), &cel)
+ })
+ .collect();
+ if blank.sketch {
+ let (layer, cel) = (doc.alloc_id('l'), doc.alloc_id('c'));
+ doc.layers.push(Layer::vector(&layer, "sketch", &cel, Vec::new()));
+ }
+ let bundle = Self::create(root, doc)?;
+ bundle.stamp(author)?;
+ Ok(bundle)
+ }
+
+ pub fn save(&mut self) -> Result<()> {
+ self.doc.rev += 1;
+ let mut text = serde_json::to_string_pretty(&self.doc)?;
+ text.push('\n');
+ write_atomic(&self.root.join("doc.json"), text.as_bytes())
+ }
+
+ pub fn strokes_path(&self, layer: &str, cel: &str) -> PathBuf {
+ self.root.join("strokes").join(layer).join(format!("{cel}.strokes"))
+ }
+
+ pub fn read_marks(&self, layer: &str, cel: &str) -> Result<Vec<Mark>> {
+ let path = self.strokes_path(layer, cel);
+ if !path.exists() {
+ return Ok(Vec::new());
+ }
+ decode_cel(&fs::read(&path)?).with_context(|| format!("reading {}", path.display()))
+ }
+
+ pub fn read_strokes(&self, layer: &str, cel: &str) -> Result<Vec<Stroke>> {
+ Ok(strokes_of(&self.read_marks(layer, cel)?).cloned().collect())
+ }
+
+ pub fn write_marks(&self, layer: &str, cel: &str, marks: &[Mark]) -> Result<u64> {
+ self.embed_brushes_of(marks)?;
+ let bytes = encode_cel(marks)?;
+ write_atomic(&self.strokes_path(layer, cel), &bytes)?;
+ Ok(bytes.len() as u64)
+ }
+
+ pub fn apply(&mut self, ops: &[Op]) -> Result<Applied> {
+ self.apply_as(ops, "cli")
+ }
+
+ pub fn apply_as(&mut self, ops: &[Op], author: &str) -> Result<Applied> {
+ let (mut doc, mut applied) = apply_all(&self.doc, ops)?;
+ self.embed_library(
+ applied
+ .marks
+ .iter()
+ .flat_map(|p| p.changes.iter().flat_map(MarkChange::brushes)),
+ )?;
+ let plan = applied.marks.clone();
+ let written = applied
+ .marks
+ .iter_mut()
+ .map(|pending| {
+ let mut marks = self.read_marks(&pending.layer, &pending.cel)?;
+ pending
+ .changes
+ .iter_mut()
+ .try_for_each(|change| self.apply_change(&plan, &mut marks, change, &pending.cel))?;
+ Ok((pending.layer.clone(), pending.cel.clone(), marks))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ name_parts(&mut doc, &applied.marks);
+ let touched: Vec<PathBuf> = written
+ .iter()
+ .map(|(layer, cel, _)| self.strokes_path(layer, cel))
+ .chain(applied.dropped_cels.iter().map(|(l, c)| self.strokes_path(l, c)))
+ .collect();
+ checkpoint(self, &doc, author, &summarize(ops), &touched)?;
+ self.doc = doc;
+ written
+ .iter()
+ .try_for_each(|(layer, cel, marks)| self.write_marks(layer, cel, marks).map(|_| ()))?;
+ self.save()?;
+ applied.dropped_cels.iter().for_each(|(layer, cel)| {
+ let _ = fs::remove_file(self.strokes_path(layer, cel));
+ });
+ Ok(applied)
+ }
+
+ pub fn apply_change(
+ &self,
+ plan: &[PendingMarks],
+ marks: &mut Vec<Mark>,
+ change: &mut MarkChange,
+ cel: &str,
+ ) -> Result<()> {
+ match change {
+ MarkChange::Copy { layer, cel, upto } => {
+ *marks = self.marks_after(plan, layer, cel, *upto)?;
+ Ok(())
+ }
+ MarkChange::Paste {
+ sources,
+ transform,
+ cut,
+ made,
+ } => {
+ let copies = sources
+ .iter()
+ .map(|source| {
+ let from = self.marks_after(plan, &source.layer, &source.cel, source.upto)?;
+ source
+ .ids
+ .iter()
+ .try_for_each(|id| match from.iter().any(|m| m.id() == *id) {
+ true => Ok(()),
+ false => bail!("{} does not exist", markedit::address(&source.cel, *id)),
+ })?;
+ Ok(from
+ .into_iter()
+ .filter(|m| source.ids.contains(&m.id()))
+ .map(|m| (source.cel.clone(), m))
+ .collect::<Vec<_>>())
+ })
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .flatten()
+ .collect();
+ *made = markedit::paste(marks, copies, transform.as_ref(), cut.as_deref())?;
+ Ok(())
+ }
+ _ => markedit::apply(marks, change, cel),
+ }
+ }
+
+ fn marks_after(&self, plan: &[PendingMarks], layer: &str, cel: &str, upto: usize) -> Result<Vec<Mark>> {
+ let mut marks = self.read_marks(layer, cel)?;
+ if let Some(pending) = plan.iter().find(|p| p.layer == layer && p.cel == cel) {
+ pending
+ .changes
+ .iter()
+ .take(upto)
+ .try_for_each(|c| self.apply_change(plan, &mut marks, &mut c.clone(), cel))?;
+ }
+ Ok(marks)
+ }
+
+ pub fn replace_marks(&mut self, layer: &str, cel: &str, marks: &[Mark], author: &str, summary: &str) -> Result<()> {
+ checkpoint(self, &self.doc, author, summary, &[self.strokes_path(layer, cel)])?;
+ self.write_marks(layer, cel, marks)?;
+ self.save()
+ }
+
+ pub fn cache_dir(&self) -> PathBuf {
+ self.root.join(".cache")
+ }
+
+ pub fn reload(&mut self) -> Result<()> {
+ self.doc = Self::open(&self.root)?.doc;
+ Ok(())
+ }
+
+ pub fn ensure_unchanged(&self) -> Result<()> {
+ match disk_rev(&self.root) {
+ Some(disk) if disk != self.doc.rev => Err(Changed {
+ disk,
+ here: self.doc.rev,
+ }
+ .into()),
+ _ => Ok(()),
+ }
+ }
+
+ pub fn stamp_path(&self) -> PathBuf {
+ self.cache_dir().join("sync.json")
+ }
+
+ pub fn stamp(&self, author: &str) -> Result<SyncStamp> {
+ let stamp = SyncStamp {
+ rev: self.doc.rev,
+ author: author.to_string(),
+ at_ms: now_ms(),
+ };
+ write_atomic(&self.stamp_path(), serde_json::to_string(&stamp)?.as_bytes())?;
+ Ok(stamp)
+ }
+
+ pub fn read_stamp(&self) -> Option<SyncStamp> {
+ serde_json::from_str(&fs::read_to_string(self.stamp_path()).ok()?).ok()
+ }
+}
+
+pub fn summarize(ops: &[Op]) -> String {
+ let parts: Vec<String> = ops
+ .iter()
+ .map(|op| match op {
+ Op::AddLayer { layer, .. } => format!("add layer {}", layer["kind"].as_str().unwrap_or("")),
+ Op::AddNode { node, .. } => format!("add {}", node["type"].as_str().unwrap_or("node")),
+ Op::AddCel { layer, .. } => format!("add cel to {layer}"),
+ Op::AddMask { layer, .. } => format!("add mask to {layer}"),
+ Op::Lasso(spec) => format!(
+ "lasso {}on {}",
+ match (spec.cut, &spec.action) {
+ (true, LassoAction::Remove) => "cut and delete ",
+ (false, LassoAction::Remove) => "delete ",
+ (true, _) => "cut and move ",
+ (false, _) => "move ",
+ },
+ spec.layer
+ ),
+ Op::Set { id, .. } => format!("set {id}"),
+ Op::Remove { ids } => format!("rm {}", ids.join(" ")),
+ Op::Move { id, .. } => format!("mv {id}"),
+ Op::Stroke(spec) => format!("stroke on {}", spec.layer),
+ Op::Fill(FillSpec {
+ like: Some(cel), layer, ..
+ }) => format!("fills on {layer} like {cel}"),
+ Op::Fill(spec) => format!("fill on {}", spec.layer),
+ Op::Palette(_) => "palette".to_string(),
+ Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
+ Op::Path { id, .. } => format!("path {id}"),
+ Op::Copy(spec) => format!(
+ "copy {} mark{} to {}",
+ spec.ids.len(),
+ if spec.ids.len() == 1 { "" } else { "s" },
+ match &spec.to {
+ crate::ops::CopyTarget::Cel(cel) => cel.clone(),
+ crate::ops::CopyTarget::Frame { frame, .. } => format!("frame {frame}"),
+ }
+ ),
+ Op::Timeline { origin: Some(_), .. } => "timeline origin".to_string(),
+ Op::Timeline { .. } => "timeline".to_string(),
+ Op::Atmosphere(Some(_)) => "atmosphere".to_string(),
+ Op::Atmosphere(None) => "atmosphere off".to_string(),
+ Op::Clip(edit) => match edit {
+ ClipEdit::Add(clip) => format!("add clip {}", clip.name),
+ ClipEdit::Set { name, .. } => format!("set clip {name}"),
+ ClipEdit::Remove { name } => format!("rm clip {name}"),
+ },
+ Op::Export { .. } => "export folder".to_string(),
+ Op::Frames(FrameSpec { insert, at, count, .. }) => format!(
+ "{} {count} frame{} at {at}",
+ if *insert { "insert" } else { "remove" },
+ if *count == 1 { "" } else { "s" }
+ ),
+ Op::Duplicate { layer } => format!("duplicate layer {layer}"),
+ Op::Part { ids, name } if name.is_empty() => format!("take {} out of their part", ids.join(", ")),
+ Op::Part { ids, name } => format!("part {name}: {}", ids.join(", ")),
+ Op::Ink(spec) => format!("ink {} on {}", spec.from.join(", "), spec.layer),
+ Op::Light(spec) => format!("light {}", spec.from.join(", ")),
+ Op::Hatch(spec) => format!("hatch on {}", spec.layer),
+ Op::Paint(spec) => format!("paint on {}", spec.layer),
+ Op::Scatter(spec) => format!("scatter on {}", spec.layer),
+ Op::Inbetween(spec) if spec.redo => "redo in-betweens".to_string(),
+ Op::Inbetween(spec) => format!(
+ "in-between {} frames {} to {}",
+ spec.layers.join(","),
+ spec.from.unwrap_or_default(),
+ spec.to.unwrap_or_default()
+ ),
+ Op::Retime(spec) => format!(
+ "retime frames {} to {} {}",
+ spec.from,
+ spec.to,
+ match spec.action {
+ crate::retime::Retime::On(n) => format!("on {n}s"),
+ crate::retime::Retime::Fit(n) => format!("into {n} frames"),
+ crate::retime::Retime::Reverse => "reversed".to_string(),
+ crate::retime::Retime::Pingpong => "ping-pong".to_string(),
+ }
+ ),
+ Op::Cel(spec) => match &spec.action {
+ CelAction::New { layer } => format!("new drawing on {layer}"),
+ CelAction::Dup { cel } => format!("duplicate {cel}"),
+ CelAction::Link { cel } => format!("link {cel}"),
+ CelAction::Unlink { cel } => format!("unlink {cel}"),
+ CelAction::Move { cel } => format!("move {cel} to frame {}", spec.frame.unwrap_or(0)),
+ },
+ })
+ .collect();
+ let grouped = parts.iter().fold(Vec::<(String, usize)>::new(), |mut acc, part| {
+ match acc.last_mut() {
+ Some((last, n)) if last == part => *n += 1,
+ _ => acc.push((part.clone(), 1)),
+ }
+ acc
+ });
+ let text = grouped
+ .iter()
+ .map(|(part, n)| if *n > 1 { format!("{part} x{n}") } else { part.clone() })
+ .collect::<Vec<_>>()
+ .join(", ");
+ if text.chars().count() > 120 {
+ format!("{}...", text.chars().take(117).collect::<String>())
+ } else {
+ text
+ }
+}
+
+static OPENED: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
+
+fn remember(root: &Path) {
+ let mut opened = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+ if !opened.iter().any(|r| r == root) {
+ opened.push(root.to_path_buf());
+ }
+}
+
+pub fn opened() -> Vec<PathBuf> {
+ OPENED.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let mut tmp = path.as_os_str().to_owned();
+ tmp.push(format!(".tmp-{}-{n}", std::process::id()));
+ let tmp = PathBuf::from(tmp);
+ fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;
+ fs::rename(&tmp, path).with_context(|| format!("renaming into {}", path.display()))?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::synth::Synth;
+
+ fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-bundle-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ #[test]
+ fn a_writer_finds_out_when_the_document_changed_under_it() {
+ use crate::ops::parse_lines;
+ let dir = scratch("changed");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ doc.next_id = 10;
+ let mut first = Bundle::create(&dir, doc).unwrap();
+ assert_eq!(disk_rev(&dir), Some(first.doc.rev));
+ let mut second = Bundle::open(&dir).unwrap();
+ assert!(first.ensure_unchanged().is_ok());
+ second
+ .apply(&parse_lines(r#"{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}"#).unwrap())
+ .unwrap();
+ assert_eq!(disk_rev(&dir), Some(second.doc.rev));
+ let refused = first.ensure_unchanged().unwrap_err();
+ assert_eq!(
+ refused.downcast_ref::<Changed>(),
+ Some(&Changed {
+ disk: second.doc.rev,
+ here: first.doc.rev
+ })
+ );
+ first.reload().unwrap();
+ assert!(first.ensure_unchanged().is_ok());
+ fs::write(dir.join("doc.json"), "{\n \"rev\":\n 99, \"format\": \"x\"}").unwrap();
+ assert_eq!(disk_rev(&dir), Some(99));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_moved_drawing_pushes_the_drawings_it_lands_on_and_leaves_its_frames_blank() {
+ use crate::ops::parse_lines;
+ let dir = scratch("move");
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 12;
+ let mut layer = Layer::paint("l1", "ink", "c1");
+ if let Some(cels) = layer.cels_mut() {
+ cels[0].hold = Some(2);
+ cels.push(crate::doc::Cel::at("c2", 2));
+ cels[1].hold = Some(2);
+ cels.push(crate::doc::Cel::at("c3", 4));
+ cels[2].hold = Some(3);
+ cels.push(crate::doc::Cel::at("c4", 7));
+ }
+ doc.layers.push(layer);
+ doc.next_id = 10;
+ let mut b = Bundle::create(&dir, doc).unwrap();
+ let starts = |b: &Bundle| -> Vec<(String, u32, Option<u32>)> {
+ b.doc
+ .layer("l1")
+ .unwrap()
+ .cels()
+ .iter()
+ .map(|c| (c.id.clone(), c.frame, c.hold))
+ .collect()
+ };
+ b.apply(&parse_lines(r#"{"op":"cel","move":"c1","frame":9}"#).unwrap())
+ .unwrap();
+ assert_eq!(starts(&b)[0], ("c2".into(), 2, Some(2)));
+ assert!(starts(&b).contains(&("c1".into(), 9, Some(2))));
+ assert!(starts(&b).contains(&("c4".into(), 7, Some(2))), "{:?}", starts(&b));
+ b.apply(&parse_lines(r#"{"op":"cel","move":"c1","frame":5}"#).unwrap())
+ .unwrap();
+ let after = starts(&b);
+ assert!(after.contains(&("c3".into(), 4, Some(1))), "{after:?}");
+ assert!(after.contains(&("c1".into(), 5, Some(2))), "{after:?}");
+ assert!(after.contains(&("c4".into(), 7, Some(2))), "{after:?}");
+ b.apply(&parse_lines(r#"{"op":"cel","move":"c1","frame":6}"#).unwrap())
+ .unwrap();
+ let after = starts(&b);
+ assert!(after.contains(&("c1".into(), 6, Some(2))), "{after:?}");
+ assert!(after.contains(&("c4".into(), 8, Some(2))), "{after:?}");
+ (0..3).for_each(|_| {
+ crate::history::step(&mut b, crate::history::Stack::Undo).unwrap();
+ });
+ assert_eq!(starts(&b)[0], ("c1".into(), 0, Some(2)));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn parts_name_marks_and_follow_them_through_dup_unlink_and_copy() {
+ use crate::ops::parse_lines;
+ let dir = scratch("parts");
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 6;
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ doc.next_id = 10;
+ let mut b = Bundle::create(&dir, doc).unwrap();
+ let run = |b: &mut Bundle, text: &str| b.apply(&parse_lines(text).unwrap()).map(|_| ());
+ let parts = |b: &Bundle, cel: &str| -> Vec<(String, Vec<u32>)> {
+ match b.doc.locate(cel) {
+ Some(Loc::Cel(path, c)) => b.doc.layer_at(&path).cels()[c].parts.clone().into_iter().collect(),
+ _ => panic!("no cel {cel}"),
+ }
+ };
+ let named = |pairs: &[(&str, &[u32])]| -> Vec<(String, Vec<u32>)> {
+ pairs.iter().map(|(n, ids)| (n.to_string(), ids.to_vec())).collect()
+ };
+ run(
+ &mut b,
+ r#"{"op":"stroke","layer":"l1","path":"M1 1 L30 30","part":"leaf"}
+{"op":"stroke","layer":"l1","path":"M30 1 L1 30"}
+{"op":"stroke","layer":"l1","path":"M5 5 L9 9","part":"leaf"}
+{"op":"part","ids":["c1:s2"],"name":"stem"}"#,
+ )
+ .unwrap();
+ assert_eq!(parts(&b, "c1"), named(&[("leaf", &[1, 3]), ("stem", &[2])]));
+ run(&mut b, r#"{"op":"part","ids":["c1:s2"],"name":"leaf"}"#).unwrap();
+ assert_eq!(parts(&b, "c1"), named(&[("leaf", &[1, 3, 2])]));
+ let refused = format!(
+ "{:#}",
+ run(&mut b, r#"{"op":"part","ids":["c1:s9"],"name":"x"}"#).unwrap_err()
+ );
+ assert!(refused.contains("c1:s9 does not exist"), "{refused}");
+ run(
+ &mut b,
+ r#"{"op":"cel","dup":"c1","frame":2,"id":"c2"}
+{"op":"cel","link":"c1","frame":4,"id":"c3"}"#,
+ )
+ .unwrap();
+ run(&mut b, r#"{"op":"cel","unlink":"c3"}"#).unwrap();
+ assert_eq!(parts(&b, "c2"), parts(&b, "c1"));
+ assert_eq!(parts(&b, "c3"), parts(&b, "c1"));
+ run(
+ &mut b,
+ r#"{"op":"part","ids":["c2:s3"],"name":""}
+{"op":"copy","ids":["c1:s1","c1:s3"],"to":"c2","x":4}"#,
+ )
+ .unwrap();
+ assert_eq!(parts(&b, "c2"), named(&[("leaf", &[1, 2, 4, 5])]));
+ crate::history::step(&mut b, crate::history::Stack::Undo).unwrap();
+ assert_eq!(parts(&b, "c2"), parts(&b, "c1"));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_duplicated_layer_copies_its_drawings_links_and_mask_with_new_ids() {
+ use crate::ops::parse_lines;
+ let dir = scratch("duplicate");
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 6;
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ doc.next_id = 10;
+ let mut b = Bundle::create(&dir, doc).unwrap();
+ b.apply(
+ &parse_lines(
+ r#"{"op":"stroke","layer":"l1","path":"M1 1 L60 60"}
+{"op":"set","id":"c1","hold":2}
+{"op":"cel","link":"c1","frame":3}
+{"op":"add","mask":{"name":"m"},"in":"l1"}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let made = b
+ .apply(&parse_lines(r#"{"op":"duplicate","layer":"l1"}"#).unwrap())
+ .unwrap();
+ let copy = made.added[0].clone();
+ let layers: Vec<String> = b.doc.layers.iter().map(|l| l.id.clone()).collect();
+ assert_eq!(layers, ["l1".to_string(), copy.clone()]);
+ let dup = b.doc.layer(&copy).unwrap().clone();
+ assert_eq!(dup.name, "ink copy");
+ let cels = dup.cels();
+ assert_eq!(cels.len(), 2);
+ assert_ne!(cels[0].id, "c1");
+ assert_eq!(cels[1].link.as_deref(), Some(cels[0].id.as_str()));
+ assert_eq!(
+ b.read_marks(&copy, &cels[0].id).unwrap(),
+ b.read_marks("l1", "c1").unwrap()
+ );
+ assert!(
+ dup.mask
+ .as_ref()
+ .is_some_and(|m| m.id != b.doc.layer("l1").unwrap().mask.as_ref().unwrap().id)
+ );
+ b.doc.validate().unwrap();
+ crate::history::step(&mut b, crate::history::Stack::Undo).unwrap();
+ assert_eq!(b.doc.layers.len(), 1);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn drawings_copy_their_strokes_keep_ids_and_undo() {
+ use crate::history::{Stack, step};
+ use crate::ops::parse_lines;
+ let dir = scratch("drawings");
+ let mut doc = Document::new(256, 256);
+ doc.timeline.frames = 4;
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let mut marks = crate::stroke::marks(Synth::canvas(256.0, 256.0).strokes(3, 2));
+ marks[1].set_id(7);
+ bundle.write_marks("l1", "c1", &marks).unwrap();
+ let ops = parse_lines(
+ r#"{"op":"stroke","layer":"l1","path":"M10 10 L90 90"}
+{"op":"cel","dup":"c1","frame":2}
+{"op":"stroke","layer":"l1","path":"M20 10 L20 90"}"#,
+ )
+ .unwrap();
+ let applied = bundle.apply(&ops).unwrap();
+ let copy = applied.added[0].clone();
+ let source = bundle.read_marks("l1", "c1").unwrap();
+ let copied = bundle.read_marks("l1", &copy).unwrap();
+ assert_eq!(source.len(), 5);
+ assert_eq!(copied, source[..4].to_vec());
+ assert_eq!(copied.iter().map(Mark::id).collect::<Vec<_>>(), [0, 7, 2, 8]);
+ bundle
+ .apply(
+ &parse_lines(&format!(
+ r#"{{"op":"cel","link":"{copy}","frame":3}}
+{{"op":"rm","id":"{copy}"}}"#
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ let heir = bundle.doc.layer("l1").unwrap().cels()[1].clone();
+ assert_eq!((heir.frame, heir.link.clone()), (3, None));
+ assert_eq!(bundle.read_marks("l1", &heir.id).unwrap(), copied);
+ assert!(!bundle.strokes_path("l1", &copy).exists());
+ step(&mut bundle, Stack::Undo).unwrap();
+ assert_eq!(bundle.read_marks("l1", &copy).unwrap(), copied);
+ assert!(!bundle.strokes_path("l1", &heir.id).exists());
+ step(&mut bundle, Stack::Undo).unwrap();
+ assert!(!bundle.strokes_path("l1", &copy).exists());
+ assert_eq!(bundle.read_marks("l1", "c1").unwrap(), marks);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn copies_take_new_ids_move_on_the_way_and_undo_in_one_step() {
+ use crate::history::{Stack, step};
+ use crate::markedit::{Copied, MarkChange};
+ use crate::ops::parse_lines;
+ let dir = scratch("copies");
+ let mut doc = Document::new(256, 256);
+ doc.timeline.frames = 4;
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ doc.layers.push(Layer::paint("l2", "other", "c2"));
+ doc.next_id = 10;
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let ops = parse_lines(
+ r#"{"op":"set","id":"c1","hold":1}
+{"op":"stroke","layer":"l1","path":"M10 10 L90 10"}
+{"op":"stroke","layer":"l1","path":"M10 40 L90 40"}
+{"op":"stroke","layer":"l1","path":"M10 70 L90 70"}"#,
+ )
+ .unwrap();
+ bundle.apply(&ops).unwrap();
+ let source = bundle.read_marks("l1", "c1").unwrap();
+ let copy = parse_lines(
+ r#"{"op":"copy","ids":["c1:s3","c1:s1"],"frame":2,"x":5,"y":-4}
+{"op":"stroke","layer":"l1","path":"M50 50 L60 60"}
+{"op":"copy","ids":["c1:s4"],"to":"c2"}"#,
+ )
+ .unwrap();
+ let applied = bundle.apply(&copy).unwrap();
+ let target = bundle.doc.layer("l1").unwrap().cels()[1].clone();
+ assert_eq!((target.frame, applied.added.clone()), (2, vec![target.id.clone()]));
+ let made: Vec<Copied> = applied
+ .marks
+ .iter()
+ .flat_map(|p| p.changes.iter())
+ .flat_map(|c| match c {
+ MarkChange::Paste { made, .. } => made.clone(),
+ _ => Vec::new(),
+ })
+ .collect();
+ let pair = |cel: &str, from: u32, to: u32| Copied {
+ cel: cel.to_string(),
+ from,
+ to,
+ };
+ assert_eq!(made, [pair("c1", 1, 1), pair("c1", 3, 2), pair("c1", 4, 1)]);
+ let copied = bundle.read_marks("l1", &target.id).unwrap();
+ let first = copied[0].as_stroke().unwrap().samples[0].pos();
+ assert_eq!((copied.len(), first), (2, (15.0, 6.0)));
+ assert_eq!(copied[1].as_stroke().unwrap().samples[0].pos(), (15.0, 66.0));
+ let other = bundle.read_marks("l2", "c2").unwrap();
+ assert_eq!(other[0].as_stroke().unwrap().samples, {
+ let s = bundle.read_marks("l1", "c1").unwrap();
+ s[3].as_stroke().unwrap().samples.clone()
+ });
+ step(&mut bundle, Stack::Undo).unwrap();
+ assert_eq!(bundle.read_marks("l1", "c1").unwrap(), source);
+ assert!(bundle.read_marks("l2", "c2").unwrap().is_empty());
+ assert_eq!(bundle.doc.layer("l1").unwrap().cels().len(), 1);
+ let cut =
+ parse_lines(r#"{"op":"copy","ids":["c1:s1"],"to":"c1","cut":[[0,0],[50,0],[50,100],[0,100]]}"#).unwrap();
+ bundle.apply(&cut).unwrap();
+ let marks = bundle.read_marks("l1", "c1").unwrap();
+ assert_eq!((marks.len(), marks[3].cuts().len()), (4, 1));
+ let link = parse_lines(r#"{"op":"cel","link":"c1","frame":3,"id":"k"}"#).unwrap();
+ bundle.apply(&link).unwrap();
+ let refused = bundle.apply(&parse_lines(r#"{"op":"copy","ids":["c1:s1"],"to":"k"}"#).unwrap());
+ assert!(format!("{:#}", refused.unwrap_err()).contains("copy into c1 instead"));
+ let missing = bundle.apply(&parse_lines(r#"{"op":"copy","ids":["c1:s9"],"to":"c2"}"#).unwrap());
+ assert!(format!("{:#}", missing.unwrap_err()).contains("c1:s9 does not exist"));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn bundle_round_trip() {
+ let dir = scratch("trip");
+ let mut doc = Document::new(256, 256);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let bundle = Bundle::create(&dir, doc.clone()).unwrap();
+ let strokes = Synth::canvas(256.0, 256.0).strokes(10, 2);
+ bundle
+ .write_marks("l1", "c1", &crate::stroke::marks(strokes.clone()))
+ .unwrap();
+ let opened = Bundle::open(&dir).unwrap();
+ assert_eq!(opened.doc.rev, 1);
+ assert_eq!(opened.doc.layers, doc.layers);
+ assert_eq!(opened.read_strokes("l1", "c1").unwrap(), strokes);
+ assert!(opened.read_strokes("l1", "missing").unwrap().is_empty());
+ let stamp = opened.stamp("cli").unwrap();
+ assert_eq!(opened.read_stamp(), Some(stamp));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn v0_bundles_upgrade_on_open_and_keep_their_strokes() {
+ let dir = scratch("upgrade");
+ fs::create_dir_all(dir.join("strokes/ink")).unwrap();
+ let v0 = r##"{"format":"draw-anything/0","rev":3,"canvas":{"width":128,"height":128},
+ "layers":[{"id":"bg","name":"bg","kind":"vector","shapes":[{"type":"rect","x":0,"y":0,"w":128,"h":128,"fill":"#102030"}]},
+ {"id":"ink","name":"ink","kind":"paint"}]}"##;
+ fs::write(dir.join("doc.json"), v0).unwrap();
+ let strokes = Synth::canvas(128.0, 128.0).strokes(4, 1);
+ fs::write(
+ dir.join("strokes/ink/c0.strokes"),
+ encode_cel(&crate::stroke::marks(strokes.clone())).unwrap(),
+ )
+ .unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ assert_eq!(bundle.doc.format, crate::doc::FORMAT);
+ assert_eq!(bundle.doc.rev, 4);
+ let cel = bundle.doc.layer("ink").unwrap().cels()[0].id.clone();
+ assert_eq!(bundle.read_strokes("ink", &cel).unwrap(), strokes);
+ assert!(!dir.join("strokes/ink/c0.strokes").exists());
+ let again = Bundle::open(&dir).unwrap();
+ assert_eq!(again.doc.rev, 4);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn m1_bundles_embed_the_m1_brushes_they_use() {
+ let dir = scratch("m1");
+ let mut doc = Document::new(64, 64);
+ doc.format = "draw-anything/1".into();
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let text = serde_json::to_string(&doc).unwrap();
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("doc.json"), text).unwrap();
+ let mut synth = Synth::canvas(64.0, 64.0);
+ synth.brushes = vec!["ink".into(), "chalk".into()];
+ fs::create_dir_all(dir.join("strokes/l1")).unwrap();
+ fs::write(
+ dir.join("strokes/l1/c1.strokes"),
+ encode_cel(&crate::stroke::marks(synth.strokes(6, 3))).unwrap(),
+ )
+ .unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ assert_eq!(bundle.doc.format, crate::doc::FORMAT);
+ let embedded = bundle.brushes().unwrap();
+ assert_eq!(embedded.keys().collect::<Vec<_>>(), ["chalk", "ink"]);
+ assert_eq!(embedded["ink"], brushes::legacy_m1("ink").unwrap());
+ assert_ne!(embedded["ink"], brushes::library("ink").unwrap());
+ assert_eq!(bundle.brush("marker").unwrap(), brushes::library("marker"));
+ assert_eq!(Bundle::open(&dir).unwrap().doc.rev, bundle.doc.rev);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn strokes_embed_their_brush_on_first_use() {
+ let dir = scratch("embed");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let stroke = |brush: &str| {
+ crate::ops::parse_lines(&format!(
+ r#"{{"op":"stroke","layer":"l1","brush":"{brush}","path":"M1 1 L40 40"}}"#
+ ))
+ .unwrap()
+ };
+ bundle.apply(&stroke("marker")).unwrap();
+ assert_eq!(bundle.brushes().unwrap()["marker"], brushes::library("marker").unwrap());
+ let rev = bundle.doc.rev;
+ let err = bundle.apply(&stroke("nope")).unwrap_err().to_string();
+ assert!(err.contains("unknown brush") && err.contains("marker"), "{err}");
+ assert_eq!(Bundle::open(&dir).unwrap().doc.rev, rev);
+ assert_eq!(bundle.read_strokes("l1", "c1").unwrap().len(), 1);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn masks_clips_locks_and_lassos_go_through_ops() {
+ let dir = scratch("masks");
+ let mut doc = Document::new(128, 64);
+ doc.layers.push(Layer::paint("l1", "flat", "c1"));
+ doc.layers.push(Layer::paint("l2", "shade", "c2"));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let run = |bundle: &mut Bundle, text: &str| bundle.apply(&crate::ops::parse_lines(text).unwrap());
+ let added = run(&mut bundle, r#"{"op":"add","mask":{},"in":"l2","hide":true}"#).unwrap();
+ let mask = added.added[0].clone();
+ let shade = bundle.doc.layer("l2").unwrap();
+ let mask_cel = shade.mask.as_ref().unwrap().cels()[0].id.clone();
+ assert_eq!(shade.mask.as_ref().unwrap().name, "mask");
+ let hidden = bundle.read_marks(&mask, &mask_cel).unwrap();
+ assert_eq!(hidden[0].as_fill().unwrap().coverage.pixels(), 128 * 64);
+ assert!(run(&mut bundle, r#"{"op":"add","mask":{},"in":"l2"}"#).is_err());
+ assert!(
+ run(
+ &mut bundle,
+ r#"{"op":"mv","id":"l1","above":"MASK"}"#.replace("MASK", &mask).as_str()
+ )
+ .is_err()
+ );
+ assert!(run(&mut bundle, r#"{"op":"set","id":"l2","mask":null}"#).is_err());
+ run(&mut bundle, r#"{"op":"set","id":"l2","clip":true,"lockAlpha":true}"#).unwrap();
+ run(
+ &mut bundle,
+ r#"{"op":"stroke","layer":"l2","path":"M0 30 L120 30","size":6}
+{"op":"stroke","layer":"l1","path":"M0 10 L120 10","size":6}"#,
+ )
+ .unwrap();
+ assert!(bundle.read_marks("l2", "c2").unwrap()[0].locked());
+ assert!(!bundle.read_marks("l1", "c1").unwrap()[0].locked());
+ let line = format!(r#"{{"op":"stroke","layer":"{mask}","path":"M0 0 L10 10","brush":"eraser"}}"#);
+ run(&mut bundle, &line).unwrap();
+ assert_eq!(bundle.read_marks(&mask, &mask_cel).unwrap().len(), 2);
+ let lasso = run(
+ &mut bundle,
+ r#"{"op":"lasso","layer":"l2","polygon":[[40,0],[80,0],[80,64],[40,64]],"cut":true,"x":0,"y":20}"#,
+ )
+ .unwrap();
+ assert_eq!(lasso.marks[0].changes[0].ids(), vec![2]);
+ let marks = bundle.read_marks("l2", "c2").unwrap();
+ assert_eq!(marks.len(), 2);
+ assert!(marks.iter().all(|m| m.locked() && m.cuts().len() == 1));
+ assert!(
+ run(
+ &mut bundle,
+ r#"{"op":"lasso","layer":"l2","polygon":[[40,0],[80,0],[80,8]],"rm":true}"#
+ )
+ .unwrap_err()
+ .to_string()
+ .contains("holds no strokes")
+ );
+ run(&mut bundle, &format!(r#"{{"op":"rm","id":"{mask}"}}"#)).unwrap();
+ assert!(bundle.doc.layer("l2").unwrap().mask.is_none());
+ assert!(!bundle.strokes_path(&mask, &mask_cel).exists());
+ crate::history::step(&mut bundle, crate::history::Stack::Undo).unwrap();
+ assert_eq!(bundle.read_marks(&mask, &mask_cel).unwrap().len(), 2);
+ assert_eq!(
+ Bundle::open(&dir).unwrap().doc.layer(&mask).map(|m| m.id.clone()),
+ Some(mask)
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn apply_saves_and_drops_removed_stroke_files() {
+ let dir = scratch("apply");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .write_marks(
+ "l1",
+ "c1",
+ &crate::stroke::marks(Synth::canvas(64.0, 64.0).strokes(2, 1)),
+ )
+ .unwrap();
+ let ops = crate::ops::parse_lines(r#"{"op":"rm","id":"l1"}"#).unwrap();
+ let applied = bundle.apply(&ops).unwrap();
+ assert_eq!(applied.removed, vec!["l1"]);
+ assert!(!bundle.strokes_path("l1", "c1").exists());
+ assert_eq!(Bundle::open(&dir).unwrap().doc.rev, 2);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/core/src/color.rs b/crates/core/src/color.rs
new file mode 100644
index 0000000..e621776
--- /dev/null
+++ b/crates/core/src/color.rs
@@ -0,0 +1,105 @@
+use anyhow::{Result, bail};
+
+pub type Rgba = [f32; 4];
+
+pub fn parse_hex(text: &str) -> Result<Rgba> {
+ let hex = text.trim().trim_start_matches('#');
+ let channel = |i: usize| -> Result<f32> { Ok(u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16)? as f32 / 255.0) };
+ match hex.len() {
+ 6 => Ok([channel(0)?, channel(1)?, channel(2)?, 1.0]),
+ 8 => Ok([channel(0)?, channel(1)?, channel(2)?, channel(3)?]),
+ _ => bail!("colour {text:?} is not #rrggbb or #rrggbbaa"),
+ }
+}
+
+pub fn to_u16(c: Rgba) -> [u16; 4] {
+ c.map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16)
+}
+
+pub fn from_u16(c: [u16; 4]) -> Rgba {
+ c.map(|v| v as f32 / 65535.0)
+}
+
+pub fn to_hex(c: Rgba) -> String {
+ let [r, g, b, a] = c.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
+ match a {
+ 255 => format!("#{r:02x}{g:02x}{b:02x}"),
+ _ => format!("#{r:02x}{g:02x}{b:02x}{a:02x}"),
+ }
+}
+
+fn linear(v: f32) -> f32 {
+ match v <= 0.04045 {
+ true => v / 12.92,
+ false => libm::powf((v + 0.055) / 1.055, 2.4),
+ }
+}
+
+fn encoded(v: f32) -> f32 {
+ let v = v.clamp(0.0, 1.0);
+ match v <= 0.003_130_8 {
+ true => v * 12.92,
+ false => 1.055 * libm::powf(v, 1.0 / 2.4) - 0.055,
+ }
+}
+
+pub fn to_linear(c: Rgba) -> [f32; 3] {
+ [linear(c[0]), linear(c[1]), linear(c[2])]
+}
+
+pub fn from_linear(rgb: [f32; 3], alpha: f32) -> Rgba {
+ [encoded(rgb[0]), encoded(rgb[1]), encoded(rgb[2]), alpha]
+}
+
+pub fn to_oklab(c: Rgba) -> [f32; 3] {
+ let [r, g, b] = [linear(c[0]), linear(c[1]), linear(c[2])];
+ let l = libm::cbrtf(0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b);
+ let m = libm::cbrtf(0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b);
+ let s = libm::cbrtf(0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b);
+ [
+ 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
+ 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
+ 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
+ ]
+}
+
+pub fn from_oklab(lab: [f32; 3], alpha: f32) -> Rgba {
+ let [l, a, b] = lab;
+ let cube = |v: f32| v * v * v;
+ let l_ = cube(l + 0.396_337_78 * a + 0.215_803_76 * b);
+ let m_ = cube(l - 0.105_561_346 * a - 0.063_854_17 * b);
+ let s_ = cube(l - 0.089_484_18 * a - 1.291_485_5 * b);
+ [
+ encoded(4.076_741_7 * l_ - 3.307_711_6 * m_ + 0.230_969_94 * s_),
+ encoded(-1.268_438 * l_ + 2.609_757_4 * m_ - 0.341_319_38 * s_),
+ encoded(-0.004_196_086_3 * l_ - 0.703_418_6 * m_ + 1.707_614_7 * s_),
+ alpha,
+ ]
+}
+
+pub fn value_step(c: Rgba, by: f32) -> Rgba {
+ let [l, a, b] = to_oklab(c);
+ from_oklab([(l + by).clamp(0.0, 1.0), a + by * 0.03, b + by * 0.15], c[3])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_short_and_alpha_forms() {
+ assert_eq!(parse_hex("#ff0000").unwrap(), [1.0, 0.0, 0.0, 1.0]);
+ assert_eq!(parse_hex("00ff0080").unwrap()[3], 128.0 / 255.0);
+ assert!(parse_hex("#fff").is_err());
+ }
+
+ #[test]
+ fn oklab_round_trips_and_value_steps_go_darker_cooler_and_lighter_warmer() {
+ let c = parse_hex("#6a8f5c").unwrap();
+ assert_eq!(to_hex(from_oklab(to_oklab(c), 1.0)), "#6a8f5c");
+ let (dark, light) = (value_step(c, -0.16), value_step(c, 0.14));
+ assert!(to_oklab(dark)[0] < to_oklab(c)[0] && to_oklab(light)[0] > to_oklab(c)[0]);
+ assert!(to_oklab(dark)[2] < to_oklab(c)[2] && to_oklab(light)[2] > to_oklab(c)[2]);
+ assert_eq!(to_hex([1.0, 0.0, 0.0, 0.5]), "#ff000080");
+ }
+}
diff --git a/crates/core/src/cut.rs b/crates/core/src/cut.rs
new file mode 100644
index 0000000..014cbe7
--- /dev/null
+++ b/crates/core/src/cut.rs
@@ -0,0 +1,142 @@
+use crate::varint::{self, Reader};
+use anyhow::{Result, bail};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Keep {
+ Inside,
+ Outside,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Cut {
+ pub keep: Keep,
+ pub polygon: Vec<[f32; 2]>,
+}
+
+pub fn inside_polygon(polygon: &[[f32; 2]], (x, y): (f32, f32)) -> bool {
+ let n = polygon.len();
+ (0..n).fold(false, |inside, i| {
+ let (a, b) = (polygon[i], polygon[(i + n - 1) % n]);
+ if (a[1] > y) != (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0] {
+ !inside
+ } else {
+ inside
+ }
+ })
+}
+
+pub fn crossings(polygon: &[[f32; 2]], y: f32) -> Vec<f32> {
+ let n = polygon.len();
+ let mut xs: Vec<f32> = (0..n)
+ .filter_map(|i| {
+ let (a, b) = (polygon[i], polygon[(i + n - 1) % n]);
+ ((a[1] > y) != (b[1] > y)).then(|| (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])
+ })
+ .collect();
+ xs.sort_by(f32::total_cmp);
+ xs
+}
+
+pub fn polygon_box(polygon: &[[f32; 2]]) -> Option<[f32; 4]> {
+ let first = polygon.first()?;
+ Some(
+ polygon
+ .iter()
+ .fold([first[0], first[1], first[0], first[1]], |[x0, y0, x1, y1], p| {
+ [x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1])]
+ }),
+ )
+}
+
+impl Cut {
+ pub fn keeps(&self, at: (f32, f32)) -> bool {
+ inside_polygon(&self.polygon, at) == (self.keep == Keep::Inside)
+ }
+
+ pub fn map(&mut self, f: impl Fn([f32; 2]) -> [f32; 2]) {
+ self.polygon.iter_mut().for_each(|p| *p = f(*p));
+ }
+}
+
+pub fn keeps(cuts: &[Cut], at: (f32, f32)) -> bool {
+ cuts.iter().all(|c| c.keeps(at))
+}
+
+pub fn clip_bounds(cuts: &[Cut], bounds: [f32; 4]) -> Option<[f32; 4]> {
+ cuts.iter()
+ .filter(|c| c.keep == Keep::Inside)
+ .filter_map(|c| polygon_box(&c.polygon))
+ .try_fold(bounds, |[x0, y0, x1, y1], [a0, b0, a1, b1]| {
+ let clipped = [x0.max(a0), y0.max(b0), x1.min(a1), y1.min(b1)];
+ (clipped[0] < clipped[2] && clipped[1] < clipped[3]).then_some(clipped)
+ })
+}
+
+pub fn encode(out: &mut Vec<u8>, cuts: &[Cut]) {
+ varint::put(out, cuts.len() as u64);
+ cuts.iter().for_each(|cut| {
+ out.push(match cut.keep {
+ Keep::Inside => 0,
+ Keep::Outside => 1,
+ });
+ varint::put(out, cut.polygon.len() as u64);
+ cut.polygon
+ .iter()
+ .flatten()
+ .for_each(|v| out.extend_from_slice(&v.to_le_bytes()));
+ });
+}
+
+pub fn decode(reader: &mut Reader) -> Result<Vec<Cut>> {
+ let count = reader.varint()? as usize;
+ (0..count)
+ .map(|_| {
+ let keep = match reader.u8()? {
+ 0 => Keep::Inside,
+ 1 => Keep::Outside,
+ other => bail!("unknown cut side {other}"),
+ };
+ let n = reader.varint()? as usize;
+ let polygon = (0..n)
+ .map(|_| Ok([reader.f32()?, reader.f32()?]))
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Cut { keep, polygon })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn square(keep: Keep) -> Cut {
+ Cut {
+ keep,
+ polygon: vec![[10.0, 10.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]],
+ }
+ }
+
+ #[test]
+ fn cuts_keep_one_side_and_round_trip() {
+ let inside = square(Keep::Inside);
+ let outside = square(Keep::Outside);
+ assert!(inside.keeps((20.0, 20.0)) && !inside.keeps((60.0, 20.0)));
+ assert!(!outside.keeps((20.0, 20.0)) && outside.keeps((60.0, 20.0)));
+ assert!(!keeps(&[inside.clone(), outside.clone()], (20.0, 20.0)));
+ assert_eq!(
+ clip_bounds(std::slice::from_ref(&inside), [0.0, 0.0, 30.0, 100.0]),
+ Some([10.0, 10.0, 30.0, 50.0])
+ );
+ assert_eq!(clip_bounds(std::slice::from_ref(&inside), [60.0, 0.0, 80.0, 5.0]), None);
+ assert_eq!(
+ clip_bounds(std::slice::from_ref(&outside), [60.0, 0.0, 80.0, 5.0]),
+ Some([60.0, 0.0, 80.0, 5.0])
+ );
+ assert_eq!(crossings(&inside.polygon, 20.0), vec![10.0, 50.0]);
+ let mut bytes = Vec::new();
+ encode(&mut bytes, &[inside.clone(), outside.clone()]);
+ let mut reader = Reader::new(&bytes);
+ assert_eq!(decode(&mut reader).unwrap(), vec![inside, outside]);
+ assert!(reader.done());
+ }
+}
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
new file mode 100644
index 0000000..5f30ccf
--- /dev/null
+++ b/crates/core/src/doc.rs
@@ -0,0 +1,1411 @@
+use crate::color::parse_hex;
+use crate::generators::{Mirror, Picture, Repeat, Scatter, Text};
+use crate::look::{Adjustment, Atmosphere, Effect, Rays};
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+use std::borrow::Cow;
+use std::collections::{BTreeMap, BTreeSet};
+
+pub const FORMAT: &str = "draw-anything/8";
+pub const MAX_SIZE: u32 = 16384;
+pub const MASK: usize = usize::MAX;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Document {
+ pub format: String,
+ pub rev: u64,
+ pub canvas: Canvas,
+ #[serde(default)]
+ pub timeline: Timeline,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub palette: Vec<Swatch>,
+ pub layers: Vec<Layer>,
+ #[serde(default, skip_serializing_if = "Exports::is_empty")]
+ pub export: Exports,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub atmosphere: Option<Atmosphere>,
+ #[serde(default)]
+ pub next_id: u64,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Exports {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub godot: Option<String>,
+}
+
+impl Exports {
+ pub fn is_empty(&self) -> bool {
+ self.godot.is_none()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Canvas {
+ pub width: u32,
+ pub height: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub background: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Swatch {
+ pub color: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub name: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Timeline {
+ pub fps: u32,
+ pub frames: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub origin: Option<[f32; 2]>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub clips: Vec<Clip>,
+}
+
+impl Default for Timeline {
+ fn default() -> Self {
+ Self {
+ fps: 12,
+ frames: 1,
+ origin: None,
+ clips: Vec::new(),
+ }
+ }
+}
+
+impl Timeline {
+ pub fn clip(&self, name: &str) -> Option<&Clip> {
+ self.clips.iter().find(|c| c.name == name)
+ }
+
+ pub fn clip_at(&self, frame: u32) -> Option<&Clip> {
+ self.clips.iter().find(|c| c.from <= frame && frame <= c.to)
+ }
+
+ pub fn fps_of(&self, clip: &Clip) -> u32 {
+ clip.fps.unwrap_or(self.fps)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Clip {
+ pub name: String,
+ pub from: u32,
+ pub to: u32,
+ #[serde(default, rename = "loop")]
+ pub looping: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fps: Option<u32>,
+}
+
+impl Clip {
+ pub fn new(name: &str, from: u32, to: u32, looping: bool) -> Self {
+ Self {
+ name: name.to_string(),
+ from,
+ to,
+ looping,
+ fps: None,
+ }
+ }
+
+ pub fn frames(&self) -> u32 {
+ self.to - self.from + 1
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Layer {
+ pub id: String,
+ pub name: String,
+ #[serde(flatten)]
+ pub content: LayerContent,
+ #[serde(default = "one")]
+ pub opacity: f32,
+ #[serde(default)]
+ pub blend: Blend,
+ #[serde(default = "yes")]
+ pub visible: bool,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub locked: bool,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub clip: bool,
+ #[serde(default, rename = "lockAlpha", skip_serializing_if = "is_false")]
+ pub lock_alpha: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mask: Option<Box<Layer>>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub effects: Vec<Effect>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub depth: Option<f32>,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub reference: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "lowercase")]
+pub enum LayerContent {
+ Paint {
+ #[serde(default)]
+ cels: Vec<Cel>,
+ },
+ Vector {
+ #[serde(default)]
+ cels: Vec<Cel>,
+ },
+ Group {
+ #[serde(default)]
+ children: Vec<Layer>,
+ },
+ Adjust {
+ adjust: Adjustment,
+ },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum Kind {
+ Paint,
+ Vector,
+ Group,
+ Adjust,
+}
+
+impl Kind {
+ pub fn name(self) -> &'static str {
+ match self {
+ Kind::Paint => "paint",
+ Kind::Vector => "vector",
+ Kind::Group => "group",
+ Kind::Adjust => "adjust",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Blend {
+ #[default]
+ Normal,
+ Multiply,
+ Screen,
+ Overlay,
+ Add,
+ ColorDodge,
+ SoftLight,
+ HardLight,
+ Lighten,
+ Darken,
+ Color,
+ Luminosity,
+}
+
+impl Blend {
+ pub const ALL: [Blend; 12] = [
+ Blend::Normal,
+ Blend::Multiply,
+ Blend::Screen,
+ Blend::Overlay,
+ Blend::Add,
+ Blend::ColorDodge,
+ Blend::SoftLight,
+ Blend::HardLight,
+ Blend::Lighten,
+ Blend::Darken,
+ Blend::Color,
+ Blend::Luminosity,
+ ];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Blend::Normal => "normal",
+ Blend::Multiply => "multiply",
+ Blend::Screen => "screen",
+ Blend::Overlay => "overlay",
+ Blend::Add => "add",
+ Blend::ColorDodge => "color-dodge",
+ Blend::SoftLight => "soft-light",
+ Blend::HardLight => "hard-light",
+ Blend::Lighten => "lighten",
+ Blend::Darken => "darken",
+ Blend::Color => "color",
+ Blend::Luminosity => "luminosity",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Cel {
+ pub id: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub hold: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub link: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tween: Option<Tween>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub nodes: Vec<Node>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub parts: BTreeMap<String, Vec<u32>>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Tween {
+ pub from: String,
+ pub to: String,
+ pub t: f32,
+ #[serde(default, rename = "match", skip_serializing_if = "String::is_empty")]
+ pub matching: String,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub pairs: Vec<[u32; 2]>,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub made: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub unpaired: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Node {
+ pub id: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub name: String,
+ #[serde(flatten)]
+ pub shape: Shape,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fill: Option<Paint>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub stroke: Option<StrokeStyle>,
+ #[serde(default, skip_serializing_if = "Transform::is_identity")]
+ pub transform: Transform,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub opacity: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub blur: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub clip: Option<String>,
+ #[serde(default = "yes", skip_serializing_if = "is_true")]
+ pub visible: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum Shape {
+ Rect {
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ radius: f32,
+ },
+ Ellipse {
+ cx: f32,
+ cy: f32,
+ rx: f32,
+ ry: f32,
+ },
+ Path {
+ d: String,
+ },
+ Group {
+ #[serde(default)]
+ children: Vec<Node>,
+ },
+ Rays(Rays),
+ Image(Picture),
+ Scatter(Scatter),
+ Repeat(Repeat),
+ Mirror(Mirror),
+ Text(Text),
+}
+
+impl Shape {
+ pub fn children(&self) -> &[Node] {
+ match self {
+ Shape::Group { children }
+ | Shape::Scatter(Scatter { children, .. })
+ | Shape::Repeat(Repeat { children, .. })
+ | Shape::Mirror(Mirror { children, .. }) => children,
+ _ => &[],
+ }
+ }
+
+ pub fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
+ match self {
+ Shape::Group { children }
+ | Shape::Scatter(Scatter { children, .. })
+ | Shape::Repeat(Repeat { children, .. })
+ | Shape::Mirror(Mirror { children, .. }) => Some(children),
+ _ => None,
+ }
+ }
+
+ pub fn generates(&self) -> bool {
+ matches!(self, Shape::Scatter(_) | Shape::Repeat(_) | Shape::Mirror(_))
+ }
+
+ pub fn validate(&self) -> Result<()> {
+ match self {
+ Shape::Rays(r) => r.validate(),
+ Shape::Image(p) => p.validate(),
+ Shape::Scatter(s) => s.validate(),
+ Shape::Repeat(r) => r.validate(),
+ Shape::Text(t) => t.validate(),
+ _ => Ok(()),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum Paint {
+ Solid(String),
+ Linear { linear: Linear },
+ Radial { radial: Radial },
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Linear {
+ pub from: [f32; 2],
+ pub to: [f32; 2],
+ pub stops: Vec<Stop>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Radial {
+ pub center: [f32; 2],
+ pub radius: f32,
+ pub stops: Vec<Stop>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Stop(pub f32, pub String);
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct StrokeStyle {
+ #[serde(default = "black")]
+ pub paint: Paint,
+ #[serde(default = "one")]
+ pub width: f32,
+ #[serde(default)]
+ pub cap: Cap,
+ #[serde(default)]
+ pub join: Join,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub dash: Vec<f32>,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Cap {
+ Butt,
+ #[default]
+ Round,
+ Square,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Join {
+ Miter,
+ #[default]
+ Round,
+ Bevel,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Transform {
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub x: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub y: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub rotate: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub sx: f32,
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub sy: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pivot: Option<[f32; 2]>,
+}
+
+impl Default for Transform {
+ fn default() -> Self {
+ Self {
+ x: 0.0,
+ y: 0.0,
+ rotate: 0.0,
+ sx: 1.0,
+ sy: 1.0,
+ pivot: None,
+ }
+ }
+}
+
+impl Transform {
+ pub fn is_identity(&self) -> bool {
+ *self == Self::default()
+ }
+}
+
+fn one() -> f32 {
+ 1.0
+}
+
+fn yes() -> bool {
+ true
+}
+
+fn black() -> Paint {
+ Paint::Solid("#000000".into())
+}
+
+fn is_one(v: &f32) -> bool {
+ *v == 1.0
+}
+
+fn is_zero(v: &f32) -> bool {
+ *v == 0.0
+}
+
+fn is_true(v: &bool) -> bool {
+ *v
+}
+
+fn is_false(v: &bool) -> bool {
+ !*v
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Loc {
+ Layer(Vec<usize>),
+ Cel(Vec<usize>, usize),
+ Node(Vec<usize>, usize, Vec<usize>),
+}
+
+pub enum Item<'a> {
+ Layer(&'a Layer),
+ Cel(&'a Layer, &'a Cel),
+ Node(&'a Layer, &'a Cel, &'a Node),
+}
+
+impl Layer {
+ fn with(id: &str, name: &str, content: LayerContent) -> Self {
+ Self {
+ id: id.to_string(),
+ name: name.to_string(),
+ content,
+ opacity: 1.0,
+ blend: Blend::Normal,
+ visible: true,
+ locked: false,
+ clip: false,
+ lock_alpha: false,
+ mask: None,
+ effects: Vec::new(),
+ depth: None,
+ reference: false,
+ }
+ }
+
+ pub fn paint(id: &str, name: &str, cel: &str) -> Self {
+ Self::with(
+ id,
+ name,
+ LayerContent::Paint {
+ cels: vec![Cel::at(cel, 0)],
+ },
+ )
+ }
+
+ pub fn vector(id: &str, name: &str, cel: &str, nodes: Vec<Node>) -> Self {
+ let mut first = Cel::at(cel, 0);
+ first.nodes = nodes;
+ Self::with(id, name, LayerContent::Vector { cels: vec![first] })
+ }
+
+ pub fn group(id: &str, name: &str, children: Vec<Layer>) -> Self {
+ Self::with(id, name, LayerContent::Group { children })
+ }
+
+ pub fn adjust(id: &str, name: &str, adjust: Adjustment) -> Self {
+ Self::with(id, name, LayerContent::Adjust { adjust })
+ }
+
+ pub fn kind(&self) -> Kind {
+ match self.content {
+ LayerContent::Paint { .. } => Kind::Paint,
+ LayerContent::Vector { .. } => Kind::Vector,
+ LayerContent::Group { .. } => Kind::Group,
+ LayerContent::Adjust { .. } => Kind::Adjust,
+ }
+ }
+
+ pub fn adjustment(&self) -> Option<&Adjustment> {
+ match &self.content {
+ LayerContent::Adjust { adjust } => Some(adjust),
+ _ => None,
+ }
+ }
+
+ pub fn reads_under(&self) -> bool {
+ self.adjustment().is_some_and(Adjustment::reads_under)
+ }
+
+ pub fn cels(&self) -> &[Cel] {
+ match &self.content {
+ LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,
+ LayerContent::Group { .. } | LayerContent::Adjust { .. } => &[],
+ }
+ }
+
+ pub fn cels_mut(&mut self) -> Option<&mut Vec<Cel>> {
+ match &mut self.content {
+ LayerContent::Paint { cels } | LayerContent::Vector { cels } => Some(cels),
+ LayerContent::Group { .. } | LayerContent::Adjust { .. } => None,
+ }
+ }
+
+ pub fn children(&self) -> &[Layer] {
+ match &self.content {
+ LayerContent::Group { children } => children,
+ _ => &[],
+ }
+ }
+
+ pub fn child(&self, index: usize) -> Option<&Layer> {
+ match index {
+ MASK => self.mask.as_deref(),
+ i => self.children().get(i),
+ }
+ }
+
+ fn child_mut(&mut self, index: usize) -> &mut Layer {
+ match (index, &mut self.content) {
+ (MASK, _) => self
+ .mask
+ .as_deref_mut()
+ .expect("layer path runs through a missing mask"),
+ (i, LayerContent::Group { children }) => &mut children[i],
+ _ => panic!("layer path runs through a non-group layer"),
+ }
+ }
+
+ pub fn mask_at(&self, frame: u32) -> Option<(&Layer, &Cel)> {
+ let mask = self.mask.as_deref().filter(|m| m.visible)?;
+ Some((mask, mask.content_at(frame)?))
+ }
+
+ pub fn cel_at(&self, frame: u32) -> Option<&Cel> {
+ let cel = self.cels().iter().rev().find(|c| c.frame <= frame)?;
+ match cel.hold {
+ Some(hold) if frame >= cel.frame + hold => None,
+ _ => Some(cel),
+ }
+ }
+
+ pub fn content_of<'a>(&'a self, cel: &'a Cel) -> &'a Cel {
+ cel.link
+ .as_ref()
+ .and_then(|id| self.cels().iter().find(|c| &c.id == id))
+ .unwrap_or(cel)
+ }
+
+ pub fn content_at(&self, frame: u32) -> Option<&Cel> {
+ self.cel_at(frame).map(|c| self.content_of(c))
+ }
+}
+
+impl Cel {
+ pub fn at(id: &str, frame: u32) -> Self {
+ Self {
+ id: id.to_string(),
+ frame,
+ hold: None,
+ link: None,
+ tween: None,
+ nodes: Vec::new(),
+ parts: BTreeMap::new(),
+ }
+ }
+
+ pub fn part_of(&self, id: u32) -> Option<&str> {
+ self.parts
+ .iter()
+ .find(|(_, ids)| ids.contains(&id))
+ .map(|(name, _)| name.as_str())
+ }
+
+ pub fn set_part(&mut self, name: &str, ids: &[u32]) {
+ self.parts
+ .values_mut()
+ .for_each(|list| list.retain(|i| !ids.contains(i)));
+ if !name.is_empty() {
+ let list = self.parts.entry(name.to_string()).or_default();
+ list.extend(ids.iter().filter(|i| !list.contains(i)).copied().collect::<Vec<_>>());
+ }
+ self.parts.retain(|_, list| !list.is_empty());
+ }
+}
+
+impl Node {
+ pub fn new(id: &str, shape: Shape) -> Self {
+ Self {
+ id: id.to_string(),
+ name: String::new(),
+ shape,
+ fill: None,
+ stroke: None,
+ transform: Transform::default(),
+ opacity: 1.0,
+ blur: 0.0,
+ clip: None,
+ visible: true,
+ }
+ }
+
+ pub fn filled(mut self, hex: &str) -> Self {
+ self.fill = Some(Paint::Solid(hex.to_string()));
+ self
+ }
+
+ pub fn children(&self) -> &[Node] {
+ self.shape.children()
+ }
+
+ pub fn type_name(&self) -> &'static str {
+ match self.shape {
+ Shape::Rect { .. } => "rect",
+ Shape::Ellipse { .. } => "ellipse",
+ Shape::Path { .. } => "path",
+ Shape::Group { .. } => "group",
+ Shape::Rays(_) => "rays",
+ Shape::Image(_) => "image",
+ Shape::Scatter(_) => "scatter",
+ Shape::Repeat(_) => "repeat",
+ Shape::Mirror(_) => "mirror",
+ Shape::Text(_) => "text",
+ }
+ }
+}
+
+fn walk_layers<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) {
+ layers.iter().for_each(|l| {
+ out.push(l);
+ out.extend(l.mask.as_deref());
+ walk_layers(l.children(), out);
+ });
+}
+
+fn walk_nodes<'a>(nodes: &'a [Node], out: &mut Vec<&'a Node>) {
+ nodes.iter().for_each(|n| {
+ out.push(n);
+ walk_nodes(n.children(), out);
+ });
+}
+
+fn find_node(nodes: &[Node], id: &str, path: &mut Vec<usize>) -> bool {
+ nodes.iter().enumerate().any(|(i, n)| {
+ path.push(i);
+ if n.id == id || find_node(n.children(), id, path) {
+ return true;
+ }
+ path.pop();
+ false
+ })
+}
+
+fn find_here(layer: &Layer, id: &str, path: &[usize]) -> Option<Loc> {
+ if layer.id == id {
+ return Some(Loc::Layer(path.to_vec()));
+ }
+ layer.cels().iter().enumerate().find_map(|(c, cel)| {
+ if cel.id == id {
+ return Some(Loc::Cel(path.to_vec(), c));
+ }
+ let mut nodes = Vec::new();
+ find_node(&cel.nodes, id, &mut nodes).then(|| Loc::Node(path.to_vec(), c, nodes))
+ })
+}
+
+fn find_in(layers: &[Layer], id: &str, path: &mut Vec<usize>) -> Option<Loc> {
+ layers.iter().enumerate().find_map(|(i, layer)| {
+ path.push(i);
+ let found = find_here(layer, id, path)
+ .or_else(|| {
+ let mask = layer.mask.as_deref()?;
+ path.push(MASK);
+ let found = find_here(mask, id, path);
+ path.pop();
+ found
+ })
+ .or_else(|| find_in(layer.children(), id, path));
+ path.pop();
+ found
+ })
+}
+
+pub fn valid_id(id: &str) -> bool {
+ !id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+pub fn check_color(text: &str) -> Result<()> {
+ if text == "none" {
+ return Ok(());
+ }
+ parse_hex(text).map(|_| ())
+}
+
+fn check_paint(paint: &Paint) -> Result<()> {
+ let stops = match paint {
+ Paint::Solid(text) => return check_color(text),
+ Paint::Linear { linear } => &linear.stops,
+ Paint::Radial { radial } => {
+ if radial.radius <= 0.0 {
+ bail!("radial gradient radius must be positive");
+ }
+ &radial.stops
+ }
+ };
+ if stops.is_empty() {
+ bail!("a gradient needs at least one stop");
+ }
+ stops.iter().try_for_each(|Stop(at, color)| {
+ if !(0.0..=1.0).contains(at) {
+ bail!("gradient stop {at} is outside 0..1");
+ }
+ parse_hex(color).map(|_| ())
+ })
+}
+
+fn check_node(node: &Node) -> Result<()> {
+ let context = || format!("node {}", node.id);
+ if !(0.0..=1.0).contains(&node.opacity) {
+ bail!("{}: opacity {} is outside 0..1", context(), node.opacity);
+ }
+ if !(0.0..=500.0).contains(&node.blur) {
+ bail!("{}: blur {} is outside 0..500", context(), node.blur);
+ }
+ match &node.shape {
+ Shape::Rect { w, h, radius, .. } if *w < 0.0 || *h < 0.0 || *radius < 0.0 => {
+ bail!("{}: width, height and radius cannot be negative", context())
+ }
+ Shape::Ellipse { rx, ry, .. } if *rx < 0.0 || *ry < 0.0 => {
+ bail!("{}: radii cannot be negative", context())
+ }
+ Shape::Path { d } if d.trim().is_empty() => bail!("{}: empty path", context()),
+ _ => {}
+ }
+ if node.clip.as_ref().is_some_and(|c| c.trim().is_empty()) {
+ bail!("{}: empty clip path", context());
+ }
+ node.fill.iter().try_for_each(check_paint).with_context(context)?;
+ if let Some(stroke) = &node.stroke {
+ check_paint(&stroke.paint).with_context(context)?;
+ if stroke.width < 0.0 {
+ bail!("{}: stroke width cannot be negative", context());
+ }
+ }
+ Ok(())
+}
+
+fn check_cels(layer: &Layer) -> Result<()> {
+ let cels = layer.cels();
+ cels.windows(2).try_for_each(|pair| {
+ let (a, b) = (&pair[0], &pair[1]);
+ if a.frame >= b.frame {
+ bail!("layer {}: cels {} and {} are not in frame order", layer.id, a.id, b.id);
+ }
+ if a.hold.is_some_and(|h| a.frame + h > b.frame) {
+ bail!("layer {}: cel {} overlaps cel {}", layer.id, a.id, b.id);
+ }
+ Ok(())
+ })?;
+ cels.iter().try_for_each(|cel| {
+ if cel.hold == Some(0) {
+ bail!("cel {}: hold must be at least 1", cel.id);
+ }
+ if let Some(target) = &cel.link {
+ let Some(source) = cels.iter().find(|c| &c.id == target) else {
+ bail!(
+ "cel {} links to {target}, which is not a cel of layer {}",
+ cel.id,
+ layer.id
+ );
+ };
+ if source.link.is_some() {
+ bail!("cel {} links to {target}, which is itself a link", cel.id);
+ }
+ if !cel.nodes.is_empty() {
+ bail!("cel {} is a link and cannot hold nodes", cel.id);
+ }
+ if cel.tween.is_some() {
+ bail!("cel {} is a link and cannot be an in-between", cel.id);
+ }
+ }
+ if let Some(tween) = &cel.tween
+ && !(tween.t > 0.0 && tween.t < 1.0)
+ {
+ bail!(
+ "cel {}: an in-between's t must be between 0 and 1, not {}",
+ cel.id,
+ tween.t
+ );
+ }
+ if layer.kind() == Kind::Paint && !cel.nodes.is_empty() {
+ bail!(
+ "cel {} belongs to paint layer {} and cannot hold nodes",
+ cel.id,
+ layer.id
+ );
+ }
+ let mut nodes = Vec::new();
+ walk_nodes(&cel.nodes, &mut nodes);
+ nodes.iter().try_for_each(|n| check_node(n))
+ })
+}
+
+fn check_mask(owner: &Layer, mask: &Layer) -> Result<()> {
+ let context = format!("mask {} of layer {}", mask.id, owner.id);
+ if mask.kind() != Kind::Paint {
+ bail!("{context} must be a paint layer");
+ }
+ if mask.mask.is_some() || mask.clip {
+ bail!("{context} cannot have a mask or clip");
+ }
+ if mask.opacity != 1.0 || mask.blend != Blend::Normal {
+ bail!("{context} keeps opacity 1 and blend normal; hide it with visible=false");
+ }
+ Ok(())
+}
+
+impl Document {
+ pub fn new(width: u32, height: u32) -> Self {
+ Self {
+ format: FORMAT.to_string(),
+ rev: 0,
+ canvas: Canvas {
+ width,
+ height,
+ background: None,
+ },
+ timeline: Timeline::default(),
+ palette: Vec::new(),
+ layers: Vec::new(),
+ export: Exports::default(),
+ atmosphere: None,
+ next_id: 0,
+ }
+ }
+
+ pub fn all_layers(&self) -> Vec<&Layer> {
+ let mut out = Vec::new();
+ walk_layers(&self.layers, &mut out);
+ out
+ }
+
+ pub fn ids(&self) -> BTreeSet<String> {
+ self.all_layers()
+ .iter()
+ .flat_map(|layer| {
+ let mut nodes = Vec::new();
+ layer.cels().iter().for_each(|c| walk_nodes(&c.nodes, &mut nodes));
+ std::iter::once(layer.id.clone())
+ .chain(layer.cels().iter().map(|c| c.id.clone()))
+ .chain(nodes.into_iter().map(|n| n.id.clone()))
+ .collect::<Vec<_>>()
+ })
+ .collect()
+ }
+
+ pub fn alloc_id(&mut self, prefix: char) -> String {
+ let mut taken = self.ids();
+ self.alloc_id_in(prefix, &mut taken)
+ }
+
+ pub fn alloc_id_in(&mut self, prefix: char, taken: &mut BTreeSet<String>) -> String {
+ loop {
+ self.next_id += 1;
+ let id = format!("{prefix}{}", self.next_id);
+ if taken.insert(id.clone()) {
+ return id;
+ }
+ }
+ }
+
+ pub fn locate(&self, id: &str) -> Option<Loc> {
+ find_in(&self.layers, id, &mut Vec::new())
+ }
+
+ pub fn locate_path(&self, path: &[usize]) -> Option<&Layer> {
+ let (first, rest) = path.split_first()?;
+ rest.iter()
+ .try_fold(self.layers.get(*first)?, |layer, &i| layer.child(i))
+ }
+
+ pub fn layer_at(&self, path: &[usize]) -> &Layer {
+ self.locate_path(path).expect("layer path leads nowhere")
+ }
+
+ pub fn layer_at_mut(&mut self, path: &[usize]) -> &mut Layer {
+ let (first, rest) = path.split_first().expect("empty layer path");
+ rest.iter()
+ .fold(&mut self.layers[*first], |layer, &i| layer.child_mut(i))
+ }
+
+ pub fn is_mask(&self, id: &str) -> bool {
+ matches!(self.locate(id), Some(Loc::Layer(path)) if path.last() == Some(&MASK))
+ }
+
+ pub fn layer_list_mut(&mut self, parent: &[usize]) -> Option<&mut Vec<Layer>> {
+ if parent.is_empty() {
+ return Some(&mut self.layers);
+ }
+ match &mut self.layer_at_mut(parent).content {
+ LayerContent::Group { children } => Some(children),
+ _ => None,
+ }
+ }
+
+ pub fn item(&self, id: &str) -> Option<Item<'_>> {
+ Some(match self.locate(id)? {
+ Loc::Layer(path) => Item::Layer(self.layer_at(&path)),
+ Loc::Cel(path, c) => {
+ let layer = self.layer_at(&path);
+ Item::Cel(layer, &layer.cels()[c])
+ }
+ Loc::Node(path, c, nodes) => {
+ let layer = self.layer_at(&path);
+ let cel = &layer.cels()[c];
+ let (first, rest) = nodes.split_first()?;
+ let node = rest.iter().fold(&cel.nodes[*first], |n, &i| &n.children()[i]);
+ Item::Node(layer, cel, node)
+ }
+ })
+ }
+
+ pub fn layer(&self, id: &str) -> Option<&Layer> {
+ match self.item(id)? {
+ Item::Layer(layer) => Some(layer),
+ _ => None,
+ }
+ }
+
+ pub fn find_layer(&self, key: &str) -> Result<&Layer> {
+ if let Some(layer) = self.layer(key) {
+ return Ok(layer);
+ }
+ let named: Vec<&Layer> = self.all_layers().into_iter().filter(|l| l.name == key).collect();
+ match named[..] {
+ [layer] => Ok(layer),
+ [] => bail!(
+ "no layer {key:?}: layers are {}",
+ self.all_layers()
+ .iter()
+ .map(|l| format!("{} ({})", l.id, l.name))
+ .collect::<Vec<_>>()
+ .join(", ")
+ ),
+ _ => bail!("{} layers are named {key:?}; use the layer id", named.len()),
+ }
+ }
+
+ pub fn paint_content_at(&self, frame: u32) -> Vec<(&Layer, &Cel)> {
+ self.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Paint)
+ .filter_map(|l| l.content_at(frame).map(|c| (l, c)))
+ .collect()
+ }
+
+ pub fn paint_cels(&self) -> Vec<(&Layer, &Cel)> {
+ self.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Paint)
+ .flat_map(|l| l.cels().iter().filter(|c| c.link.is_none()).map(move |c| (l, c)))
+ .collect()
+ }
+
+ pub fn swatch(&self, key: &str) -> Option<usize> {
+ let key = key.trim();
+ self.palette
+ .iter()
+ .position(|s| !s.name.is_empty() && s.name == key)
+ .or_else(|| {
+ self.palette
+ .iter()
+ .position(|s| key.starts_with('#') && s.color.eq_ignore_ascii_case(key))
+ })
+ .or_else(|| key.parse::<usize>().ok().filter(|i| *i < self.palette.len()))
+ }
+
+ pub fn effects_of<'a>(&self, layer: &'a Layer) -> Cow<'a, [Effect]> {
+ match (layer.depth, &self.atmosphere) {
+ (Some(depth), Some(air)) if depth > 0.0 => Cow::Owned(
+ layer
+ .effects
+ .iter()
+ .cloned()
+ .chain(air.effects(depth, self.canvas.height as f32))
+ .collect(),
+ ),
+ _ => Cow::Borrowed(&layer.effects),
+ }
+ }
+
+ pub fn resolve_color(&self, text: &str) -> Result<String> {
+ if text.trim().starts_with('#') {
+ parse_hex(text)?;
+ return Ok(text.trim().to_string());
+ }
+ match self
+ .palette
+ .iter()
+ .find(|s| !s.name.is_empty() && s.name == text.trim())
+ {
+ Some(swatch) => Ok(swatch.color.clone()),
+ None => {
+ let names: Vec<&str> = self
+ .palette
+ .iter()
+ .map(|s| s.name.as_str())
+ .filter(|n| !n.is_empty())
+ .collect();
+ if names.is_empty() {
+ bail!("colour {text:?} is not #rrggbb, #rrggbbaa or a palette name (the palette has no names)");
+ }
+ bail!(
+ "colour {text:?} is not #rrggbb, #rrggbbaa or a palette name: {}",
+ names.join(", ")
+ )
+ }
+ }
+ }
+
+ pub fn validate(&self) -> Result<()> {
+ if self.format != FORMAT {
+ bail!("format {} is not {FORMAT}", self.format);
+ }
+ let (w, h) = (self.canvas.width, self.canvas.height);
+ if w == 0 || h == 0 || w > MAX_SIZE || h > MAX_SIZE {
+ bail!("canvas {w}x{h} must be between 1 and {MAX_SIZE} on each side");
+ }
+ if let Some(bg) = &self.canvas.background {
+ check_color(bg).context("canvas background")?;
+ }
+ let mut swatch_names = BTreeSet::new();
+ self.palette.iter().try_for_each(|swatch| {
+ parse_hex(&swatch.color).with_context(|| format!("palette colour {}", swatch.color))?;
+ if swatch.name.starts_with('#') {
+ bail!("palette name {} cannot start with #", swatch.name);
+ }
+ if !swatch.name.is_empty() && !swatch_names.insert(&swatch.name) {
+ bail!("palette name {} is used twice", swatch.name);
+ }
+ Ok(())
+ })?;
+ let t = &self.timeline;
+ if t.fps == 0 || t.fps > 240 || t.frames == 0 {
+ bail!("timeline needs 1 to 240 fps and at least one frame");
+ }
+ let mut names = BTreeSet::new();
+ t.clips.iter().try_for_each(|clip| {
+ if clip.from > clip.to || clip.to >= t.frames {
+ bail!(
+ "clip {} spans frames {} to {} outside 0 to {}",
+ clip.name,
+ clip.from,
+ clip.to,
+ t.frames - 1
+ );
+ }
+ if !names.insert(&clip.name) {
+ bail!("clip name {} is used twice", clip.name);
+ }
+ if clip.name.trim().is_empty() {
+ bail!("a clip needs a name");
+ }
+ if clip.fps.is_some_and(|f| f == 0 || f > 240) {
+ bail!("clip {} needs 1 to 240 fps", clip.name);
+ }
+ Ok(())
+ })?;
+ if t.origin.is_some_and(|o| !o.iter().all(|v| v.is_finite())) {
+ bail!("timeline origin must be two numbers");
+ }
+ if self.export.godot.as_ref().is_some_and(|g| g.trim().is_empty()) {
+ bail!("export.godot must be a folder");
+ }
+ if let Some(air) = &self.atmosphere {
+ air.validate().context("atmosphere")?;
+ }
+ let layers = self.all_layers();
+ if let Some(deep) = layers
+ .iter()
+ .find(|l| l.depth.is_some() && !self.layers.iter().any(|t| t.id == l.id))
+ {
+ bail!(
+ "layer {}: depth is for layers at the top of the stack (the planes)",
+ deep.id
+ );
+ }
+ let mut seen = BTreeSet::new();
+ let mut nodes = Vec::new();
+ layers
+ .iter()
+ .for_each(|l| l.cels().iter().for_each(|c| walk_nodes(&c.nodes, &mut nodes)));
+ layers
+ .iter()
+ .map(|l| &l.id)
+ .chain(layers.iter().flat_map(|l| l.cels().iter().map(|c| &c.id)))
+ .chain(nodes.iter().map(|n| &n.id))
+ .try_for_each(|id| {
+ if !valid_id(id) {
+ bail!("id {id:?} may only use letters, digits, - and _");
+ }
+ if !seen.insert(id) {
+ bail!("id {id} is used twice");
+ }
+ Ok(())
+ })?;
+ layers.iter().try_for_each(|layer| {
+ if !(0.0..=1.0).contains(&layer.opacity) {
+ bail!("layer {}: opacity {} is outside 0..1", layer.id, layer.opacity);
+ }
+ if layer.lock_alpha && layer.kind() != Kind::Paint {
+ bail!("layer {}: lockAlpha is for paint layers", layer.id);
+ }
+ if let Some(mask) = &layer.mask {
+ check_mask(layer, mask)?;
+ }
+ layer.effects.iter().try_for_each(|e| {
+ e.validate()
+ .with_context(|| format!("layer {}: {} effect", layer.id, e.name()))
+ })?;
+ if let Some(adjust) = layer.adjustment() {
+ adjust
+ .validate()
+ .with_context(|| format!("layer {}: {}", layer.id, adjust.label()))?;
+ }
+ nodes
+ .iter()
+ .try_for_each(|n| n.shape.validate().with_context(|| format!("node {}", n.id)))?;
+ if let Some(depth) = layer.depth
+ && (!depth.is_finite() || depth < 0.0)
+ {
+ bail!("layer {}: depth {depth} must be 0 or more", layer.id);
+ }
+ check_cels(layer)
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> Document {
+ let mut doc = Document::new(256, 128);
+ doc.timeline.frames = 8;
+ let mut lines = Layer::paint("l1", "lines", "c1");
+ if let Some(cels) = lines.cels_mut() {
+ cels[0].hold = Some(2);
+ cels.push(Cel {
+ hold: Some(2),
+ ..Cel::at("c2", 2)
+ });
+ cels.push(Cel {
+ link: Some("c1".into()),
+ ..Cel::at("c3", 4)
+ });
+ }
+ let shapes = Layer::vector(
+ "l2",
+ "shapes",
+ "c4",
+ vec![
+ Node::new(
+ "n1",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 10.0,
+ h: 10.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#ff0000"),
+ Node::new(
+ "n2",
+ Shape::Group {
+ children: vec![Node::new("n3", Shape::Path { d: "M0 0 L5 5".into() })],
+ },
+ ),
+ ],
+ );
+ doc.layers = vec![Layer::group("g1", "art", vec![lines]), shapes];
+ doc.palette = vec![
+ Swatch {
+ color: "#1b1b1b".into(),
+ name: "ink".into(),
+ },
+ Swatch {
+ color: "#F4EFE6".into(),
+ name: String::new(),
+ },
+ ];
+ doc.next_id = 10;
+ doc
+ }
+
+ #[test]
+ fn json_round_trip_keeps_everything() {
+ let doc = sample();
+ let text = serde_json::to_string_pretty(&doc).unwrap();
+ let back: Document = serde_json::from_str(&text).unwrap();
+ assert_eq!(back, doc);
+ assert!(text.contains("\"kind\": \"group\""));
+ assert!(!text.contains("\"transform\""));
+ back.validate().unwrap();
+ }
+
+ #[test]
+ fn cels_resolve_holds_and_links() {
+ let doc = sample();
+ let lines = doc.layer("l1").unwrap();
+ let at = |f| lines.cel_at(f).map(|c| c.id.as_str());
+ assert_eq!(
+ [at(0), at(1), at(2), at(3), at(4), at(7)],
+ [Some("c1"), Some("c1"), Some("c2"), Some("c2"), Some("c3"), Some("c3")]
+ );
+ assert_eq!(lines.content_at(5).unwrap().id, "c1");
+ let shapes = doc.layer("l2").unwrap();
+ assert_eq!(shapes.cel_at(7).unwrap().id, "c4");
+ assert_eq!(doc.paint_content_at(4).len(), 1);
+ assert_eq!(doc.paint_cels().len(), 2);
+ }
+
+ #[test]
+ fn hold_ends_a_cel() {
+ let mut layer = Layer::paint("l", "l", "c");
+ if let Some(cels) = layer.cels_mut() {
+ cels[0].hold = Some(3);
+ }
+ assert!(layer.cel_at(2).is_some());
+ assert!(layer.cel_at(3).is_none());
+ }
+
+ #[test]
+ fn locate_finds_every_kind() {
+ let doc = sample();
+ assert_eq!(doc.locate("g1"), Some(Loc::Layer(vec![0])));
+ assert_eq!(doc.locate("l1"), Some(Loc::Layer(vec![0, 0])));
+ assert_eq!(doc.locate("c2"), Some(Loc::Cel(vec![0, 0], 1)));
+ assert_eq!(doc.locate("n3"), Some(Loc::Node(vec![1], 0, vec![1, 0])));
+ assert!(doc.locate("zz").is_none());
+ assert!(matches!(doc.item("n3"), Some(Item::Node(_, _, n)) if n.type_name() == "path"));
+ }
+
+ #[test]
+ fn ids_are_allocated_without_collisions() {
+ let mut doc = sample();
+ doc.next_id = 0;
+ let id = doc.alloc_id('n');
+ assert_eq!(id, "n4");
+ assert!(!doc.ids().contains(&id));
+ }
+
+ #[test]
+ fn validation_catches_mistakes() {
+ let broken = |f: fn(&mut Document)| {
+ let mut doc = sample();
+ f(&mut doc);
+ doc.validate().unwrap_err().to_string()
+ };
+ assert!(broken(|d| d.layers[1].id = "l1".into()).contains("used twice"));
+ assert!(broken(|d| d.layers[1].id = "has space".into()).contains("may only use"));
+ assert!(broken(|d| d.layer_at_mut(&[0, 0]).cels_mut().unwrap()[0].hold = Some(3)).contains("overlaps"));
+ assert!(
+ broken(|d| d.layer_at_mut(&[0, 0]).cels_mut().unwrap()[2].link = Some("c9".into())).contains("not a cel")
+ );
+ assert!(broken(|d| d.timeline.clips.push(Clip::new("x", 2, 9, true))).contains("clip"));
+ assert!(
+ broken(|d| d.layer_at_mut(&[1]).cels_mut().unwrap()[0].nodes[0].fill = Some(Paint::Solid("red".into())))
+ .contains("node n1")
+ );
+ assert!(broken(|d| d.canvas.width = 0).contains("canvas"));
+ assert!(broken(|d| d.palette[1].name = "ink".into()).contains("used twice"));
+ assert!(broken(|d| d.palette[0].color = "black".into()).contains("palette"));
+ }
+
+ #[test]
+ fn masks_are_layers_under_their_owner() {
+ let mut doc = sample();
+ let mut mask = Layer::paint("m1", "mask", "c9");
+ mask.visible = false;
+ doc.layer_at_mut(&[1]).mask = Some(Box::new(mask));
+ doc.layer_at_mut(&[1]).clip = true;
+ let text = serde_json::to_string_pretty(&doc).unwrap();
+ assert!(text.contains("\"mask\": {") && text.contains("\"clip\": true"));
+ let back: Document = serde_json::from_str(&text).unwrap();
+ assert_eq!(back, doc);
+ back.validate().unwrap();
+ assert_eq!(doc.locate("m1"), Some(Loc::Layer(vec![1, MASK])));
+ assert_eq!(doc.locate("c9"), Some(Loc::Cel(vec![1, MASK], 0)));
+ assert_eq!(doc.layer_at(&[1, MASK]).id, "m1");
+ assert!(doc.is_mask("m1") && !doc.is_mask("l2"));
+ assert!(doc.ids().contains("c9"));
+ assert!(doc.paint_cels().iter().any(|(l, c)| l.id == "m1" && c.id == "c9"));
+ assert!(doc.layer("l2").unwrap().mask_at(0).is_none());
+ doc.layer_at_mut(&[1, MASK]).visible = true;
+ assert_eq!(
+ doc.layer("l2").unwrap().mask_at(0).map(|(_, c)| c.id.as_str()),
+ Some("c9")
+ );
+ doc.layer_at_mut(&[1, MASK]).opacity = 0.5;
+ assert!(doc.validate().unwrap_err().to_string().contains("mask m1"));
+ doc.layer_at_mut(&[1, MASK]).opacity = 1.0;
+ doc.layer_at_mut(&[1]).lock_alpha = true;
+ assert!(doc.validate().unwrap_err().to_string().contains("lockAlpha"));
+ }
+
+ #[test]
+ fn palette_names_resolve_to_colours() {
+ let doc = sample();
+ assert_eq!(doc.resolve_color("ink").unwrap(), "#1b1b1b");
+ assert_eq!(doc.resolve_color("#ff0000").unwrap(), "#ff0000");
+ assert!(doc.resolve_color("skin").unwrap_err().to_string().contains("ink"));
+ assert_eq!(
+ [
+ doc.swatch("ink"),
+ doc.swatch("#f4efe6"),
+ doc.swatch("1"),
+ doc.swatch("7")
+ ],
+ [Some(0), Some(1), Some(1), None]
+ );
+ let text = serde_json::to_string(&doc).unwrap();
+ assert!(text.contains(r##""palette":[{"color":"#1b1b1b","name":"ink"},{"color":"#F4EFE6"}]"##));
+ }
+
+ #[test]
+ fn paints_parse_from_json() {
+ let solid: Paint = serde_json::from_str(r##""#336699""##).unwrap();
+ assert_eq!(solid, Paint::Solid("#336699".into()));
+ let linear: Paint =
+ serde_json::from_str(r##"{"linear":{"from":[0,0],"to":[0,100],"stops":[[0,"#000000"],[1,"#ffffff"]]}}"##)
+ .unwrap();
+ assert!(matches!(linear, Paint::Linear { .. }));
+ check_paint(&linear).unwrap();
+ let stroke: StrokeStyle = serde_json::from_str(r#"{"width":3}"#).unwrap();
+ assert_eq!(stroke.paint, Paint::Solid("#000000".into()));
+ assert_eq!(stroke.cap, Cap::Round);
+ }
+}
diff --git a/crates/core/src/fill.rs b/crates/core/src/fill.rs
new file mode 100644
index 0000000..dffe490
--- /dev/null
+++ b/crates/core/src/fill.rs
@@ -0,0 +1,378 @@
+use crate::color::{Rgba, from_u16, to_u16};
+use crate::cut::{self, Cut};
+use crate::stroke::Author;
+use crate::varint::{self, Reader};
+use anyhow::{Result, bail};
+
+pub const TOLERANCE: f32 = 0.1;
+pub const EXPAND: f32 = 2.0;
+pub const MAX_GAP: f32 = 64.0;
+pub const MAX_EXPAND: f32 = 32.0;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum FillRef {
+ This,
+ All,
+ Layer(String),
+}
+
+impl FillRef {
+ pub fn name(&self) -> &str {
+ match self {
+ FillRef::This => "this",
+ FillRef::All => "all",
+ FillRef::Layer(id) => id,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Seed {
+ pub x: f32,
+ pub y: f32,
+ pub tolerance: f32,
+ pub gap: f32,
+ pub expand: f32,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum FillSource {
+ Seed { seed: Seed, reference: FillRef },
+ Polygon(Vec<[f32; 2]>),
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Coverage {
+ pub x: u32,
+ pub y: u32,
+ pub width: u32,
+ pub height: u32,
+ pub alpha: Vec<u8>,
+}
+
+impl Coverage {
+ pub fn from_mask(width: u32, height: u32, mask: &[u8]) -> Self {
+ let (w, h) = (width as usize, height as usize);
+ let rows: Vec<usize> = (0..h)
+ .filter(|&y| mask[y * w..(y + 1) * w].iter().any(|&a| a > 0))
+ .collect();
+ let (Some(&y0), Some(&y1)) = (rows.first(), rows.last()) else {
+ return Self::default();
+ };
+ let (x0, x1) = rows.iter().fold((w, 0), |(lo, hi), &y| {
+ let row = &mask[y * w..(y + 1) * w];
+ let first = row.iter().position(|&a| a > 0).unwrap_or(w);
+ let last = row.iter().rposition(|&a| a > 0).unwrap_or(0);
+ (lo.min(first), hi.max(last))
+ });
+ let alpha = (y0..=y1)
+ .flat_map(|y| mask[y * w + x0..=y * w + x1].iter().copied())
+ .collect();
+ Self {
+ x: x0 as u32,
+ y: y0 as u32,
+ width: (x1 - x0 + 1) as u32,
+ height: (y1 - y0 + 1) as u32,
+ alpha,
+ }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.width == 0 || self.height == 0
+ }
+
+ pub fn pixels(&self) -> usize {
+ self.alpha.iter().filter(|&&a| a > 0).count()
+ }
+
+ pub fn at(&self, x: u32, y: u32) -> u8 {
+ if x < self.x || y < self.y || x >= self.x + self.width || y >= self.y + self.height {
+ return 0;
+ }
+ self.alpha[((y - self.y) * self.width + (x - self.x)) as usize]
+ }
+
+ pub fn bounds(&self) -> Option<[f32; 4]> {
+ (!self.is_empty()).then(|| {
+ [
+ self.x as f32,
+ self.y as f32,
+ (self.x + self.width) as f32,
+ (self.y + self.height) as f32,
+ ]
+ })
+ }
+
+ fn encode(&self, out: &mut Vec<u8>) {
+ [self.x, self.y, self.width, self.height]
+ .iter()
+ .for_each(|v| varint::put(out, *v as u64));
+ let runs = self.alpha.chunk_by(|a, b| a == b).collect::<Vec<_>>();
+ varint::put(out, runs.len() as u64);
+ runs.iter().for_each(|run| {
+ varint::put(out, run.len() as u64);
+ out.push(run[0]);
+ });
+ }
+
+ fn decode(reader: &mut Reader) -> Result<Self> {
+ let mut next = || -> Result<u32> { Ok(u32::try_from(reader.varint()?)?) };
+ let (x, y, width, height) = (next()?, next()?, next()?, next()?);
+ let total = width as usize * height as usize;
+ let runs = reader.varint()? as usize;
+ let mut alpha = Vec::with_capacity(total);
+ (0..runs).try_for_each(|_| {
+ let len = reader.varint()? as usize;
+ let value = reader.u8()?;
+ if alpha.len() + len > total {
+ bail!("fill coverage runs past its {width}x{height} box");
+ }
+ alpha.resize(alpha.len() + len, value);
+ Ok(())
+ })?;
+ if alpha.len() != total {
+ bail!("fill coverage has {} of {total} pixels", alpha.len());
+ }
+ Ok(Self {
+ x,
+ y,
+ width,
+ height,
+ alpha,
+ })
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Fill {
+ pub id: u32,
+ pub color: [u16; 4],
+ pub opacity: f32,
+ pub author: Author,
+ pub source: FillSource,
+ pub coverage: Coverage,
+ pub lock: bool,
+ pub cuts: Vec<Cut>,
+}
+
+const FILL_LOCK: u8 = 0x80;
+const FILL_CUTS: u8 = 0x40;
+
+impl Fill {
+ pub fn new(id: u32, color: Rgba, source: FillSource, coverage: Coverage) -> Self {
+ Self {
+ id,
+ color: to_u16(color),
+ opacity: 1.0,
+ author: Author::Human,
+ source,
+ coverage,
+ lock: false,
+ cuts: Vec::new(),
+ }
+ }
+
+ pub fn by(mut self, author: Author) -> Self {
+ self.author = author;
+ self
+ }
+
+ pub fn color(&self) -> Rgba {
+ from_u16(self.color)
+ }
+
+ pub fn bounds(&self) -> Option<[f32; 4]> {
+ self.coverage.bounds()
+ }
+
+ pub fn reference(&self) -> Option<&FillRef> {
+ match &self.source {
+ FillSource::Seed { reference, .. } => Some(reference),
+ FillSource::Polygon(_) => None,
+ }
+ }
+}
+
+fn put_f32(out: &mut Vec<u8>, v: f32) {
+ out.extend_from_slice(&v.to_le_bytes());
+}
+
+pub(crate) fn encode(out: &mut Vec<u8>, fill: &Fill) {
+ varint::put(out, fill.id as u64);
+ fill.color.iter().for_each(|c| out.extend_from_slice(&c.to_le_bytes()));
+ put_f32(out, fill.opacity);
+ out.push(match fill.author {
+ Author::Human => 0,
+ Author::Agent => 1,
+ });
+ let flags = (if fill.lock { FILL_LOCK } else { 0 }) | (if fill.cuts.is_empty() { 0 } else { FILL_CUTS });
+ match &fill.source {
+ FillSource::Seed { seed, reference } => {
+ out.push(flags);
+ put_f32(out, seed.x);
+ put_f32(out, seed.y);
+ match reference {
+ FillRef::This => out.push(0),
+ FillRef::All => out.push(1),
+ FillRef::Layer(id) => {
+ out.push(2);
+ varint::put(out, id.len() as u64);
+ out.extend_from_slice(id.as_bytes());
+ }
+ }
+ [seed.tolerance, seed.gap, seed.expand]
+ .iter()
+ .for_each(|v| put_f32(out, *v));
+ }
+ FillSource::Polygon(points) => {
+ out.push(1 | flags);
+ varint::put(out, points.len() as u64);
+ points.iter().flatten().for_each(|v| put_f32(out, *v));
+ }
+ }
+ fill.coverage.encode(out);
+ if !fill.cuts.is_empty() {
+ cut::encode(out, &fill.cuts);
+ }
+}
+
+pub(crate) fn decode(reader: &mut Reader, version: u8) -> Result<Fill> {
+ let id = u32::try_from(reader.varint()?)?;
+ let color = [reader.u16()?, reader.u16()?, reader.u16()?, reader.u16()?];
+ let opacity = reader.f32()?;
+ let author = if reader.u8()? == 1 {
+ Author::Agent
+ } else {
+ Author::Human
+ };
+ let tag = reader.u8()?;
+ let flags = if version >= 5 { tag & (FILL_LOCK | FILL_CUTS) } else { 0 };
+ let source = match tag & !flags {
+ 0 => {
+ let (x, y) = (reader.f32()?, reader.f32()?);
+ let reference = match reader.u8()? {
+ 0 => FillRef::This,
+ 1 => FillRef::All,
+ 2 => {
+ let len = reader.varint()? as usize;
+ FillRef::Layer(String::from_utf8(reader.take(len)?.to_vec())?)
+ }
+ other => bail!("unknown fill reference {other}"),
+ };
+ let (tolerance, gap, expand) = (reader.f32()?, reader.f32()?, reader.f32()?);
+ FillSource::Seed {
+ seed: Seed {
+ x,
+ y,
+ tolerance,
+ gap,
+ expand,
+ },
+ reference,
+ }
+ }
+ 1 => {
+ let n = reader.varint()? as usize;
+ FillSource::Polygon(
+ (0..n)
+ .map(|_| Ok([reader.f32()?, reader.f32()?]))
+ .collect::<Result<_>>()?,
+ )
+ }
+ other => bail!("unknown fill source {other}"),
+ };
+ let coverage = Coverage::decode(reader)?;
+ let cuts = if flags & FILL_CUTS != 0 {
+ cut::decode(reader)?
+ } else {
+ Vec::new()
+ };
+ Ok(Fill {
+ id,
+ color,
+ opacity,
+ author,
+ source,
+ coverage,
+ lock: flags & FILL_LOCK != 0,
+ cuts,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn masks_crop_to_their_bounds() {
+ let (w, h) = (8u32, 6u32);
+ let mut mask = vec![0u8; (w * h) as usize];
+ [(2, 1), (5, 1), (3, 4)]
+ .iter()
+ .for_each(|&(x, y)| mask[y * 8 + x] = 255);
+ mask[2 * 8 + 4] = 128;
+ let c = Coverage::from_mask(w, h, &mask);
+ assert_eq!((c.x, c.y, c.width, c.height), (2, 1, 4, 4));
+ assert_eq!((c.at(5, 1), c.at(4, 2), c.at(0, 0), c.at(7, 5)), (255, 128, 0, 0));
+ assert_eq!(c.pixels(), 4);
+ assert_eq!(c.bounds(), Some([2.0, 1.0, 6.0, 5.0]));
+ assert!(Coverage::from_mask(4, 4, &[0; 16]).is_empty());
+ }
+
+ #[test]
+ fn fills_round_trip_with_every_source() {
+ let mut mask = vec![0u8; 64 * 64];
+ (10..40).for_each(|y| (5..60).for_each(|x| mask[y * 64 + x] = if x == 5 { 90 } else { 255 }));
+ let coverage = Coverage::from_mask(64, 64, &mask);
+ let seed = Seed {
+ x: 20.5,
+ y: 30.0,
+ tolerance: 0.1,
+ gap: 4.0,
+ expand: 2.0,
+ };
+ let fills = [
+ Fill::new(
+ 3,
+ [0.2, 0.4, 0.6, 1.0],
+ FillSource::Seed {
+ seed,
+ reference: FillRef::Layer("lines".into()),
+ },
+ coverage.clone(),
+ )
+ .by(Author::Agent),
+ Fill::new(
+ 4,
+ [1.0, 0.0, 0.0, 0.5],
+ FillSource::Seed {
+ seed,
+ reference: FillRef::All,
+ },
+ Coverage::default(),
+ ),
+ Fill::new(
+ 5,
+ [0.0, 0.0, 0.0, 1.0],
+ FillSource::Polygon(vec![[1.0, 1.0], [30.0, 2.5], [9.0, 40.0]]),
+ coverage,
+ ),
+ ];
+ let mut locked = fills[2].clone();
+ locked.lock = true;
+ locked.cuts = vec![Cut {
+ keep: cut::Keep::Inside,
+ polygon: vec![[0.0, 0.0], [20.0, 0.0], [0.0, 20.0]],
+ }];
+ fills.iter().chain([&locked]).for_each(|fill| {
+ let mut bytes = Vec::new();
+ encode(&mut bytes, fill);
+ let mut reader = Reader::new(&bytes);
+ assert_eq!(&decode(&mut reader, 5).unwrap(), fill);
+ assert!(reader.done());
+ });
+ let mut bytes = Vec::new();
+ encode(&mut bytes, &fills[0]);
+ assert!(bytes.len() < 200, "{} bytes", bytes.len());
+ }
+}
diff --git a/crates/core/src/generators.rs b/crates/core/src/generators.rs
new file mode 100644
index 0000000..0beb7cf
--- /dev/null
+++ b/crates/core/src/generators.rs
@@ -0,0 +1,351 @@
+use crate::doc::Node;
+use crate::path::flatten;
+use crate::rng::hash2_unit;
+use anyhow::{Result, bail};
+use serde::{Deserialize, Serialize};
+
+pub type Affine = [f32; 6];
+
+pub const IDENTITY: Affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
+const MAX_COPIES: u32 = 10_000;
+const TRIES: i32 = 16;
+
+pub fn then(a: Affine, b: Affine) -> Affine {
+ [
+ a[0] * b[0] + a[2] * b[1],
+ a[1] * b[0] + a[3] * b[1],
+ a[0] * b[2] + a[2] * b[3],
+ a[1] * b[2] + a[3] * b[3],
+ a[0] * b[4] + a[2] * b[5] + a[4],
+ a[1] * b[4] + a[3] * b[5] + a[5],
+ ]
+}
+
+fn translate(x: f32, y: f32) -> Affine {
+ [1.0, 0.0, 0.0, 1.0, x, y]
+}
+
+fn rotate(degrees: f32) -> Affine {
+ let (s, c) = libm::sincosf(degrees.to_radians());
+ [c, s, -s, c, 0.0, 0.0]
+}
+
+fn scale(k: f32) -> Affine {
+ [k, 0.0, 0.0, k, 0.0, 0.0]
+}
+
+fn about(pivot: [f32; 2], m: Affine) -> Affine {
+ then(then(translate(pivot[0], pivot[1]), m), translate(-pivot[0], -pivot[1]))
+}
+
+pub fn apply(m: Affine, (x, y): (f32, f32)) -> (f32, f32) {
+ (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Scatter {
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ pub count: u32,
+ pub seed: u32,
+ pub size: [f32; 2],
+ pub turn: [f32; 2],
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub avoid: Vec<String>,
+ pub children: Vec<Node>,
+}
+
+impl Default for Scatter {
+ fn default() -> Self {
+ Self {
+ x: 0.0,
+ y: 0.0,
+ w: 400.0,
+ h: 200.0,
+ count: 12,
+ seed: 1,
+ size: [0.8, 1.2],
+ turn: [-20.0, 20.0],
+ avoid: Vec::new(),
+ children: Vec::new(),
+ }
+ }
+}
+
+fn inside(polygons: &[Vec<[f32; 2]>], (x, y): (f32, f32)) -> bool {
+ polygons
+ .iter()
+ .map(|ring| {
+ ring.iter()
+ .zip(ring.iter().cycle().skip(1))
+ .filter(|([x0, y0], [x1, y1])| (*y0 > y) != (*y1 > y) && x < x0 + (y - y0) * (x1 - x0) / (y1 - y0))
+ .count()
+ })
+ .sum::<usize>()
+ % 2
+ == 1
+}
+
+impl Scatter {
+ pub fn validate(&self) -> Result<()> {
+ if self.count > MAX_COPIES {
+ bail!("scatter: count {} is over {MAX_COPIES}", self.count);
+ }
+ if self.w < 0.0 || self.h < 0.0 {
+ bail!("scatter: the region needs a positive width and height");
+ }
+ self.avoid.iter().try_for_each(|d| flatten(d).map(|_| ()))
+ }
+
+ pub fn instances(&self) -> Vec<Affine> {
+ let avoid: Vec<Vec<[f32; 2]>> = self.avoid.iter().filter_map(|d| flatten(d).ok()).flatten().collect();
+ let seed = self.seed ^ 0x5CA7_7E12;
+ (0..self.count.min(MAX_COPIES) as i32)
+ .filter_map(|i| {
+ let at = (0..TRIES).find_map(|t| {
+ let r = |k: i32| hash2_unit(i, t * 8 + k, seed);
+ let p = (self.x + self.w * r(0), self.y + self.h * r(1));
+ (!inside(&avoid, p)).then_some(p)
+ })?;
+ let r = |k: i32| hash2_unit(i, 1000 + k, seed);
+ let size = self.size[0] + (self.size[1] - self.size[0]) * r(0);
+ let turn = self.turn[0] + (self.turn[1] - self.turn[0]) * r(1);
+ Some(then(then(translate(at.0, at.1), rotate(turn)), scale(size)))
+ })
+ .collect()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Repeat {
+ pub count: u32,
+ pub step: [f32; 2],
+ pub turn: f32,
+ pub pivot: [f32; 2],
+ pub scale: f32,
+ pub columns: u32,
+ pub row: [f32; 2],
+ pub children: Vec<Node>,
+}
+
+impl Default for Repeat {
+ fn default() -> Self {
+ Self {
+ count: 4,
+ step: [40.0, 0.0],
+ turn: 0.0,
+ pivot: [0.0, 0.0],
+ scale: 1.0,
+ columns: 0,
+ row: [0.0, 40.0],
+ children: Vec::new(),
+ }
+ }
+}
+
+impl Repeat {
+ pub fn validate(&self) -> Result<()> {
+ if self.count > MAX_COPIES {
+ bail!("repeat: count {} is over {MAX_COPIES}", self.count);
+ }
+ if self.scale <= 0.0 {
+ bail!("repeat: scale must be above 0");
+ }
+ Ok(())
+ }
+
+ pub fn instances(&self) -> Vec<Affine> {
+ (0..self.count.min(MAX_COPIES))
+ .map(|i| {
+ let (col, row) = match self.columns {
+ 0 => (i, 0),
+ n => (i % n, i / n),
+ };
+ let offset = (
+ self.step[0] * col as f32 + self.row[0] * row as f32,
+ self.step[1] * col as f32 + self.row[1] * row as f32,
+ );
+ let grow = libm::powf(self.scale, i as f32);
+ then(
+ translate(offset.0, offset.1),
+ about(self.pivot, then(rotate(self.turn * i as f32), scale(grow))),
+ )
+ })
+ .collect()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Mirror {
+ pub x: f32,
+ pub y: f32,
+ pub angle: f32,
+ pub children: Vec<Node>,
+}
+
+impl Default for Mirror {
+ fn default() -> Self {
+ Self {
+ x: 0.0,
+ y: 0.0,
+ angle: 90.0,
+ children: Vec::new(),
+ }
+ }
+}
+
+impl Mirror {
+ pub fn reflection(&self) -> Affine {
+ let (s, c) = libm::sincosf(2.0 * self.angle.to_radians());
+ about([self.x, self.y], [c, s, s, -c, 0.0, 0.0])
+ }
+
+ pub fn instances(&self) -> Vec<Affine> {
+ vec![IDENTITY, self.reflection()]
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Text {
+ pub text: String,
+ pub font: String,
+ pub x: f32,
+ pub y: f32,
+ pub size: f32,
+ pub tracking: f32,
+ pub leading: f32,
+ pub align: Align,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Align {
+ #[default]
+ Left,
+ Center,
+ Right,
+}
+
+impl Default for Text {
+ fn default() -> Self {
+ Self {
+ text: "text".into(),
+ font: String::new(),
+ x: 0.0,
+ y: 0.0,
+ size: 32.0,
+ tracking: 0.0,
+ leading: 1.2,
+ align: Align::Left,
+ }
+ }
+}
+
+impl Text {
+ pub fn validate(&self) -> Result<()> {
+ if self.font.trim().is_empty() {
+ bail!("text needs a font: a file in the bundle's fonts folder");
+ }
+ if self.size <= 0.0 || self.size > 4096.0 {
+ bail!("text: size {} is outside 0..4096", self.size);
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Picture {
+ pub src: String,
+ #[serde(default)]
+ pub x: f32,
+ #[serde(default)]
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+}
+
+impl Picture {
+ pub fn validate(&self) -> Result<()> {
+ if self.src.trim().is_empty() || self.src.contains('/') || self.src.contains('\\') {
+ bail!(
+ "an image's src is a file name in the bundle's images folder, not {:?}",
+ self.src
+ );
+ }
+ if self.w <= 0.0 || self.h <= 0.0 {
+ bail!("an image needs a width and height above 0");
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scatter_repeats_with_its_seed_and_keeps_out_of_what_it_avoids() {
+ let s = Scatter {
+ count: 200,
+ avoid: vec!["M0 0 L200 0 L200 200 L0 200 Z".into()],
+ ..Scatter::default()
+ };
+ let a = s.instances();
+ assert_eq!(a, s.instances());
+ assert_ne!(a, Scatter { seed: 2, ..s.clone() }.instances());
+ assert!(
+ a.iter().all(|m| !(m[4] < 200.0 && m[5] < 200.0)),
+ "nothing lands in the avoided square"
+ );
+ assert!(a.len() > 150);
+ assert!(
+ a.iter()
+ .all(|m| m[4] >= 0.0 && m[4] <= 400.0 && m[5] >= 0.0 && m[5] <= 200.0)
+ );
+ }
+
+ #[test]
+ fn repeat_steps_and_mirror_reflects() {
+ let r = Repeat {
+ count: 6,
+ step: [10.0, 0.0],
+ columns: 3,
+ row: [0.0, 20.0],
+ ..Repeat::default()
+ };
+ let at: Vec<(f32, f32)> = r.instances().iter().map(|m| apply(*m, (0.0, 0.0))).collect();
+ assert_eq!(
+ at,
+ vec![
+ (0.0, 0.0),
+ (10.0, 0.0),
+ (20.0, 0.0),
+ (0.0, 20.0),
+ (10.0, 20.0),
+ (20.0, 20.0)
+ ]
+ );
+ let arc = Repeat {
+ count: 4,
+ step: [0.0, 0.0],
+ turn: 90.0,
+ pivot: [0.0, 0.0],
+ ..Repeat::default()
+ };
+ let p = apply(arc.instances()[1], (10.0, 0.0));
+ assert!((p.0).abs() < 1e-4 && (p.1 - 10.0).abs() < 1e-4, "{p:?}");
+ let m = Mirror {
+ x: 100.0,
+ ..Mirror::default()
+ };
+ let q = apply(m.reflection(), (130.0, 40.0));
+ assert!((q.0 - 70.0).abs() < 1e-3 && (q.1 - 40.0).abs() < 1e-3, "{q:?}");
+ }
+}
diff --git a/crates/core/src/history.rs b/crates/core/src/history.rs
new file mode 100644
index 0000000..b6b1231
--- /dev/null
+++ b/crates/core/src/history.rs
@@ -0,0 +1,436 @@
+use crate::bundle::{Bundle, now_ms, write_atomic};
+use crate::doc::Document;
+use crate::migrate::migrate;
+use crate::patch::{Patch, diff};
+use anyhow::{Context, Result, anyhow};
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+pub const KEEP: usize = 100;
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Entry {
+ pub seq: u64,
+ pub rev: u64,
+ pub author: String,
+ pub at_ms: u64,
+ pub summary: String,
+ pub files: Vec<String>,
+ #[serde(default)]
+ pub absent: Vec<String>,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub patch: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Stack {
+ Undo,
+ Redo,
+}
+
+impl Stack {
+ fn dir(self) -> &'static str {
+ match self {
+ Stack::Undo => "undo",
+ Stack::Redo => "redo",
+ }
+ }
+
+ fn other(self) -> Self {
+ match self {
+ Stack::Undo => Stack::Redo,
+ Stack::Redo => Stack::Undo,
+ }
+ }
+}
+
+fn stack_dir(bundle: &Bundle, stack: Stack) -> PathBuf {
+ bundle.cache_dir().join("history").join(stack.dir())
+}
+
+fn entry_dir(bundle: &Bundle, stack: Stack, seq: u64) -> PathBuf {
+ stack_dir(bundle, stack).join(format!("{seq:010}"))
+}
+
+fn seqs(bundle: &Bundle, stack: Stack) -> Result<Vec<u64>> {
+ let dir = stack_dir(bundle, stack);
+ if !dir.exists() {
+ return Ok(Vec::new());
+ }
+ let mut out: Vec<u64> = fs::read_dir(&dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().join("meta.json").exists())
+ .filter_map(|e| e.file_name().to_str()?.parse().ok())
+ .collect();
+ out.sort_by_key(|s| std::cmp::Reverse(*s));
+ Ok(out)
+}
+
+fn read_entry(bundle: &Bundle, stack: Stack, seq: u64) -> Result<Entry> {
+ let text = fs::read_to_string(entry_dir(bundle, stack, seq).join("meta.json"))?;
+ Ok(serde_json::from_str(&text)?)
+}
+
+pub fn entries(bundle: &Bundle, stack: Stack) -> Result<Vec<Entry>> {
+ Ok(seqs(bundle, stack)?
+ .into_iter()
+ .filter_map(|seq| read_entry(bundle, stack, seq).ok())
+ .collect())
+}
+
+fn next_seq(bundle: &Bundle) -> Result<u64> {
+ let newest = |stack| seqs(bundle, stack).map(|s| s.first().copied().unwrap_or(0));
+ Ok(newest(Stack::Undo)?.max(newest(Stack::Redo)?) + 1)
+}
+
+fn write_entry(bundle: &Bundle, stack: Stack, entry: &Entry, patch: &Patch) -> Result<()> {
+ let dir = entry_dir(bundle, stack, entry.seq);
+ fs::create_dir_all(dir.join("files"))?;
+ write_atomic(
+ &dir.join("patch.json.zst"),
+ &zstd::encode_all(&serde_json::to_vec(patch)?[..], 3)?,
+ )?;
+ entry.files.iter().try_for_each(|rel| {
+ let source = bundle.root.join(rel);
+ if source.exists() {
+ let packed = zstd::encode_all(&fs::read(&source)?[..], 3)?;
+ write_atomic(&dir.join("files").join(rel), &packed)?;
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ write_atomic(&dir.join("meta.json"), serde_json::to_string_pretty(entry)?.as_bytes())
+}
+
+fn relative(bundle: &Bundle, path: &Path) -> String {
+ path.strip_prefix(&bundle.root)
+ .unwrap_or(path)
+ .to_string_lossy()
+ .replace('\\', "/")
+}
+
+fn absent(bundle: &Bundle, files: &[String]) -> Vec<String> {
+ files
+ .iter()
+ .filter(|f| !bundle.root.join(f).exists())
+ .cloned()
+ .collect()
+}
+
+pub fn record(bundle: &Bundle, restore: &Patch, author: &str, summary: &str, files: &[PathBuf]) -> Result<()> {
+ let files: Vec<String> = files.iter().map(|f| relative(bundle, f)).collect();
+ let entry = Entry {
+ seq: next_seq(bundle)?,
+ rev: bundle.doc.rev,
+ author: author.to_string(),
+ at_ms: now_ms(),
+ summary: summary.to_string(),
+ absent: absent(bundle, &files),
+ files,
+ patch: true,
+ };
+ write_entry(bundle, Stack::Undo, &entry, restore)?;
+ let redo = stack_dir(bundle, Stack::Redo);
+ if redo.exists() {
+ fs::remove_dir_all(&redo)?;
+ }
+ seqs(bundle, Stack::Undo)?
+ .iter()
+ .skip(KEEP)
+ .try_for_each(|old| fs::remove_dir_all(entry_dir(bundle, Stack::Undo, *old)))?;
+ Ok(())
+}
+
+pub fn checkpoint(bundle: &Bundle, after: &Document, author: &str, summary: &str, files: &[PathBuf]) -> Result<()> {
+ record(bundle, &diff(after, &bundle.doc)?, author, summary, files)
+}
+
+fn read_patch(dir: &Path) -> Result<Patch> {
+ let bytes = zstd::decode_all(&fs::read(dir.join("patch.json.zst"))?[..])?;
+ Ok(serde_json::from_slice(&bytes)?)
+}
+
+fn snapshot_doc(dir: &Path) -> Result<Document> {
+ let text = zstd::decode_all(&fs::read(dir.join("doc.json.zst"))?[..])?;
+ let value: serde_json::Value = serde_json::from_slice(&text).context("reading the snapshot document")?;
+ let migrated = migrate(value).context("upgrading the snapshot document")?;
+ serde_json::from_value(migrated.value).context("reading the snapshot document")
+}
+
+fn restored(current: &Document, entry: &Entry, dir: &Path) -> Result<Document> {
+ if entry.patch {
+ read_patch(dir)?
+ .applied(current)
+ .with_context(|| format!("step #{}: the document no longer matches it", entry.seq))
+ } else {
+ snapshot_doc(dir)
+ }
+}
+
+fn restore_files(bundle: &Bundle, entry: &Entry, dir: &Path) -> Result<()> {
+ entry.files.iter().try_for_each(|rel| {
+ let target = bundle.root.join(rel);
+ if entry.absent.contains(rel) {
+ if target.exists() {
+ fs::remove_file(&target)?;
+ }
+ } else {
+ let packed = fs::read(dir.join("files").join(rel)).with_context(|| format!("snapshot of {rel}"))?;
+ write_atomic(&target, &zstd::decode_all(&packed[..])?)?;
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+}
+
+pub fn peek(bundle: &Bundle, stack: Stack) -> Result<Option<(Entry, Option<Patch>)>> {
+ let Some(seq) = seqs(bundle, stack)?.first().copied() else {
+ return Ok(None);
+ };
+ let entry = read_entry(bundle, stack, seq)?;
+ let patch = if entry.patch {
+ Some(read_patch(&entry_dir(bundle, stack, seq))?)
+ } else {
+ None
+ };
+ Ok(Some((entry, patch)))
+}
+
+pub fn step(bundle: &mut Bundle, stack: Stack) -> Result<Option<Entry>> {
+ let Some(seq) = seqs(bundle, stack)?.first().copied() else {
+ return Ok(None);
+ };
+ let entry = read_entry(bundle, stack, seq)?;
+ let dir = entry_dir(bundle, stack, seq);
+ let mirror = Entry {
+ seq: next_seq(bundle)?,
+ rev: bundle.doc.rev,
+ author: entry.author.clone(),
+ at_ms: entry.at_ms,
+ summary: entry.summary.clone(),
+ files: entry.files.clone(),
+ absent: absent(bundle, &entry.files),
+ patch: true,
+ };
+ if entry.patch {
+ let patch = read_patch(&dir)?;
+ if let Err(e) = patch.apply_in_place(&mut bundle.doc) {
+ bundle.reload()?;
+ return Err(e.context(format!("step #{seq}: the document no longer matches it")));
+ }
+ write_entry(bundle, stack.other(), &mirror, &patch.reversed())?;
+ } else {
+ let doc = snapshot_doc(&dir)?;
+ write_entry(bundle, stack.other(), &mirror, &diff(&doc, &bundle.doc)?)?;
+ bundle.doc = Document {
+ rev: bundle.doc.rev,
+ ..doc
+ };
+ }
+ restore_files(bundle, &entry, &dir)?;
+ bundle.save()?;
+ fs::remove_dir_all(dir)?;
+ Ok(Some(entry))
+}
+
+pub struct Before {
+ pub doc: Document,
+ pub files: BTreeMap<String, Option<Vec<u8>>>,
+}
+
+pub fn before(bundle: &Bundle, seq: u64) -> Result<Before> {
+ let chain: Vec<u64> = seqs(bundle, Stack::Undo)?.into_iter().filter(|s| *s >= seq).collect();
+ if chain.last() != Some(&seq) {
+ return Err(anyhow!("no undo step #{seq}"));
+ }
+ chain.iter().try_fold(
+ Before {
+ doc: bundle.doc.clone(),
+ files: BTreeMap::new(),
+ },
+ |mut state, &s| {
+ let entry = read_entry(bundle, Stack::Undo, s)?;
+ let dir = entry_dir(bundle, Stack::Undo, s);
+ state.doc = restored(&state.doc, &entry, &dir)?;
+ entry.files.iter().try_for_each(|rel| {
+ let bytes = if entry.absent.contains(rel) {
+ None
+ } else {
+ Some(zstd::decode_all(&fs::read(dir.join("files").join(rel))?[..])?)
+ };
+ state.files.insert(rel.clone(), bytes);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ Ok(state)
+ },
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::Layer;
+ use crate::ops::parse_lines;
+ use crate::synth::Synth;
+
+ fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("draw-history-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ #[test]
+ fn undo_and_redo_walk_edits_and_stroke_files() {
+ let dir = scratch("walk");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::paint("l1", "ink", "c1"));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .apply(&parse_lines(r#"{"op":"add","layer":{"kind":"vector","name":"shapes"}}"#).unwrap())
+ .unwrap();
+ let with_layer = bundle.doc.layers.len();
+ let strokes = Synth::canvas(64.0, 64.0).strokes(3, 1);
+ checkpoint(
+ &bundle,
+ &bundle.doc,
+ "test",
+ "paint",
+ &[bundle.strokes_path("l1", "c1")],
+ )
+ .unwrap();
+ bundle
+ .write_marks("l1", "c1", &crate::stroke::marks(strokes.clone()))
+ .unwrap();
+ bundle.save().unwrap();
+ assert_eq!(entries(&bundle, Stack::Undo).unwrap().len(), 2);
+ let made = entries(&bundle, Stack::Undo).unwrap()[0].clone();
+ let undone = step(&mut bundle, Stack::Undo).unwrap().unwrap();
+ assert_eq!(undone.summary, "paint");
+ assert!(!bundle.strokes_path("l1", "c1").exists());
+ let waiting = entries(&bundle, Stack::Redo).unwrap()[0].clone();
+ assert_eq!((waiting.author.as_str(), waiting.at_ms), ("test", made.at_ms));
+ let undone = step(&mut bundle, Stack::Undo).unwrap().unwrap();
+ assert!(undone.summary.contains("add layer"));
+ assert_eq!(bundle.doc.layers.len(), with_layer - 1);
+ assert!(step(&mut bundle, Stack::Undo).unwrap().is_none());
+ step(&mut bundle, Stack::Redo).unwrap().unwrap();
+ step(&mut bundle, Stack::Redo).unwrap().unwrap();
+ assert_eq!(bundle.doc.layers.len(), with_layer);
+ assert_eq!(bundle.read_strokes("l1", "c1").unwrap(), strokes);
+ let reopened = Bundle::open(&dir).unwrap();
+ assert_eq!(reopened.doc.rev, bundle.doc.rev);
+ bundle
+ .apply(&parse_lines(r#"{"op":"set","id":"l1","name":"x"}"#).unwrap())
+ .unwrap();
+ assert!(entries(&bundle, Stack::Redo).unwrap().is_empty());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn steps_store_changes_and_old_snapshot_steps_still_undo() {
+ let dir = scratch("patch");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::vector("v", "shapes", "c1", Vec::new()));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ let big: String = (0..400)
+ .map(|i| {
+ format!(r#"{{"op":"add","node":{{"id":"n{i}","type":"rect","x":{i},"y":0,"w":5,"h":5}},"in":"v"}}"#)
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ bundle.apply(&parse_lines(&big).unwrap()).unwrap();
+ let legacy_doc = bundle.doc.clone();
+ let legacy = Entry {
+ seq: 50,
+ rev: bundle.doc.rev,
+ author: "m1".into(),
+ at_ms: 0,
+ summary: "old style".into(),
+ files: Vec::new(),
+ absent: Vec::new(),
+ patch: false,
+ };
+ let legacy_dir = entry_dir(&bundle, Stack::Undo, 50);
+ fs::create_dir_all(&legacy_dir).unwrap();
+ let text = serde_json::to_string(&legacy_doc).unwrap();
+ fs::write(
+ legacy_dir.join("doc.json.zst"),
+ zstd::encode_all(text.as_bytes(), 3).unwrap(),
+ )
+ .unwrap();
+ fs::write(legacy_dir.join("meta.json"), serde_json::to_string(&legacy).unwrap()).unwrap();
+ bundle
+ .apply(&parse_lines(r#"{"op":"set","id":"n7","x":99}"#).unwrap())
+ .unwrap();
+ let newest = seqs(&bundle, Stack::Undo).unwrap()[0];
+ assert_eq!(newest, 51);
+ let packed = fs::metadata(entry_dir(&bundle, Stack::Undo, newest).join("patch.json.zst"))
+ .unwrap()
+ .len();
+ assert!(packed < 200, "{packed} bytes");
+ bundle.apply(&parse_lines(r#"{"op":"rm","id":"n3"}"#).unwrap()).unwrap();
+ let plain = |d: &Document| Document { rev: 0, ..d.clone() };
+ assert_eq!(plain(&super::before(&bundle, newest).unwrap().doc), plain(&legacy_doc));
+ step(&mut bundle, Stack::Undo).unwrap();
+ step(&mut bundle, Stack::Undo).unwrap();
+ assert_eq!(plain(&bundle.doc), plain(&legacy_doc));
+ bundle.doc.layers[0].name = "drifted".into();
+ bundle.save().unwrap();
+ let undone = step(&mut bundle, Stack::Undo).unwrap().unwrap();
+ assert_eq!(undone.summary, "old style");
+ assert_eq!(plain(&bundle.doc), plain(&legacy_doc));
+ step(&mut bundle, Stack::Redo).unwrap();
+ assert_eq!(bundle.doc.layers[0].name, "drifted");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_step_that_no_longer_fits_fails_and_changes_nothing() {
+ let dir = scratch("stale");
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::vector("v", "shapes", "c1", Vec::new()));
+ let mut bundle = Bundle::create(&dir, doc).unwrap();
+ bundle
+ .apply(&parse_lines(r#"{"op":"set","id":"v","name":"one"}"#).unwrap())
+ .unwrap();
+ bundle.doc.layers[0].name = "edited outside history".into();
+ bundle.save().unwrap();
+ let rev = bundle.doc.rev;
+ let err = step(&mut bundle, Stack::Undo).unwrap_err();
+ assert!(format!("{err:#}").contains("no longer matches"), "{err:#}");
+ assert_eq!(Bundle::open(&dir).unwrap().doc.rev, rev);
+ assert!(entries(&bundle, Stack::Redo).unwrap().is_empty());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ #[ignore = "timing: LANDSCAPE=<copy of landscape.draw> cargo test --release -p klad-core undo_timing -- --ignored --nocapture"]
+ fn undo_timing() {
+ let path = std::env::var("LANDSCAPE").expect("LANDSCAPE");
+ let mut bundle = Bundle::open(&path).unwrap();
+ let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0;
+ let tree = bundle
+ .doc
+ .layer("trees")
+ .and_then(|l| l.cels().first())
+ .and_then(|c| c.nodes.first())
+ .map(|n| n.id.clone())
+ .unwrap();
+ (0..3).for_each(|round| {
+ let line = format!(r#"{{"op":"set","id":"{tree}","transform.x":{}}}"#, 10 * (round + 1));
+ let t = std::time::Instant::now();
+ bundle.apply_as(&parse_lines(&line).unwrap(), "editor").unwrap();
+ let edit = ms(t);
+ let t = std::time::Instant::now();
+ step(&mut bundle, Stack::Undo).unwrap().unwrap();
+ let undo = ms(t);
+ let t = std::time::Instant::now();
+ step(&mut bundle, Stack::Redo).unwrap().unwrap();
+ println!(
+ "move {tree}: edit {edit:.1} ms, undo {undo:.1} ms, redo {:.1} ms",
+ ms(t)
+ );
+ });
+ }
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
new file mode 100644
index 0000000..76c8a84
--- /dev/null
+++ b/crates/core/src/lib.rs
@@ -0,0 +1,48 @@
+pub mod brushes;
+pub mod bundle;
+pub mod color;
+pub mod cut;
+pub mod doc;
+pub mod fill;
+pub mod generators;
+pub mod history;
+pub mod look;
+pub mod markedit;
+pub mod migrate;
+pub mod notes;
+pub mod ops;
+pub mod patch;
+pub mod path;
+pub mod pathedit;
+pub mod retime;
+pub mod rng;
+pub mod stroke;
+pub mod synth;
+pub mod timing;
+pub mod tween;
+mod varint;
+
+pub mod notices {
+ pub const LICENSE: &str = include_str!("../../../LICENSE");
+ pub const NOTICES: &str = include_str!("../../../THIRD-PARTY-NOTICES.md");
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn the_licence_and_the_notices_ship_with_the_code() {
+ assert!(LICENSE.contains("PolyForm Internal Use License 1.0.0") && LICENSE.contains("Indicode BV"));
+ [
+ "skia-safe",
+ "eframe",
+ "zstd",
+ "### Skia",
+ "### Phosphor icons",
+ "SIL Open Font License",
+ ]
+ .iter()
+ .for_each(|name| assert!(NOTICES.contains(name), "{name}"));
+ }
+ }
+}
diff --git a/crates/core/src/look.rs b/crates/core/src/look.rs
new file mode 100644
index 0000000..d7dca44
--- /dev/null
+++ b/crates/core/src/look.rs
@@ -0,0 +1,1002 @@
+use crate::color::parse_hex;
+use crate::doc::{Blend, Paint, Stop};
+use crate::rng::hash2_unit;
+use anyhow::{Result, bail};
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Effect {
+ Haze(Haze),
+ Blur(Blur),
+ Glow(Glow),
+ Outline(Outline),
+ Shadow(Shadow),
+ Noise(Noise),
+ Displace(Displace),
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Haze {
+ pub amount: f32,
+ pub color: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub top: Option<String>,
+ pub span: f32,
+ pub desaturate: f32,
+}
+
+impl Default for Haze {
+ fn default() -> Self {
+ Self {
+ amount: 0.4,
+ color: "#9aa8b8".into(),
+ top: None,
+ span: 0.0,
+ desaturate: 0.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Atmosphere {
+ pub color: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub top: Option<String>,
+ pub density: f32,
+ pub blur: f32,
+ pub desaturate: f32,
+}
+
+impl Default for Atmosphere {
+ fn default() -> Self {
+ Self {
+ color: "#9aa8b8".into(),
+ top: None,
+ density: 0.5,
+ blur: 1.0,
+ desaturate: 0.15,
+ }
+ }
+}
+
+impl Atmosphere {
+ pub fn validate(&self) -> Result<()> {
+ parse_hex(&self.color)?;
+ self.top.as_deref().map_or(Ok(()), |t| parse_hex(t).map(|_| ()))?;
+ if self.density < 0.0 || self.blur < 0.0 || self.desaturate < 0.0 {
+ bail!("atmosphere: density, blur and desaturate are 0 or more");
+ }
+ Ok(())
+ }
+
+ pub fn effects(&self, depth: f32, height: f32) -> Vec<Effect> {
+ if depth <= 0.0 {
+ return Vec::new();
+ }
+ let haze = Effect::Haze(Haze {
+ amount: 1.0 - libm::expf(-self.density * depth),
+ color: self.color.clone(),
+ top: self.top.clone(),
+ span: height,
+ desaturate: (self.desaturate * depth).min(1.0),
+ });
+ let sigma = self.blur * depth;
+ std::iter::once(haze)
+ .chain((sigma >= 0.25).then_some(Effect::Blur(Blur { radius: sigma })))
+ .collect()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Blur {
+ pub radius: f32,
+}
+
+impl Default for Blur {
+ fn default() -> Self {
+ Self { radius: 4.0 }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Glow {
+ pub radius: f32,
+ pub strength: f32,
+ pub threshold: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub color: Option<String>,
+ pub blend: Blend,
+}
+
+impl Default for Glow {
+ fn default() -> Self {
+ Self {
+ radius: 12.0,
+ strength: 1.0,
+ threshold: 0.0,
+ color: None,
+ blend: Blend::Screen,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Outline {
+ pub width: f32,
+ pub color: String,
+ #[serde(skip_serializing_if = "is_false")]
+ pub inside: bool,
+}
+
+impl Default for Outline {
+ fn default() -> Self {
+ Self {
+ width: 3.0,
+ color: "#1b1b1b".into(),
+ inside: false,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Shadow {
+ pub x: f32,
+ pub y: f32,
+ pub radius: f32,
+ pub color: String,
+}
+
+impl Default for Shadow {
+ fn default() -> Self {
+ Self {
+ x: 6.0,
+ y: 8.0,
+ radius: 6.0,
+ color: "#00000080".into(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Noise {
+ pub amount: f32,
+ pub size: f32,
+ pub seed: u32,
+ pub mono: bool,
+}
+
+impl Default for Noise {
+ fn default() -> Self {
+ Self {
+ amount: 0.08,
+ size: 1.0,
+ seed: 1,
+ mono: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Displace {
+ pub amount: f32,
+ pub size: f32,
+ pub seed: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub by: Option<String>,
+}
+
+impl Default for Displace {
+ fn default() -> Self {
+ Self {
+ amount: 8.0,
+ size: 48.0,
+ seed: 1,
+ by: None,
+ }
+ }
+}
+
+fn is_false(v: &bool) -> bool {
+ !*v
+}
+
+pub const EFFECTS: [&str; 7] = ["blur", "glow", "outline", "shadow", "noise", "displace", "haze"];
+
+impl Effect {
+ pub fn named(name: &str) -> Option<Self> {
+ Some(match name {
+ "blur" => Effect::Blur(Blur::default()),
+ "glow" => Effect::Glow(Glow::default()),
+ "outline" => Effect::Outline(Outline::default()),
+ "shadow" => Effect::Shadow(Shadow::default()),
+ "noise" => Effect::Noise(Noise::default()),
+ "displace" => Effect::Displace(Displace::default()),
+ "haze" => Effect::Haze(Haze::default()),
+ _ => return None,
+ })
+ }
+
+ pub fn name(&self) -> &'static str {
+ match self {
+ Effect::Blur(_) => "blur",
+ Effect::Glow(_) => "glow",
+ Effect::Outline(_) => "outline",
+ Effect::Shadow(_) => "shadow",
+ Effect::Noise(_) => "noise",
+ Effect::Displace(_) => "displace",
+ Effect::Haze(_) => "haze",
+ }
+ }
+
+ pub fn reach(&self) -> f32 {
+ match self {
+ Effect::Blur(b) => b.radius.max(0.0) * 3.0,
+ Effect::Glow(g) => g.radius.max(0.0) * 3.0,
+ Effect::Outline(o) => o.width.max(0.0) + 1.0,
+ Effect::Shadow(s) => s.x.abs().max(s.y.abs()) + s.radius.max(0.0) * 3.0,
+ Effect::Noise(_) | Effect::Haze(_) => 0.0,
+ Effect::Displace(d) => d.amount.abs() + 1.0,
+ }
+ }
+
+ pub fn validate(&self) -> Result<()> {
+ let colour = |c: &str| parse_hex(c).map(|_| ());
+ match self {
+ Effect::Blur(b) if !(0.0..=256.0).contains(&b.radius) => {
+ bail!("blur radius {} is outside 0..256", b.radius)
+ }
+ Effect::Glow(g) if !(0.0..=256.0).contains(&g.radius) => {
+ bail!("glow radius {} is outside 0..256", g.radius)
+ }
+ Effect::Glow(g) => g.color.as_deref().map_or(Ok(()), colour),
+ Effect::Outline(o) if !(0.0..=128.0).contains(&o.width) => {
+ bail!("outline width {} is outside 0..128", o.width)
+ }
+ Effect::Outline(o) => colour(&o.color),
+ Effect::Shadow(s) if !(0.0..=256.0).contains(&s.radius) => {
+ bail!("shadow radius {} is outside 0..256", s.radius)
+ }
+ Effect::Shadow(s) if s.x.abs().max(s.y.abs()) > 1024.0 => bail!("shadow offset is over 1024 px"),
+ Effect::Shadow(s) => colour(&s.color),
+ Effect::Noise(n) if n.size <= 0.0 => bail!("noise size must be above 0"),
+ Effect::Displace(d) if d.size <= 0.0 => bail!("displacement size must be above 0"),
+ Effect::Displace(d) if d.amount.abs() > 512.0 => bail!("displacement is over 512 px"),
+ Effect::Haze(h) => {
+ colour(&h.color)?;
+ h.top.as_deref().map_or(Ok(()), colour)
+ }
+ _ => Ok(()),
+ }
+ }
+}
+
+pub fn reach(effects: &[Effect]) -> f32 {
+ effects.iter().map(Effect::reach).sum()
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Adjustment {
+ Hsl(Hsl),
+ Levels(Levels),
+ Curves(Curves),
+ Balance(Balance),
+ GradientMap(GradientMap),
+ Fill(ColorFill),
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Hsl {
+ pub hue: f32,
+ pub saturation: f32,
+ pub lightness: f32,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Levels {
+ pub black: f32,
+ pub white: f32,
+ pub gamma: f32,
+ pub low: f32,
+ pub high: f32,
+}
+
+impl Default for Levels {
+ fn default() -> Self {
+ Self {
+ black: 0.0,
+ white: 1.0,
+ gamma: 1.0,
+ low: 0.0,
+ high: 1.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Curves {
+ pub points: Vec<[f32; 2]>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub red: Vec<[f32; 2]>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub green: Vec<[f32; 2]>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub blue: Vec<[f32; 2]>,
+}
+
+impl Default for Curves {
+ fn default() -> Self {
+ Self {
+ points: vec![[0.0, 0.0], [1.0, 1.0]],
+ red: Vec::new(),
+ green: Vec::new(),
+ blue: Vec::new(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
+pub struct Balance {
+ pub shadows: [f32; 3],
+ pub midtones: [f32; 3],
+ pub highlights: [f32; 3],
+ pub keep_light: bool,
+}
+
+impl Default for Balance {
+ fn default() -> Self {
+ Self {
+ shadows: [0.0; 3],
+ midtones: [0.0; 3],
+ highlights: [0.0; 3],
+ keep_light: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct GradientMap {
+ pub stops: Vec<Stop>,
+}
+
+impl Default for GradientMap {
+ fn default() -> Self {
+ Self {
+ stops: vec![Stop(0.0, "#1a1033".into()), Stop(1.0, "#ffe9b0".into())],
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct ColorFill {
+ pub paint: Paint,
+}
+
+impl Default for ColorFill {
+ fn default() -> Self {
+ Self {
+ paint: Paint::Solid("#203060".into()),
+ }
+ }
+}
+
+pub const ADJUSTMENTS: [&str; 6] = ["hsl", "levels", "curves", "balance", "gradient-map", "fill"];
+
+impl Adjustment {
+ pub fn named(name: &str) -> Option<Self> {
+ Some(match name {
+ "hsl" => Adjustment::Hsl(Hsl::default()),
+ "levels" => Adjustment::Levels(Levels::default()),
+ "curves" => Adjustment::Curves(Curves::default()),
+ "balance" => Adjustment::Balance(Balance::default()),
+ "gradient-map" => Adjustment::GradientMap(GradientMap::default()),
+ "fill" => Adjustment::Fill(ColorFill::default()),
+ _ => return None,
+ })
+ }
+
+ pub fn name(&self) -> &'static str {
+ match self {
+ Adjustment::Hsl(_) => "hsl",
+ Adjustment::Levels(_) => "levels",
+ Adjustment::Curves(_) => "curves",
+ Adjustment::Balance(_) => "balance",
+ Adjustment::GradientMap(_) => "gradient-map",
+ Adjustment::Fill(_) => "fill",
+ }
+ }
+
+ pub fn label(&self) -> &'static str {
+ label_of(self.name())
+ }
+
+ pub fn reads_under(&self) -> bool {
+ !matches!(self, Adjustment::Fill(_))
+ }
+
+ pub fn validate(&self) -> Result<()> {
+ match self {
+ Adjustment::Fill(f) => match &f.paint {
+ Paint::Solid(c) => parse_hex(c).map(|_| ()),
+ Paint::Linear { linear } => linear.stops.iter().try_for_each(|s| parse_hex(&s.1).map(|_| ())),
+ Paint::Radial { radial } => radial.stops.iter().try_for_each(|s| parse_hex(&s.1).map(|_| ())),
+ },
+ other => other.prepare().map(|_| ()),
+ }
+ }
+
+ pub fn prepare(&self) -> Result<Prepared> {
+ Ok(match self {
+ Adjustment::Hsl(h) => Prepared::Hsl(h.clone()),
+ Adjustment::Levels(l) => {
+ if l.white <= l.black {
+ bail!("levels: white {} must be above black {}", l.white, l.black);
+ }
+ if l.gamma <= 0.0 {
+ bail!("levels: gamma must be above 0");
+ }
+ Prepared::Levels(l.clone())
+ }
+ Adjustment::Curves(c) => Prepared::Curves(Box::new([
+ curve_lut(&c.points)?,
+ curve_lut(&c.red)?,
+ curve_lut(&c.green)?,
+ curve_lut(&c.blue)?,
+ ])),
+ Adjustment::Balance(b) => Prepared::Balance(b.clone()),
+ Adjustment::GradientMap(g) => {
+ if g.stops.is_empty() {
+ bail!("a gradient map needs at least one stop");
+ }
+ let mut stops: Vec<(f32, [f32; 3])> = g
+ .stops
+ .iter()
+ .map(|s| parse_hex(&s.1).map(|c| (s.0, [c[0], c[1], c[2]])))
+ .collect::<Result<_>>()?;
+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));
+ Prepared::Map(stops)
+ }
+ Adjustment::Fill(_) => bail!("a colour fill is drawn, not applied to pixels"),
+ })
+ }
+}
+
+pub fn label_of(name: &str) -> &'static str {
+ match name {
+ "hsl" => "hue and saturation",
+ "levels" => "levels",
+ "curves" => "curves",
+ "balance" => "colour balance",
+ "gradient-map" => "gradient map",
+ "fill" => "colour fill",
+ _ => "adjustment",
+ }
+}
+
+const LUT: usize = 1024;
+
+pub enum Prepared {
+ Hsl(Hsl),
+ Levels(Levels),
+ Curves(Box<[Option<Vec<f32>>; 4]>),
+ Balance(Balance),
+ Map(Vec<(f32, [f32; 3])>),
+}
+
+impl Prepared {
+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
+ match self {
+ Prepared::Hsl(h) => hsl_shift(rgb, h),
+ Prepared::Levels(l) => rgb.map(|c| {
+ let v = ((c - l.black) / (l.white - l.black)).clamp(0.0, 1.0);
+ l.low + libm::powf(v, 1.0 / l.gamma) * (l.high - l.low)
+ }),
+ Prepared::Curves(luts) => {
+ let [master, r, g, b] = &**luts;
+ let through = |lut: &Option<Vec<f32>>, v: f32| lut.as_deref().map_or(v, |t| sample(t, v));
+ let [cr, cg, cb] = [through(r, rgb[0]), through(g, rgb[1]), through(b, rgb[2])];
+ [through(master, cr), through(master, cg), through(master, cb)]
+ }
+ Prepared::Balance(b) => balance(rgb, b),
+ Prepared::Map(stops) => {
+ let l = luma(rgb).clamp(0.0, 1.0);
+ gradient_at(stops, l)
+ }
+ }
+ }
+}
+
+pub fn luma(rgb: [f32; 3]) -> f32 {
+ 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
+}
+
+fn gradient_at(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] {
+ let after = stops.iter().position(|s| s.0 > t);
+ match after {
+ None => stops[stops.len() - 1].1,
+ Some(0) => stops[0].1,
+ Some(i) => {
+ let (a, b) = (stops[i - 1], stops[i]);
+ let k = (t - a.0) / (b.0 - a.0);
+ [0, 1, 2].map(|c| a.1[c] + (b.1[c] - a.1[c]) * k)
+ }
+ }
+}
+
+fn sample(lut: &[f32], v: f32) -> f32 {
+ let x = v.clamp(0.0, 1.0) * (LUT - 1) as f32;
+ let i = (x as usize).min(LUT - 2);
+ let f = x - i as f32;
+ lut[i] + (lut[i + 1] - lut[i]) * f
+}
+
+fn curve_lut(points: &[[f32; 2]]) -> Result<Option<Vec<f32>>> {
+ if points.is_empty() {
+ return Ok(None);
+ }
+ let mut pts: Vec<[f32; 2]> = points.to_vec();
+ if pts.iter().flatten().any(|v| !v.is_finite()) {
+ bail!("curve points must be numbers");
+ }
+ pts.sort_by(|a, b| a[0].total_cmp(&b[0]));
+ pts.dedup_by(|b, a| (b[0] - a[0]).abs() < 1e-4);
+ if pts.len() == 1 {
+ return Ok(Some(vec![pts[0][1]; LUT]));
+ }
+ let slopes: Vec<f32> = pts
+ .windows(2)
+ .map(|w| (w[1][1] - w[0][1]) / (w[1][0] - w[0][0]))
+ .collect();
+ let n = pts.len();
+ let mut tangents: Vec<f32> = (0..n)
+ .map(|k| match k {
+ 0 => slopes[0],
+ k if k == n - 1 => slopes[n - 2],
+ k if slopes[k - 1] * slopes[k] <= 0.0 => 0.0,
+ k => (slopes[k - 1] + slopes[k]) / 2.0,
+ })
+ .collect();
+ (0..n - 1).for_each(|k| {
+ if slopes[k] == 0.0 {
+ tangents[k] = 0.0;
+ tangents[k + 1] = 0.0;
+ return;
+ }
+ let (a, b) = (tangents[k] / slopes[k], tangents[k + 1] / slopes[k]);
+ let h = a * a + b * b;
+ if h > 9.0 {
+ let t = 3.0 / libm::sqrtf(h);
+ tangents[k] = t * a * slopes[k];
+ tangents[k + 1] = t * b * slopes[k];
+ }
+ });
+ let eval = |x: f32| -> f32 {
+ if x <= pts[0][0] {
+ return pts[0][1];
+ }
+ if x >= pts[n - 1][0] {
+ return pts[n - 1][1];
+ }
+ let k = pts.windows(2).position(|w| x < w[1][0]).unwrap_or(n - 2);
+ let (x0, y0, x1, y1) = (pts[k][0], pts[k][1], pts[k + 1][0], pts[k + 1][1]);
+ let h = x1 - x0;
+ let t = (x - x0) / h;
+ let (t2, t3) = (t * t, t * t * t);
+ (2.0 * t3 - 3.0 * t2 + 1.0) * y0
+ + (t3 - 2.0 * t2 + t) * h * tangents[k]
+ + (-2.0 * t3 + 3.0 * t2) * y1
+ + (t3 - t2) * h * tangents[k + 1]
+ };
+ Ok(Some((0..LUT).map(|i| eval(i as f32 / (LUT - 1) as f32)).collect()))
+}
+
+fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
+ let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+fn balance(rgb: [f32; 3], b: &Balance) -> [f32; 3] {
+ let l = luma(rgb);
+ let shadows = 1.0 - smoothstep(0.0, 0.55, l);
+ let highlights = smoothstep(0.45, 1.0, l);
+ let mids = (1.0 - shadows - highlights).max(0.0);
+ let shifted: [f32; 3] = [0, 1, 2].map(|c| {
+ let delta = b.shadows[c] * shadows + b.midtones[c] * mids + b.highlights[c] * highlights;
+ (rgb[c] + delta * 0.5).clamp(0.0, 1.0)
+ });
+ match b.keep_light {
+ true => set_lum(shifted, l),
+ false => shifted,
+ }
+}
+
+fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
+ let (max, min) = (r.max(g).max(b), r.min(g).min(b));
+ let l = (max + min) / 2.0;
+ let d = max - min;
+ if d <= 1e-6 {
+ return [0.0, 0.0, l];
+ }
+ let s = match l > 0.5 {
+ true => d / (2.0 - max - min),
+ false => d / (max + min),
+ };
+ let h = match max {
+ m if m == r => (g - b) / d + if g < b { 6.0 } else { 0.0 },
+ m if m == g => (b - r) / d + 2.0,
+ _ => (r - g) / d + 4.0,
+ };
+ [h / 6.0, s, l]
+}
+
+fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
+ if s <= 0.0 {
+ return [l, l, l];
+ }
+ let q = match l < 0.5 {
+ true => l * (1.0 + s),
+ false => l + s - l * s,
+ };
+ let p = 2.0 * l - q;
+ let channel = |t: f32| {
+ let t = t.rem_euclid(1.0);
+ match t {
+ t if t < 1.0 / 6.0 => p + (q - p) * 6.0 * t,
+ t if t < 0.5 => q,
+ t if t < 2.0 / 3.0 => p + (q - p) * (2.0 / 3.0 - t) * 6.0,
+ _ => p,
+ }
+ };
+ [channel(h + 1.0 / 3.0), channel(h), channel(h - 1.0 / 3.0)]
+}
+
+fn hsl_shift(rgb: [f32; 3], adjust: &Hsl) -> [f32; 3] {
+ let [h, s, l] = rgb_to_hsl(rgb.map(|c| c.clamp(0.0, 1.0)));
+ let s = (s * (1.0 + adjust.saturation.clamp(-1.0, 4.0))).clamp(0.0, 1.0);
+ let lift = adjust.lightness.clamp(-1.0, 1.0);
+ let l = match lift >= 0.0 {
+ true => l + (1.0 - l) * lift,
+ false => l * (1.0 + lift),
+ };
+ hsl_to_rgb([h + adjust.hue / 360.0, s, l])
+}
+
+fn lum(rgb: [f32; 3]) -> f32 {
+ 0.3 * rgb[0] + 0.59 * rgb[1] + 0.11 * rgb[2]
+}
+
+fn clip_color(rgb: [f32; 3]) -> [f32; 3] {
+ let l = lum(rgb);
+ let (n, x) = (rgb[0].min(rgb[1]).min(rgb[2]), rgb[0].max(rgb[1]).max(rgb[2]));
+ let low = match n < 0.0 && l - n > 1e-9 {
+ true => rgb.map(|c| l + (c - l) * l / (l - n)),
+ false => rgb,
+ };
+ match x > 1.0 && x - l > 1e-9 {
+ true => low.map(|c| l + (c - l) * (1.0 - l) / (x - l)),
+ false => low,
+ }
+}
+
+fn set_lum(rgb: [f32; 3], l: f32) -> [f32; 3] {
+ let d = l - lum(rgb);
+ clip_color(rgb.map(|c| c + d))
+}
+
+pub fn blend_rgb(mode: Blend, b: [f32; 3], s: [f32; 3]) -> [f32; 3] {
+ let each = |f: fn(f32, f32) -> f32| [f(b[0], s[0]), f(b[1], s[1]), f(b[2], s[2])];
+ let screen = |b: f32, s: f32| b + s - b * s;
+ let hard = |b: f32, s: f32| match s <= 0.5 {
+ true => b * 2.0 * s,
+ false => {
+ let t = 2.0 * s - 1.0;
+ b + t - b * t
+ }
+ };
+ match mode {
+ Blend::Normal => s,
+ Blend::Multiply => each(|b, s| b * s),
+ Blend::Screen => [screen(b[0], s[0]), screen(b[1], s[1]), screen(b[2], s[2])],
+ Blend::Overlay => [hard(s[0], b[0]), hard(s[1], b[1]), hard(s[2], b[2])],
+ Blend::Add => each(|b, s| (b + s).min(1.0)),
+ Blend::Darken => each(f32::min),
+ Blend::Lighten => each(f32::max),
+ Blend::ColorDodge => each(|b, s| match (b, s) {
+ (b, _) if b <= 0.0 => 0.0,
+ (_, s) if s >= 1.0 => 1.0,
+ (b, s) => (b / (1.0 - s)).min(1.0),
+ }),
+ Blend::HardLight => [hard(b[0], s[0]), hard(b[1], s[1]), hard(b[2], s[2])],
+ Blend::SoftLight => each(|b, s| match s <= 0.5 {
+ true => b - (1.0 - 2.0 * s) * b * (1.0 - b),
+ false => {
+ let d = match b <= 0.25 {
+ true => ((16.0 * b - 12.0) * b + 4.0) * b,
+ false => libm::sqrtf(b),
+ };
+ b + (2.0 * s - 1.0) * (d - b)
+ }
+ }),
+ Blend::Color => set_lum(s, lum(b)),
+ Blend::Luminosity => set_lum(b, lum(s)),
+ }
+}
+
+pub fn composite(mode: Blend, backdrop: [f32; 4], source: [f32; 4]) -> [f32; 4] {
+ let (ab, a_s) = (backdrop[3], source[3]);
+ let un = |p: [f32; 4]| match p[3] > 0.0 {
+ true => [p[0] / p[3], p[1] / p[3], p[2] / p[3]],
+ false => [0.0; 3],
+ };
+ let (cb, cs) = (un(backdrop), un(source));
+ if mode == Blend::Add {
+ return [0, 1, 2, 3].map(|c| (backdrop[c] + source[c]).min(1.0));
+ }
+ let mixed = blend_rgb(mode, cb, cs);
+ let alpha = a_s + ab * (1.0 - a_s);
+ let rgb = [0, 1, 2].map(|c| a_s * ((1.0 - ab) * cs[c] + ab * mixed[c]) + (1.0 - a_s) * backdrop[c]);
+ [rgb[0], rgb[1], rgb[2], alpha]
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct Rays {
+ pub x: f32,
+ pub y: f32,
+ pub angle: f32,
+ pub spread: f32,
+ pub count: u32,
+ pub length: f32,
+ pub start: f32,
+ pub falloff: f32,
+ pub noise: f32,
+ pub seed: u32,
+}
+
+impl Default for Rays {
+ fn default() -> Self {
+ Self {
+ x: 0.0,
+ y: 0.0,
+ angle: 90.0,
+ spread: 40.0,
+ count: 7,
+ length: 600.0,
+ start: 0.0,
+ falloff: 1.0,
+ noise: 0.5,
+ seed: 1,
+ }
+ }
+}
+
+pub struct Beam {
+ pub quad: [[f32; 2]; 4],
+ pub length: f32,
+ pub strength: f32,
+}
+
+impl Rays {
+ pub fn validate(&self) -> Result<()> {
+ if self.count == 0 || self.count > 256 {
+ bail!("rays: count {} is outside 1..256", self.count);
+ }
+ if self.length <= 0.0 {
+ bail!("rays: length must be above 0");
+ }
+ if !(0.0..=360.0).contains(&self.spread) {
+ bail!("rays: spread {} is outside 0..360 degrees", self.spread);
+ }
+ Ok(())
+ }
+
+ pub fn beams(&self) -> Vec<Beam> {
+ let count = self.count.clamp(1, 256);
+ let step = self.spread / count as f32;
+ let noise = self.noise.clamp(0.0, 1.0);
+ let seed = self.seed;
+ (0..count)
+ .map(|i| {
+ let r = |k: i32| hash2_unit(i as i32, k, seed ^ 0x5241_5953);
+ let middle = self.angle - self.spread / 2.0 + step * (i as f32 + 0.5) + (r(1) - 0.5) * step * noise;
+ let width = step * (0.35 + 0.5 * r(2) * noise + 0.5 * (1.0 - noise));
+ let length = self.length * (1.0 - 0.6 * noise * r(3));
+ let strength = 1.0 - 0.75 * noise * r(4);
+ let dir = |deg: f32| {
+ let a = deg.to_radians();
+ [libm::cosf(a), libm::sinf(a)]
+ };
+ let across = dir(middle + 90.0);
+ let half = self.start / 2.0 / count as f32 * (0.6 + 0.8 * r(5));
+ let foot = [
+ self.x + across[0] * (r(6) - 0.5) * self.start,
+ self.y + across[1] * (r(6) - 0.5) * self.start,
+ ];
+ let (a, b) = (dir(middle - width / 2.0), dir(middle + width / 2.0));
+ Beam {
+ quad: [
+ [foot[0] - across[0] * half, foot[1] - across[1] * half],
+ [
+ foot[0] - across[0] * half + a[0] * length,
+ foot[1] - across[1] * half + a[1] * length,
+ ],
+ [
+ foot[0] + across[0] * half + b[0] * length,
+ foot[1] + across[1] * half + b[1] * length,
+ ],
+ [foot[0] + across[0] * half, foot[1] + across[1] * half],
+ ],
+ length,
+ strength,
+ }
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn close(a: [f32; 3], b: [f32; 3]) -> bool {
+ a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-4)
+ }
+
+ #[test]
+ fn effects_read_with_defaults_and_say_how_far_they_reach() {
+ let list: Vec<Effect> =
+ serde_json::from_str(r#"[{"glow":{}},{"outline":{"width":4}},{"shadow":{"x":-3,"y":10,"radius":2}}]"#)
+ .unwrap();
+ assert_eq!(list[0], Effect::Glow(Glow::default()));
+ assert_eq!(reach(&list), 36.0 + 5.0 + 16.0);
+ assert!(serde_json::from_str::<Effect>(r#"{"glow":{"radious":3}}"#).is_err());
+ assert!(
+ Effect::Outline(Outline {
+ color: "red".into(),
+ ..Outline::default()
+ })
+ .validate()
+ .is_err()
+ );
+ assert_eq!(
+ serde_json::to_string(&list[1]).unwrap(),
+ r##"{"outline":{"width":4.0,"color":"#1b1b1b"}}"##
+ );
+ EFFECTS
+ .iter()
+ .for_each(|n| assert_eq!(Effect::named(n).unwrap().name(), *n));
+ }
+
+ #[test]
+ fn levels_curves_and_maps_do_what_they_say() {
+ let levels = Adjustment::Levels(Levels {
+ black: 0.2,
+ white: 0.6,
+ gamma: 1.0,
+ low: 0.0,
+ high: 1.0,
+ })
+ .prepare()
+ .unwrap();
+ assert!(close(levels.apply([0.1, 0.4, 0.9]), [0.0, 0.5, 1.0]));
+ let identity = Adjustment::Curves(Curves::default()).prepare().unwrap();
+ assert!(close(identity.apply([0.13, 0.5, 0.77]), [0.13, 0.5, 0.77]));
+ let dusk = Adjustment::Curves(Curves {
+ points: vec![[0.0, 0.0], [0.5, 0.3], [1.0, 0.8]],
+ blue: vec![[0.0, 0.1], [1.0, 1.0]],
+ ..Curves::default()
+ })
+ .prepare()
+ .unwrap();
+ let out = dusk.apply([0.5, 0.5, 0.0]);
+ assert!((out[0] - 0.3).abs() < 1e-3 && (out[1] - 0.3).abs() < 1e-3, "{out:?}");
+ assert!(out[2] > 0.0 && out[2] < 0.1, "{out:?}");
+ let steep = Adjustment::Curves(Curves {
+ points: vec![[0.0, 0.0], [0.4, 0.9], [0.6, 0.95], [1.0, 1.0]],
+ ..Curves::default()
+ })
+ .prepare()
+ .unwrap();
+ let ys: Vec<f32> = (0..=100).map(|i| steep.apply([i as f32 / 100.0; 3])[0]).collect();
+ assert!(ys.windows(2).all(|w| w[1] >= w[0] - 1e-6) && ys.iter().all(|y| *y <= 1.0 + 1e-6));
+ let map = Adjustment::GradientMap(GradientMap {
+ stops: vec![Stop(0.0, "#000000".into()), Stop(1.0, "#ff0000".into())],
+ })
+ .prepare()
+ .unwrap();
+ assert!(close(map.apply([1.0, 1.0, 1.0]), [1.0, 0.0, 0.0]));
+ assert!(close(map.apply([0.5, 0.5, 0.5]), [0.5, 0.0, 0.0]));
+ assert!(
+ Adjustment::Levels(Levels {
+ white: 0.1,
+ black: 0.2,
+ ..Levels::default()
+ })
+ .prepare()
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn hue_turns_and_balance_keeps_the_light() {
+ let turn = Adjustment::Hsl(Hsl {
+ hue: 120.0,
+ ..Hsl::default()
+ })
+ .prepare()
+ .unwrap();
+ assert!(close(turn.apply([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0]));
+ let grey = Adjustment::Hsl(Hsl {
+ saturation: -1.0,
+ ..Hsl::default()
+ })
+ .prepare()
+ .unwrap()
+ .apply([0.8, 0.2, 0.4]);
+ assert!((grey[0] - grey[1]).abs() < 1e-5 && (grey[1] - grey[2]).abs() < 1e-5);
+ let warm = Adjustment::Balance(Balance {
+ midtones: [0.4, 0.0, -0.4],
+ ..Balance::default()
+ })
+ .prepare()
+ .unwrap();
+ let out = warm.apply([0.5, 0.5, 0.5]);
+ assert!(out[0] > out[1] && out[1] > out[2], "{out:?}");
+ assert!((lum(out) - lum([0.5; 3])).abs() < 1e-4);
+ }
+
+ #[test]
+ fn blend_formulas_meet_their_known_values() {
+ let (b, s) = ([0.2, 0.5, 0.8], [0.6, 0.3, 0.9]);
+ assert!(close(blend_rgb(Blend::Multiply, b, s), [0.12, 0.15, 0.72]));
+ assert!(close(blend_rgb(Blend::Screen, b, s), [0.68, 0.65, 0.98]));
+ assert!(close(blend_rgb(Blend::Darken, b, s), [0.2, 0.3, 0.8]));
+ assert!(close(blend_rgb(Blend::Lighten, b, s), [0.6, 0.5, 0.9]));
+ assert!(close(blend_rgb(Blend::ColorDodge, b, s), [0.5, 0.5 / 0.7, 1.0]));
+ assert!(close(blend_rgb(Blend::HardLight, b, s), [0.36, 0.3, 0.96]));
+ let lumed = blend_rgb(Blend::Luminosity, b, s);
+ assert!((lum(lumed) - lum(s)).abs() < 1e-5);
+ assert_eq!(
+ composite(Blend::Normal, [0.0, 0.0, 1.0, 1.0], [0.5, 0.0, 0.0, 0.5]),
+ [0.5, 0.0, 0.5, 1.0]
+ );
+ }
+
+ #[test]
+ fn rays_repeat_with_their_seed() {
+ let rays = Rays {
+ x: 100.0,
+ y: 50.0,
+ ..Rays::default()
+ };
+ let a: Vec<_> = rays.beams().iter().map(|b| (b.quad, b.strength)).collect();
+ let b: Vec<_> = rays.beams().iter().map(|b| (b.quad, b.strength)).collect();
+ let c: Vec<_> = Rays {
+ seed: 2,
+ ..rays.clone()
+ }
+ .beams()
+ .iter()
+ .map(|b| (b.quad, b.strength))
+ .collect();
+ assert_eq!(a, b);
+ assert_ne!(a, c);
+ assert_eq!(a.len(), 7);
+ assert!(rays.beams().iter().all(|b| b.quad[1][1] > 50.0 && b.length <= 600.0));
+ }
+}
diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rs
new file mode 100644
index 0000000..6c4aba9
--- /dev/null
+++ b/crates/core/src/markedit.rs
@@ -0,0 +1,1039 @@
+use crate::color::{parse_hex, to_u16};
+use crate::cut::{self, Cut, Keep, inside_polygon};
+use crate::fill::{Coverage, Fill, FillSource};
+use crate::stroke::{Mark, POS_SCALE, Sample, Stroke, next_id};
+use anyhow::{Result, anyhow, bail};
+use serde_json::{Map, Value};
+
+pub type Affine = [f32; 6];
+
+pub const IDENTITY: Affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
+const STROKE_KEYS: &[&str] = &["color", "size", "opacity", "flow", "brush", "taper", "path"];
+const FILL_KEYS: &[&str] = &["color", "opacity"];
+pub const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];
+
+pub fn parse_address(text: &str) -> Option<(&str, u32)> {
+ let (cel, mark) = text.split_once(':')?;
+ let id = mark.strip_prefix('s')?.parse().ok()?;
+ crate::doc::valid_id(cel).then_some((cel, id))
+}
+
+pub fn address(cel: &str, id: u32) -> String {
+ format!("{cel}:s{id}")
+}
+
+pub fn apply_affine(a: Affine, (x, y): (f32, f32)) -> (f32, f32) {
+ (a[0] * x + a[1] * y + a[4], a[2] * x + a[3] * y + a[5])
+}
+
+pub fn invert(a: Affine) -> Option<Affine> {
+ let det = a[0] * a[3] - a[1] * a[2];
+ if det.abs() < 1e-12 {
+ return None;
+ }
+ let (ia, ib, ic, id) = (a[3] / det, -a[1] / det, -a[2] / det, a[0] / det);
+ Some([ia, ib, ic, id, -(ia * a[4] + ib * a[5]), -(ic * a[4] + id * a[5])])
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct MarkTransform {
+ pub x: f32,
+ pub y: f32,
+ pub rotate: f32,
+ pub sx: f32,
+ pub sy: f32,
+ pub pivot: Option<[f32; 2]>,
+}
+
+impl Default for MarkTransform {
+ fn default() -> Self {
+ Self {
+ x: 0.0,
+ y: 0.0,
+ rotate: 0.0,
+ sx: 1.0,
+ sy: 1.0,
+ pivot: None,
+ }
+ }
+}
+
+impl MarkTransform {
+ pub fn parse(map: &mut Map<String, Value>) -> Result<Self> {
+ let mut t = Self::default();
+ let mut number = |key: &str, slot: &mut f32| -> Result<()> {
+ if let Some(v) = map.remove(key) {
+ *slot = v.as_f64().ok_or_else(|| anyhow!("{key} must be a number"))? as f32;
+ }
+ Ok(())
+ };
+ number("x", &mut t.x)?;
+ number("y", &mut t.y)?;
+ number("rotate", &mut t.rotate)?;
+ number("sx", &mut t.sx)?;
+ number("sy", &mut t.sy)?;
+ if let Some(scale) = map.remove("scale") {
+ let k = scale.as_f64().ok_or_else(|| anyhow!("scale must be a number"))? as f32;
+ t.sx *= k;
+ t.sy *= k;
+ }
+ t.pivot = match map.remove("pivot") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(serde_json::from_value(v).map_err(|_| anyhow!("pivot must be [x, y]"))?),
+ };
+ if t.sx == 0.0 || t.sy == 0.0 {
+ bail!("sx and sy cannot be 0");
+ }
+ Ok(t)
+ }
+
+ pub fn affine(&self, pivot: [f32; 2]) -> Affine {
+ let (s, c) = (
+ libm::sinf(self.rotate.to_radians()),
+ libm::cosf(self.rotate.to_radians()),
+ );
+ let (a, b, cc, d) = (c * self.sx, -s * self.sy, s * self.sx, c * self.sy);
+ let [px, py] = pivot;
+ [
+ a,
+ b,
+ cc,
+ d,
+ px + self.x - (a * px + b * py),
+ py + self.y - (cc * px + d * py),
+ ]
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum MarkChange {
+ Add(Vec<Mark>),
+ Set {
+ id: u32,
+ props: Map<String, Value>,
+ },
+ Remove {
+ id: u32,
+ },
+ Transform {
+ ids: Vec<u32>,
+ transform: MarkTransform,
+ },
+ Lasso {
+ polygon: Vec<[f32; 2]>,
+ cut: bool,
+ action: LassoAction,
+ chosen: Vec<u32>,
+ },
+ Copy {
+ layer: String,
+ cel: String,
+ upto: usize,
+ },
+ Paste {
+ sources: Vec<Source>,
+ transform: Option<MarkTransform>,
+ cut: Option<Vec<[f32; 2]>>,
+ made: Vec<Copied>,
+ },
+ Put(Vec<Mark>),
+ Part {
+ name: String,
+ count: usize,
+ ids: Vec<u32>,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Source {
+ pub layer: String,
+ pub cel: String,
+ pub ids: Vec<u32>,
+ pub upto: usize,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Copied {
+ pub cel: String,
+ pub from: u32,
+ pub to: u32,
+}
+
+impl MarkChange {
+ pub fn ids(&self) -> Vec<u32> {
+ match self {
+ MarkChange::Add(marks) => marks.iter().map(Mark::id).collect(),
+ MarkChange::Set { id, .. } | MarkChange::Remove { id } => vec![*id],
+ MarkChange::Transform { ids, .. } => ids.clone(),
+ MarkChange::Lasso { chosen, .. } => chosen.clone(),
+ MarkChange::Paste { made, .. } => made.iter().map(|c| c.to).collect(),
+ MarkChange::Put(marks) => marks.iter().map(Mark::id).collect(),
+ MarkChange::Copy { .. } | MarkChange::Part { .. } => Vec::new(),
+ }
+ }
+
+ pub fn brushes(&self) -> Vec<&str> {
+ match self {
+ MarkChange::Add(marks) | MarkChange::Put(marks) => {
+ crate::stroke::strokes_of(marks).map(|s| s.brush.as_str()).collect()
+ }
+ MarkChange::Set { props, .. } => props.get("brush").and_then(Value::as_str).into_iter().collect(),
+ _ => Vec::new(),
+ }
+ }
+}
+
+pub fn union(marks: &[&Mark]) -> Option<[f32; 4]> {
+ marks
+ .iter()
+ .filter_map(|m| m.bounds())
+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])
+}
+
+fn number(props: &Map<String, Value>, key: &str) -> Result<Option<f32>> {
+ props
+ .get(key)
+ .map(|v| {
+ v.as_f64()
+ .map(|f| f as f32)
+ .ok_or_else(|| anyhow!("{key} must be a number"))
+ })
+ .transpose()
+}
+
+fn check_keys(props: &Map<String, Value>, allowed: &[&str], what: &str) -> Result<()> {
+ props.keys().try_for_each(|key| {
+ if allowed.contains(&key.as_str()) {
+ Ok(())
+ } else {
+ bail!("a {what} has no {key:?}; it takes {}", allowed.join(", "))
+ }
+ })
+}
+
+fn opacity(props: &Map<String, Value>) -> Result<Option<f32>> {
+ let value = number(props, "opacity")?;
+ if value.is_some_and(|o| !(0.0..=1.0).contains(&o)) {
+ bail!("opacity must be within 0..1");
+ }
+ Ok(value)
+}
+
+fn color(props: &Map<String, Value>) -> Result<Option<[u16; 4]>> {
+ props
+ .get("color")
+ .map(|v| {
+ let text = v.as_str().ok_or_else(|| anyhow!("color must be a string"))?;
+ Ok(to_u16(parse_hex(text)?))
+ })
+ .transpose()
+}
+
+fn set_stroke(stroke: &mut Stroke, props: &Map<String, Value>) -> Result<()> {
+ check_keys(props, STROKE_KEYS, "stroke")?;
+ if let Some(c) = color(props)? {
+ stroke.color = c;
+ }
+ if let Some(o) = opacity(props)? {
+ stroke.opacity = o;
+ }
+ match (number(props, "size")?, number(props, "flow")?) {
+ (Some(s), _) if s <= 0.0 => bail!("size must be positive"),
+ (_, Some(f)) if f <= 0.0 => bail!("flow must be positive"),
+ (size, flow) => {
+ stroke.size = size.unwrap_or(stroke.size);
+ stroke.flow = flow.unwrap_or(stroke.flow);
+ }
+ }
+ if let Some(brush) = props.get("brush") {
+ let id = brush.as_str().ok_or_else(|| anyhow!("brush must be a brush id"))?;
+ if !crate::doc::valid_id(id) {
+ bail!("brush id {id:?} may only use letters, digits, - and _");
+ }
+ stroke.brush = id.to_string();
+ }
+ match props.get("taper") {
+ None => {}
+ Some(Value::Null) => stroke.taper = [0.0, 0.0],
+ Some(v) => {
+ let taper: [f32; 2] =
+ serde_json::from_value(v.clone()).map_err(|_| anyhow!("taper must be [in, out] lengths in px"))?;
+ if taper.iter().any(|t| !(0.0..=10_000.0).contains(t)) {
+ bail!("taper lengths must be within 0..10000 px");
+ }
+ stroke.taper = taper;
+ }
+ }
+ if let Some(path) = props.get("path") {
+ let d = path.as_str().ok_or_else(|| anyhow!("path must be SVG path data"))?;
+ reshape(stroke, d)?;
+ }
+ Ok(())
+}
+
+fn running(points: &[[f32; 2]]) -> Vec<f32> {
+ points
+ .iter()
+ .scan((None::<[f32; 2]>, 0.0f32), |(last, total), p| {
+ if let Some(q) = last {
+ *total += libm::sqrtf((p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]));
+ }
+ *last = Some(*p);
+ Some(*total)
+ })
+ .collect()
+}
+
+fn at_length(line: &[[f32; 2]], lengths: &[f32], at: f32) -> [f32; 2] {
+ let i = lengths.partition_point(|l| *l < at).clamp(1, line.len().max(2) - 1);
+ let (a, b) = (line[i - 1], line[i]);
+ let span = (lengths[i] - lengths[i - 1]).max(1e-6);
+ let t = ((at - lengths[i - 1]) / span).clamp(0.0, 1.0);
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
+}
+
+pub fn reshape(stroke: &mut Stroke, d: &str) -> Result<()> {
+ let line: Vec<[f32; 2]> = crate::path::flatten(d)?.into_iter().flatten().collect();
+ if line.is_empty() {
+ bail!("the path has no points");
+ }
+ let place = |s: &mut Sample, p: [f32; 2]| {
+ s.x = (p[0] * POS_SCALE).round() as i32;
+ s.y = (p[1] * POS_SCALE).round() as i32;
+ };
+ if line.len() == 1 {
+ stroke.samples.iter_mut().for_each(|s| place(s, line[0]));
+ return Ok(());
+ }
+ let old: Vec<[f32; 2]> = stroke
+ .samples
+ .iter()
+ .map(|s| {
+ let (x, y) = s.pos();
+ [x, y]
+ })
+ .collect();
+ let (before, after) = (running(&old), running(&line));
+ let (from, to) = (
+ before.last().copied().unwrap_or(0.0),
+ after.last().copied().unwrap_or(0.0),
+ );
+ stroke.samples.iter_mut().zip(&before).for_each(|(s, walked)| {
+ let t = if from > 0.0 { walked / from } else { 0.0 };
+ place(s, at_length(&line, &after, t * to));
+ });
+ Ok(())
+}
+
+fn set_fill(fill: &mut Fill, props: &Map<String, Value>) -> Result<()> {
+ check_keys(props, FILL_KEYS, "fill")?;
+ if let Some(c) = color(props)? {
+ fill.color = c;
+ }
+ if let Some(o) = opacity(props)? {
+ fill.opacity = o;
+ }
+ Ok(())
+}
+
+pub fn transform_stroke(stroke: &mut Stroke, a: Affine) {
+ let scale = libm::sqrtf((a[0] * a[3] - a[1] * a[2]).abs());
+ stroke.samples.iter_mut().for_each(|s| {
+ let (x, y) = apply_affine(a, s.pos());
+ let (tx, ty) = s.tilt();
+ let amount = libm::sqrtf(tx * tx + ty * ty);
+ let (dx, dy) = (a[0] * tx + a[1] * ty, a[2] * tx + a[3] * ty);
+ let len = libm::sqrtf(dx * dx + dy * dy);
+ let tilt = if len > 1e-6 {
+ (dx / len * amount, dy / len * amount)
+ } else {
+ (tx, ty)
+ };
+ *s = Sample::quantize(x, y, s.pressure(), tilt, s.dt_ms as f32);
+ });
+ stroke.size = (stroke.size * scale).max(0.05);
+ stroke.taper = stroke.taper.map(|t| t * scale);
+ stroke.cuts.iter_mut().for_each(|c| c.map(|p| mapped(a, p)));
+}
+
+fn mapped(a: Affine, p: [f32; 2]) -> [f32; 2] {
+ let (x, y) = apply_affine(a, (p[0], p[1]));
+ [x, y]
+}
+
+fn translation(a: Affine) -> Option<(i64, i64)> {
+ let plain = a[0] == 1.0 && a[1] == 0.0 && a[2] == 0.0 && a[3] == 1.0;
+ plain.then(|| (a[4].round() as i64, a[5].round() as i64))
+}
+
+fn shifted(c: &Coverage, dx: i64, dy: i64) -> Coverage {
+ let (x0, y0) = (c.x as i64 + dx, c.y as i64 + dy);
+ let (cut_x, cut_y) = ((-x0).max(0), (-y0).max(0));
+ let (w, h) = (c.width as i64 - cut_x, c.height as i64 - cut_y);
+ if w <= 0 || h <= 0 {
+ return Coverage::default();
+ }
+ let alpha = (cut_y..c.height as i64)
+ .flat_map(|row| {
+ let start = (row * c.width as i64 + cut_x) as usize;
+ c.alpha[start..start + w as usize].iter().copied()
+ })
+ .collect();
+ Coverage {
+ x: (x0 + cut_x) as u32,
+ y: (y0 + cut_y) as u32,
+ width: w as u32,
+ height: h as u32,
+ alpha,
+ }
+}
+
+fn resampled(c: &Coverage, a: Affine) -> Coverage {
+ let Some(inverse) = invert(a) else {
+ return Coverage::default();
+ };
+ let (x0, y0, x1, y1) = (c.x as f32, c.y as f32, (c.x + c.width) as f32, (c.y + c.height) as f32);
+ let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|p| apply_affine(a, p));
+ let lo = |f: fn(&(f32, f32)) -> f32| corners.iter().map(f).fold(f32::MAX, f32::min);
+ let hi = |f: fn(&(f32, f32)) -> f32| corners.iter().map(f).fold(f32::MIN, f32::max);
+ let (bx0, by0) = (lo(|p| p.0).floor().max(0.0) as u32, lo(|p| p.1).floor().max(0.0) as u32);
+ let (bx1, by1) = (hi(|p| p.0).ceil().max(0.0) as u32, hi(|p| p.1).ceil().max(0.0) as u32);
+ if bx1 <= bx0 || by1 <= by0 {
+ return Coverage::default();
+ }
+ let (w, h) = (bx1 - bx0, by1 - by0);
+ let at = |x: i64, y: i64| -> f32 {
+ if x < 0 || y < 0 {
+ return 0.0;
+ }
+ c.at(x as u32, y as u32) as f32
+ };
+ let mask: Vec<u8> = (0..h)
+ .flat_map(|j| (0..w).map(move |i| (i, j)))
+ .map(|(i, j)| {
+ let (sx, sy) = apply_affine(inverse, ((bx0 + i) as f32 + 0.5, (by0 + j) as f32 + 0.5));
+ let (fx, fy) = (sx - 0.5, sy - 0.5);
+ let (ix, iy) = (fx.floor() as i64, fy.floor() as i64);
+ let (tx, ty) = (fx - ix as f32, fy - iy as f32);
+ let top = at(ix, iy) * (1.0 - tx) + at(ix + 1, iy) * tx;
+ let bottom = at(ix, iy + 1) * (1.0 - tx) + at(ix + 1, iy + 1) * tx;
+ (top * (1.0 - ty) + bottom * ty).round().clamp(0.0, 255.0) as u8
+ })
+ .collect();
+ let mut out = Coverage::from_mask(w, h, &mask);
+ if !out.is_empty() {
+ out.x += bx0;
+ out.y += by0;
+ }
+ out
+}
+
+pub fn transform_fill(fill: &mut Fill, a: Affine) {
+ let map = |p: [f32; 2]| mapped(a, p);
+ match &mut fill.source {
+ FillSource::Seed { seed, .. } => [seed.x, seed.y] = map([seed.x, seed.y]),
+ FillSource::Polygon(points) => points.iter_mut().for_each(|p| *p = map(*p)),
+ }
+ let (coverage, region) = match translation(a) {
+ Some((dx, dy)) => (
+ shifted(&fill.coverage, dx, dy),
+ [1.0, 0.0, 0.0, 1.0, dx as f32, dy as f32],
+ ),
+ None => (resampled(&fill.coverage, a), a),
+ };
+ fill.coverage = coverage;
+ fill.cuts.iter_mut().for_each(|c| c.map(|p| mapped(region, p)));
+}
+
+pub fn transform_mark(mark: &mut Mark, a: Affine) {
+ match mark {
+ Mark::Stroke(s) => transform_stroke(s, a),
+ Mark::Fill(f) => transform_fill(f, a),
+ }
+}
+
+fn to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let span = dx * dx + dy * dy;
+ let t = if span < 1e-9 {
+ 0.0
+ } else {
+ (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / span).clamp(0.0, 1.0)
+ };
+ let (x, y) = (a.0 + dx * t - p.0, a.1 + dy * t - p.1);
+ libm::sqrtf(x * x + y * y)
+}
+
+fn touches(mark: &Mark, at: (f32, f32), slack: f32) -> bool {
+ match mark {
+ Mark::Stroke(s) => {
+ let reach = s.size / 2.0 + slack;
+ let points: Vec<(f32, f32)> = s.samples.iter().map(Sample::pos).collect();
+ match points.len() {
+ 0 => false,
+ 1 => to_segment(at, points[0], points[0]) <= reach,
+ _ => points.windows(2).any(|w| to_segment(at, w[0], w[1]) <= reach),
+ }
+ }
+ Mark::Fill(f) => at.0 >= 0.0 && at.1 >= 0.0 && f.coverage.at(at.0 as u32, at.1 as u32) > 0,
+ }
+}
+
+pub fn hit(marks: &[Mark], at: (f32, f32), slack: f32) -> Option<u32> {
+ marks
+ .iter()
+ .rev()
+ .find(|m| cut::keeps(m.cuts(), at) && touches(m, at, slack))
+ .map(Mark::id)
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Side {
+ Inside,
+ Crossing,
+ Outside,
+}
+
+fn fill_side(fill: &Fill, polygon: &[[f32; 2]]) -> Side {
+ let c = &fill.coverage;
+ let (inside, outside) = (0..c.height).fold((false, false), |(inside, outside), row| {
+ if inside && outside {
+ return (inside, outside);
+ }
+ let y = (c.y + row) as f32 + 0.5;
+ let xs = cut::crossings(polygon, y);
+ let line = &c.alpha[(row * c.width) as usize..((row + 1) * c.width) as usize];
+ line.iter()
+ .enumerate()
+ .filter(|(_, a)| **a > 0)
+ .map(|(i, _)| ((c.x + i as u32) as f32 + 0.5, y))
+ .filter(|p| cut::keeps(&fill.cuts, *p))
+ .fold((inside, outside), |(inside, outside), p| {
+ let odd = xs.iter().filter(|x| **x > p.0).count() % 2 == 1;
+ (inside || odd, outside || !odd)
+ })
+ });
+ match (inside, outside) {
+ (true, false) => Side::Inside,
+ (true, true) => Side::Crossing,
+ _ => Side::Outside,
+ }
+}
+
+pub fn side(mark: &Mark, polygon: &[[f32; 2]]) -> Side {
+ match mark {
+ Mark::Stroke(s) => {
+ let kept: Vec<(f32, f32)> = s
+ .samples
+ .iter()
+ .map(Sample::pos)
+ .filter(|p| cut::keeps(&s.cuts, *p))
+ .collect();
+ let inside = kept.iter().filter(|p| inside_polygon(polygon, **p)).count();
+ match inside {
+ 0 => Side::Outside,
+ n if n == kept.len() => Side::Inside,
+ _ => Side::Crossing,
+ }
+ }
+ Mark::Fill(f) => fill_side(f, polygon),
+ }
+}
+
+pub fn lassoed(marks: &[Mark], polygon: &[[f32; 2]]) -> Vec<u32> {
+ sides(marks, polygon)
+ .into_iter()
+ .filter(|(_, side)| *side == Side::Inside)
+ .map(|(id, _)| id)
+ .collect()
+}
+
+pub fn sides(marks: &[Mark], polygon: &[[f32; 2]]) -> Vec<(u32, Side)> {
+ if polygon.len() < 3 {
+ return Vec::new();
+ }
+ marks
+ .iter()
+ .map(|m| (m.id(), side(m, polygon)))
+ .filter(|(_, side)| *side != Side::Outside)
+ .collect()
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum LassoAction {
+ Transform(MarkTransform),
+ Remove,
+}
+
+pub fn split(marks: &mut Vec<Mark>, polygon: &[[f32; 2]], cut: bool) -> Vec<u32> {
+ let found = sides(marks, polygon);
+ let mut next = next_id(marks);
+ let mut chosen: Vec<u32> = found
+ .iter()
+ .filter(|(_, s)| *s == Side::Inside)
+ .map(|(id, _)| *id)
+ .collect();
+ if !cut {
+ return chosen;
+ }
+ let crossing: Vec<u32> = found
+ .iter()
+ .filter(|(_, s)| *s == Side::Crossing)
+ .map(|(id, _)| *id)
+ .collect();
+ let sliced = std::mem::take(marks).into_iter().flat_map(|mut mark| {
+ if !crossing.contains(&mark.id()) {
+ return vec![mark];
+ }
+ let mut part = mark.clone();
+ part.set_id(next);
+ chosen.push(next);
+ next += 1;
+ mark.cuts_mut().push(Cut {
+ keep: Keep::Outside,
+ polygon: polygon.to_vec(),
+ });
+ part.cuts_mut().push(Cut {
+ keep: Keep::Inside,
+ polygon: polygon.to_vec(),
+ });
+ vec![mark, part]
+ });
+ *marks = sliced.collect();
+ chosen
+}
+
+pub fn bounds_of(marks: &[Mark], ids: &[u32]) -> Option<[f32; 4]> {
+ let chosen: Vec<&Mark> = marks.iter().filter(|m| ids.contains(&m.id())).collect();
+ union(&chosen)
+}
+
+fn position(marks: &[Mark], cel: &str, id: u32) -> Result<usize> {
+ marks
+ .iter()
+ .position(|m| m.id() == id)
+ .ok_or_else(|| anyhow!("{} does not exist", address(cel, id)))
+}
+
+pub fn apply(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str) -> Result<()> {
+ match change {
+ MarkChange::Add(added) => {
+ let next = next_id(marks);
+ added
+ .iter_mut()
+ .enumerate()
+ .for_each(|(i, m)| m.set_id(next + i as u32));
+ marks.extend(added.iter().cloned());
+ }
+ MarkChange::Set { id, props } => {
+ let at = position(marks, cel, *id)?;
+ let what = address(cel, *id);
+ match &mut marks[at] {
+ Mark::Stroke(s) => set_stroke(s, props),
+ Mark::Fill(f) => set_fill(f, props),
+ }
+ .map_err(|e| anyhow!("set {what}: {e}"))?;
+ }
+ MarkChange::Remove { id } => {
+ let at = position(marks, cel, *id)?;
+ marks.remove(at);
+ }
+ MarkChange::Transform { ids, transform } => transform_marks(marks, ids, transform, cel)?,
+ MarkChange::Lasso {
+ polygon,
+ cut,
+ action,
+ chosen,
+ } => {
+ if polygon.len() < 3 {
+ bail!("a lasso needs at least 3 points");
+ }
+ *chosen = split(marks, polygon, *cut);
+ if chosen.is_empty() {
+ bail!(
+ "the lasso holds no strokes or fills of {cel}{}",
+ if *cut {
+ ""
+ } else {
+ " whole (cut takes the parts crossing its edge)"
+ }
+ );
+ }
+ match action {
+ LassoAction::Transform(transform) => transform_marks(marks, chosen, transform, cel)?,
+ LassoAction::Remove => marks.retain(|m| !chosen.contains(&m.id())),
+ }
+ }
+ MarkChange::Put(put) => *marks = put.clone(),
+ MarkChange::Part { count, ids, .. } if *count > 0 => {
+ if *count > marks.len() {
+ bail!("{cel} has {} marks, fewer than the {count} just added", marks.len());
+ }
+ *ids = marks[marks.len() - *count..].iter().map(Mark::id).collect();
+ }
+ MarkChange::Part { ids, .. } => {
+ ids.iter().try_for_each(|id| position(marks, cel, *id).map(|_| ()))?;
+ }
+ MarkChange::Copy { cel: from, .. } => {
+ bail!("{cel} copies the marks of {from}; copies are resolved by the bundle")
+ }
+ MarkChange::Paste { .. } => bail!("{cel} takes copies of other marks; copies are resolved by the bundle"),
+ }
+ Ok(())
+}
+
+pub fn paste(
+ marks: &mut Vec<Mark>,
+ copies: Vec<(String, Mark)>,
+ transform: Option<&MarkTransform>,
+ cut: Option<&[[f32; 2]]>,
+) -> Result<Vec<Copied>> {
+ let mut next = next_id(marks);
+ let (made, mut copied): (Vec<Copied>, Vec<Mark>) = copies
+ .into_iter()
+ .map(|(cel, mut mark)| {
+ let from = mark.id();
+ mark.set_id(next);
+ next += 1;
+ if let Some(polygon) = cut {
+ mark.cuts_mut().push(Cut {
+ keep: Keep::Inside,
+ polygon: polygon.to_vec(),
+ });
+ }
+ (
+ Copied {
+ cel,
+ from,
+ to: mark.id(),
+ },
+ mark,
+ )
+ })
+ .unzip();
+ if let Some(t) = transform {
+ let pivot = match t.pivot {
+ Some(p) => p,
+ None => {
+ let [x0, y0, x1, y1] =
+ union(&copied.iter().collect::<Vec<_>>()).ok_or_else(|| anyhow!("the copies cover nothing"))?;
+ [(x0 + x1) / 2.0, (y0 + y1) / 2.0]
+ }
+ };
+ let a = t.affine(pivot);
+ copied.iter_mut().for_each(|m| transform_mark(m, a));
+ }
+ marks.extend(copied);
+ Ok(made)
+}
+
+fn transform_marks(marks: &mut [Mark], ids: &[u32], transform: &MarkTransform, cel: &str) -> Result<()> {
+ let at: Vec<usize> = ids.iter().map(|id| position(marks, cel, *id)).collect::<Result<_>>()?;
+ let pivot = match transform.pivot {
+ Some(p) => p,
+ None => {
+ let chosen: Vec<&Mark> = at.iter().map(|&i| &marks[i]).collect();
+ let [x0, y0, x1, y1] = union(&chosen).ok_or_else(|| anyhow!("nothing to transform"))?;
+ [(x0 + x1) / 2.0, (y0 + y1) / 2.0]
+ }
+ };
+ let a = transform.affine(pivot);
+ at.iter().for_each(|&i| transform_mark(&mut marks[i], a));
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fill::{FillRef, Seed};
+ use serde_json::json;
+
+ fn line(id: u32) -> Mark {
+ Stroke::new(id, "ink", [0.0, 0.0, 0.0, 1.0], 10.0, 1)
+ .with_points(&[(10.0, 10.0, 1.0), (30.0, 10.0, 1.0)], 4.0)
+ .tapered([4.0, 8.0])
+ .into()
+ }
+
+ fn square(id: u32) -> Mark {
+ let mut mask = vec![0u8; 64 * 64];
+ (20..30).for_each(|y| (20..40).for_each(|x| mask[y * 64 + x] = 255));
+ let source = FillSource::Seed {
+ seed: Seed {
+ x: 25.0,
+ y: 25.0,
+ tolerance: 0.1,
+ gap: 0.0,
+ expand: 2.0,
+ },
+ reference: FillRef::This,
+ };
+ Fill::new(id, [1.0, 0.0, 0.0, 1.0], source, Coverage::from_mask(64, 64, &mask)).into()
+ }
+
+ fn props(value: Value) -> Map<String, Value> {
+ value.as_object().unwrap().clone()
+ }
+
+ #[test]
+ fn addresses_name_a_cel_and_a_mark() {
+ assert_eq!(parse_address("c4:s12"), Some(("c4", 12)));
+ assert_eq!(parse_address("c4:12"), None);
+ assert_eq!(parse_address("n5"), None);
+ assert_eq!(parse_address("c 4:s1"), None);
+ assert_eq!(address("c4", 12), "c4:s12");
+ }
+
+ #[test]
+ fn set_changes_strokes_and_fills_and_rejects_typos() {
+ let mut marks = vec![line(1), square(2)];
+ let mut set = MarkChange::Set {
+ id: 1,
+ props: props(json!({"color":"#ff0000","size":4,"brush":"pencil","taper":null})),
+ };
+ apply(&mut marks, &mut set, "c1").unwrap();
+ let s = marks[0].as_stroke().unwrap();
+ assert_eq!(
+ (s.color, s.size, s.brush.as_str(), s.taper),
+ ([65535, 0, 0, 65535], 4.0, "pencil", [0.0, 0.0])
+ );
+ let mut fill = MarkChange::Set {
+ id: 2,
+ props: props(json!({"opacity":0.5})),
+ };
+ apply(&mut marks, &mut fill, "c1").unwrap();
+ assert_eq!(marks[1].as_fill().unwrap().opacity, 0.5);
+ let mut typo = MarkChange::Set {
+ id: 2,
+ props: props(json!({"size":3})),
+ };
+ let err = apply(&mut marks, &mut typo, "c1").unwrap_err().to_string();
+ assert!(err.contains("c1:s2") && err.contains("color, opacity"), "{err}");
+ let mut missing = MarkChange::Remove { id: 9 };
+ assert!(
+ apply(&mut marks, &mut missing, "c1")
+ .unwrap_err()
+ .to_string()
+ .contains("c1:s9")
+ );
+ }
+
+ #[test]
+ fn transforms_move_rotate_and_scale_about_the_middle() {
+ let mut marks = vec![line(1)];
+ let mut moved = MarkChange::Transform {
+ ids: vec![1],
+ transform: MarkTransform {
+ x: 5.0,
+ y: -2.5,
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut moved, "c1").unwrap();
+ assert_eq!(marks[0].as_stroke().unwrap().samples[0].pos(), (15.0, 7.5));
+ let mut turned = MarkChange::Transform {
+ ids: vec![1],
+ transform: MarkTransform {
+ rotate: 90.0,
+ sx: 2.0,
+ sy: 2.0,
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut turned, "c1").unwrap();
+ let s = marks[0].as_stroke().unwrap();
+ let (a, b) = (s.samples[0].pos(), s.samples[1].pos());
+ assert!((a.0 - 25.0).abs() < 0.07 && (a.1 + 12.5).abs() < 0.07, "{a:?}");
+ assert!((b.0 - 25.0).abs() < 0.07 && (b.1 - 27.5).abs() < 0.07, "{b:?}");
+ assert_eq!((s.size, s.taper), (20.0, [8.0, 16.0]));
+ }
+
+ #[test]
+ fn fills_move_by_whole_pixels_and_resample_otherwise() {
+ let mut marks = vec![square(1)];
+ let mut moved = MarkChange::Transform {
+ ids: vec![1],
+ transform: MarkTransform {
+ x: -25.2,
+ y: 3.0,
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut moved, "c1").unwrap();
+ let f = marks[0].as_fill().unwrap();
+ assert_eq!(
+ (f.coverage.x, f.coverage.y, f.coverage.width, f.coverage.height),
+ (0, 23, 15, 10)
+ );
+ assert_eq!(f.coverage.pixels(), 150);
+ let mut marks = vec![square(1)];
+ let mut doubled = MarkChange::Transform {
+ ids: vec![1],
+ transform: MarkTransform {
+ sx: 2.0,
+ sy: 2.0,
+ pivot: Some([20.0, 20.0]),
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut doubled, "c1").unwrap();
+ let f = marks[0].as_fill().unwrap();
+ assert_eq!((f.coverage.x, f.coverage.y), (20, 20));
+ assert_eq!((f.coverage.width, f.coverage.height), (40, 20));
+ assert!(f.coverage.pixels() >= 780);
+ assert!(matches!(f.source, FillSource::Seed { seed, .. } if seed.x == 30.0));
+ }
+
+ #[test]
+ fn clicks_pick_the_topmost_mark_and_lassos_take_whole_marks() {
+ let mut marks = vec![square(1), line(2)];
+ assert_eq!(hit(&marks, (20.0, 13.0), 0.0), Some(2));
+ assert_eq!(hit(&marks, (25.0, 25.0), 0.0), Some(1));
+ assert_eq!(hit(&marks, (20.0, 17.0), 0.0), None);
+ assert_eq!(hit(&marks, (20.0, 17.0), 3.0), Some(2));
+ let around_line = [[5.0, 5.0], [35.0, 5.0], [35.0, 15.0], [5.0, 15.0]];
+ assert_eq!(lassoed(&marks, &around_line), vec![2]);
+ let around_all = [[0.0, 0.0], [50.0, 0.0], [50.0, 50.0], [0.0, 50.0]];
+ assert_eq!(lassoed(&marks, &around_all), vec![1, 2]);
+ marks.swap(0, 1);
+ assert_eq!(hit(&marks, (20.0, 25.0), 0.0), Some(1));
+ assert_eq!(bounds_of(&marks, &[2]), Some([5.0, 5.0, 35.0, 15.0]));
+ }
+
+ fn arm(id: u32) -> Mark {
+ Stroke::new(id, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1)
+ .with_points(&[(0.0, 30.0, 1.0), (30.0, 30.0, 1.0), (60.0, 30.0, 1.0)], 4.0)
+ .into()
+ }
+
+ #[test]
+ fn a_cut_lasso_splits_crossing_marks_and_moves_the_inside() {
+ let hand = [[20.0, 0.0], [70.0, 0.0], [70.0, 60.0], [20.0, 60.0]];
+ let marks = vec![arm(1), line(2), square(3)];
+ assert_eq!(
+ sides(&marks, &hand),
+ vec![(1, Side::Crossing), (2, Side::Crossing), (3, Side::Inside)]
+ );
+ let mut marks = vec![arm(1), square(2)];
+ let polygon = vec![[15.0, 15.0], [70.0, 15.0], [70.0, 45.0], [15.0, 45.0]];
+ assert_eq!(sides(&marks, &polygon), vec![(1, Side::Crossing), (2, Side::Inside)]);
+ let mut whole = MarkChange::Lasso {
+ polygon: polygon.clone(),
+ cut: false,
+ action: LassoAction::Transform(MarkTransform {
+ x: 100.0,
+ ..Default::default()
+ }),
+ chosen: Vec::new(),
+ };
+ let mut plain = marks.clone();
+ apply(&mut plain, &mut whole, "c1").unwrap();
+ assert_eq!(whole.ids(), vec![2]);
+ assert_eq!(plain[0], marks[0]);
+ let mut change = MarkChange::Lasso {
+ polygon: polygon.clone(),
+ cut: true,
+ action: LassoAction::Transform(MarkTransform {
+ x: 100.0,
+ ..Default::default()
+ }),
+ chosen: Vec::new(),
+ };
+ apply(&mut marks, &mut change, "c1").unwrap();
+ assert_eq!(marks.iter().map(Mark::id).collect::<Vec<_>>(), [1, 3, 2]);
+ assert_eq!(change.ids(), vec![2, 3]);
+ let (stay, part) = (marks[0].as_stroke().unwrap(), marks[1].as_stroke().unwrap());
+ assert_eq!(stay.samples, arm(1).as_stroke().unwrap().samples);
+ assert_eq!(stay.cuts[0].keep, Keep::Outside);
+ assert_eq!(part.cuts[0].keep, Keep::Inside);
+ assert_eq!(part.samples[0].pos(), (100.0, 30.0));
+ assert_eq!(part.cuts[0].polygon[0], [115.0, 15.0]);
+ assert!(!cut::keeps(&stay.cuts, (30.0, 30.0)) && cut::keeps(&part.cuts, (130.0, 30.0)));
+ assert_eq!(hit(&marks, (30.0, 30.0), 0.0), None);
+ assert_eq!(hit(&marks, (5.0, 30.0), 0.0), Some(1));
+ assert_eq!(hit(&marks, (130.0, 30.0), 0.0), Some(3));
+ let mut gone = vec![arm(1), square(2)];
+ let mut rm = MarkChange::Lasso {
+ polygon,
+ cut: true,
+ action: LassoAction::Remove,
+ chosen: Vec::new(),
+ };
+ apply(&mut gone, &mut rm, "c1").unwrap();
+ assert_eq!(gone.len(), 1);
+ assert_eq!(gone[0].cuts()[0].keep, Keep::Outside);
+ let mut empty = MarkChange::Lasso {
+ polygon: vec![[500.0, 500.0], [510.0, 500.0], [510.0, 510.0]],
+ cut: true,
+ action: LassoAction::Remove,
+ chosen: Vec::new(),
+ };
+ assert!(apply(&mut gone, &mut empty, "c1").is_err());
+ }
+
+ #[test]
+ fn flips_mirror_strokes_and_cuts() {
+ let mut marks = vec![arm(1)];
+ marks[0].cuts_mut().push(Cut {
+ keep: Keep::Inside,
+ polygon: vec![[0.0, 0.0], [10.0, 0.0], [10.0, 40.0], [0.0, 40.0]],
+ });
+ let mut flip = MarkChange::Transform {
+ ids: vec![1],
+ transform: MarkTransform {
+ sx: -1.0,
+ pivot: Some([30.0, 30.0]),
+ ..Default::default()
+ },
+ };
+ apply(&mut marks, &mut flip, "c1").unwrap();
+ let s = marks[0].as_stroke().unwrap();
+ assert_eq!(s.samples[0].pos(), (60.0, 30.0));
+ assert_eq!(s.size, 4.0);
+ assert_eq!(s.cuts[0].polygon[1], [50.0, 0.0]);
+ }
+
+ #[test]
+ fn adds_take_the_next_ids() {
+ let mut marks = vec![line(4)];
+ let mut add = MarkChange::Add(vec![line(0), square(0)]);
+ apply(&mut marks, &mut add, "c1").unwrap();
+ assert_eq!(marks.iter().map(Mark::id).collect::<Vec<_>>(), [4, 5, 6]);
+ assert_eq!(add.ids(), [5, 6]);
+ }
+
+ #[test]
+ fn a_reshaped_stroke_keeps_its_pressure_along_the_new_path() {
+ let points: Vec<(f32, f32, f32)> = (0..=20)
+ .map(|i| (i as f32 * 5.0, 10.0, 0.2 + i as f32 * 0.04))
+ .collect();
+ let stroke = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 8.0, 3).with_points(&points, 5.0);
+ let mut bent = stroke.clone();
+ reshape(&mut bent, "M10 0 L10 200").unwrap();
+ assert_eq!(bent.samples.len(), stroke.samples.len());
+ bent.samples
+ .iter()
+ .zip(&stroke.samples)
+ .enumerate()
+ .for_each(|(i, (b, s))| {
+ let (x, y) = b.pos();
+ assert!(
+ (x - 10.0).abs() < 0.1 && (y - i as f32 * 10.0).abs() < 0.1,
+ "{i}: {x},{y}"
+ );
+ assert_eq!((b.pressure, b.tilt_x, b.dt_ms), (s.pressure, s.tilt_x, s.dt_ms));
+ });
+ let mut same = stroke.clone();
+ reshape(&mut same, "M0 10 L100 10").unwrap();
+ assert_eq!(same, stroke);
+ let mut marks = vec![Mark::Stroke(stroke)];
+ let mut change = MarkChange::Set {
+ id: 1,
+ props: serde_json::from_str(r#"{"path":"M0 0 C 30 -40 70 40 100 0"}"#).unwrap(),
+ };
+ apply(&mut marks, &mut change, "c1").unwrap();
+ let Mark::Stroke(curved) = &marks[0] else { panic!() };
+ assert!(curved.samples[5].pos().1 < -5.0, "{:?}", curved.samples[5].pos());
+ assert!(reshape(&mut curved.clone(), "").is_err());
+ }
+}
diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rs
new file mode 100644
index 0000000..eaec77b
--- /dev/null
+++ b/crates/core/src/migrate.rs
@@ -0,0 +1,287 @@
+use crate::doc::FORMAT;
+use anyhow::{Result, bail};
+use serde_json::{Map, Value, json};
+use std::collections::BTreeSet;
+use std::path::PathBuf;
+
+const V0: &str = "draw-anything/0";
+const V1: &str = "draw-anything/1";
+const V2: &str = "draw-anything/2";
+const V3: &str = "draw-anything/3";
+const V4: &str = "draw-anything/4";
+const V5: &str = "draw-anything/5";
+const V6: &str = "draw-anything/6";
+const V7: &str = "draw-anything/7";
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FileMove {
+ pub from: PathBuf,
+ pub to: PathBuf,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Migrated {
+ pub value: Value,
+ pub moves: Vec<FileMove>,
+ pub embed_m1_brushes: bool,
+}
+
+impl Migrated {
+ pub fn changed(&self) -> bool {
+ !self.moves.is_empty() || self.embed_m1_brushes
+ }
+}
+
+pub fn migrate(value: Value) -> Result<Migrated> {
+ let format = value
+ .get("format")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ match format.as_str() {
+ FORMAT => Ok(Migrated {
+ value,
+ moves: Vec::new(),
+ embed_m1_brushes: false,
+ }),
+ V2 | V3 | V4 | V5 | V6 | V7 => Ok(Migrated {
+ value: to_current(value),
+ moves: Vec::new(),
+ embed_m1_brushes: false,
+ }),
+ V1 => Ok(Migrated {
+ value: to_current(value),
+ moves: Vec::new(),
+ embed_m1_brushes: true,
+ }),
+ V0 => {
+ let (v1, moves) = from_v0(&value);
+ Ok(Migrated {
+ value: to_current(v1),
+ moves,
+ embed_m1_brushes: true,
+ })
+ }
+ other => bail!("unknown document format {other:?}"),
+ }
+}
+
+fn to_current(mut value: Value) -> Value {
+ value["format"] = Value::String(FORMAT.to_string());
+ value
+}
+
+struct Ids {
+ taken: BTreeSet<String>,
+ next: u64,
+}
+
+impl Ids {
+ fn alloc(&mut self, prefix: char) -> String {
+ loop {
+ self.next += 1;
+ let id = format!("{prefix}{}", self.next);
+ if self.taken.insert(id.clone()) {
+ return id;
+ }
+ }
+ }
+}
+
+fn strokes(layer: &str, cel: &str) -> PathBuf {
+ PathBuf::from("strokes").join(layer).join(format!("{cel}.strokes"))
+}
+
+fn from_v0(v0: &Value) -> (Value, Vec<FileMove>) {
+ let layers = v0["layers"].as_array().cloned().unwrap_or_default();
+ let mut ids = Ids {
+ taken: layers
+ .iter()
+ .filter_map(|l| l["id"].as_str().map(String::from))
+ .collect(),
+ next: 0,
+ };
+ let mut moves = Vec::new();
+ let mut converted = Vec::new();
+ for layer in &layers {
+ let id = layer["id"].as_str().unwrap_or_default().to_string();
+ let kind = layer["kind"].as_str().unwrap_or("paint");
+ let cel_id = ids.alloc('c');
+ let mut cel = json!({ "id": cel_id, "frame": 0 });
+ if kind == "vector" {
+ let nodes: Vec<Value> = layer["shapes"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|mut shape| {
+ shape["id"] = Value::String(ids.alloc('n'));
+ shape
+ })
+ .collect();
+ cel["nodes"] = Value::Array(nodes);
+ } else {
+ moves.push(FileMove {
+ from: strokes(&id, "c0"),
+ to: strokes(&id, &cel_id),
+ });
+ }
+ let mut out = Map::new();
+ out.insert("id".into(), Value::String(id));
+ out.insert("name".into(), layer["name"].clone());
+ out.insert("kind".into(), Value::String(kind.to_string()));
+ out.insert("cels".into(), json!([cel]));
+ ["opacity", "blend", "visible"]
+ .iter()
+ .filter(|k| layer.get(**k).is_some())
+ .for_each(|k| {
+ out.insert((*k).to_string(), layer[*k].clone());
+ });
+ converted.push(Value::Object(out));
+ }
+ let doc = json!({
+ "format": V1,
+ "rev": v0["rev"].as_u64().unwrap_or(0),
+ "canvas": v0["canvas"].clone(),
+ "timeline": { "fps": 12, "frames": 1 },
+ "layers": converted,
+ "nextId": ids.next,
+ });
+ (doc, moves)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::{Document, Kind, Shape};
+
+ #[test]
+ fn v0_documents_become_v1_with_cels_and_node_ids() {
+ let v0 = json!({
+ "format": "draw-anything/0", "rev": 4,
+ "canvas": { "width": 64, "height": 32, "background": "#ffffff" },
+ "layers": [
+ { "id": "sky", "name": "sky", "kind": "vector",
+ "shapes": [{ "type": "rect", "x": 0, "y": 0, "w": 64, "h": 32, "fill": "#336699" }] },
+ { "id": "c1", "name": "ink", "kind": "paint", "blend": "multiply", "opacity": 0.5 }
+ ]
+ });
+ let out = migrate(v0).unwrap();
+ assert!(out.embed_m1_brushes);
+ let moves = out.moves;
+ let doc: Document = serde_json::from_value(out.value).unwrap();
+ doc.validate().unwrap();
+ assert_eq!(doc.rev, 4);
+ assert_eq!(doc.layers[0].kind(), Kind::Vector);
+ let node = &doc.layers[0].cels()[0].nodes[0];
+ assert!(matches!(node.shape, Shape::Rect { w, .. } if w == 64.0));
+ assert!(node.id.starts_with('n'));
+ let ink = &doc.layers[1];
+ assert_eq!(ink.opacity, 0.5);
+ assert_ne!(ink.cels()[0].id, "c1");
+ assert_eq!(moves.len(), 1);
+ assert_eq!(moves[0].from, PathBuf::from("strokes/c1/c0.strokes"));
+ assert_eq!(
+ moves[0].to,
+ PathBuf::from(format!("strokes/c1/{}.strokes", ink.cels()[0].id))
+ );
+ }
+
+ #[test]
+ fn current_documents_pass_through_and_unknown_formats_fail() {
+ let current = json!({ "format": FORMAT, "rev": 1 });
+ let same = migrate(current.clone()).unwrap();
+ assert_eq!(same.value, current);
+ assert!(!same.changed());
+ assert!(migrate(json!({ "format": "other/9" })).is_err());
+ }
+
+ #[test]
+ fn v6_documents_only_change_format_and_have_no_parts() {
+ let v6 = json!({ "format": "draw-anything/6", "rev": 2, "canvas": { "width": 8, "height": 8 },
+ "timeline": { "fps": 12, "frames": 2 },
+ "layers": [{ "id": "l1", "name": "lines", "kind": "paint", "cels": [{ "id": "c1", "frame": 0 }] }] });
+ let out = migrate(v6).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert!(!out.changed());
+ let doc: crate::doc::Document = serde_json::from_value(out.value).unwrap();
+ assert!(doc.layers[0].cels()[0].parts.is_empty());
+ }
+
+ #[test]
+ fn v5_documents_only_change_format_and_read_tweens_after() {
+ let v5 = json!({ "format": "draw-anything/5", "rev": 4, "canvas": { "width": 8, "height": 8 },
+ "timeline": { "fps": 12, "frames": 4, "origin": [4, 6] },
+ "layers": [{ "id": "l1", "name": "lines", "kind": "paint",
+ "cels": [{ "id": "c1", "frame": 0, "hold": 1 }, { "id": "c2", "frame": 2 }] }] });
+ let out = migrate(v5).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert!(!out.changed());
+ let mut doc: crate::doc::Document = serde_json::from_value(out.value).unwrap();
+ doc.validate().unwrap();
+ assert!(doc.layers[0].cels().iter().all(|c| c.tween.is_none()));
+ let cels = doc.layers[0].cels_mut().unwrap();
+ cels.insert(
+ 1,
+ crate::doc::Cel {
+ tween: Some(crate::doc::Tween {
+ from: "c1".into(),
+ to: "c2".into(),
+ t: 0.5,
+ matching: String::new(),
+ pairs: Vec::new(),
+ made: "ab12".into(),
+ unpaired: String::new(),
+ }),
+ hold: Some(1),
+ ..crate::doc::Cel::at("c3", 1)
+ },
+ );
+ doc.validate().unwrap();
+ let text = serde_json::to_string(&doc.layers[0].cels()[1]).unwrap();
+ assert_eq!(
+ text,
+ r#"{"id":"c3","frame":1,"hold":1,"tween":{"from":"c1","to":"c2","t":0.5,"made":"ab12"}}"#
+ );
+ }
+
+ #[test]
+ fn v4_documents_only_change_format() {
+ let v4 = json!({ "format": "draw-anything/4", "rev": 9, "canvas": { "width": 8, "height": 8 },
+ "timeline": { "fps": 12, "frames": 4, "clips": [{ "name": "run", "from": 0, "to": 3, "loop": true }] },
+ "layers": [] });
+ let out = migrate(v4).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert!(!out.changed());
+ let doc: crate::doc::Document = serde_json::from_value(out.value).unwrap();
+ doc.validate().unwrap();
+ assert_eq!(doc.timeline.clips[0].fps, None);
+ assert_eq!(doc.timeline.fps_of(&doc.timeline.clips[0]), 12);
+ }
+
+ #[test]
+ fn v3_documents_only_change_format() {
+ let v3 = json!({ "format": "draw-anything/3", "rev": 5, "canvas": { "width": 8, "height": 8 }, "layers": [] });
+ let out = migrate(v3).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert!(!out.changed());
+ }
+
+ #[test]
+ fn v2_documents_only_change_format() {
+ let v2 = json!({ "format": "draw-anything/2", "rev": 3, "canvas": { "width": 8, "height": 8 }, "layers": [] });
+ let out = migrate(v2).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert!(out.moves.is_empty() && !out.embed_m1_brushes);
+ assert_eq!(out.value["rev"], 3);
+ }
+
+ #[test]
+ fn v1_documents_only_change_format_and_ask_for_m1_brushes() {
+ let v1 = json!({ "format": "draw-anything/1", "rev": 7, "canvas": { "width": 8, "height": 8 }, "layers": [] });
+ let out = migrate(v1).unwrap();
+ assert_eq!(out.value["format"], FORMAT);
+ assert_eq!(out.value["rev"], 7);
+ assert!(out.moves.is_empty() && out.embed_m1_brushes && out.changed());
+ }
+}
diff --git a/crates/core/src/notes.rs b/crates/core/src/notes.rs
new file mode 100644
index 0000000..035ed9a
--- /dev/null
+++ b/crates/core/src/notes.rs
@@ -0,0 +1,133 @@
+use crate::bundle::{Bundle, now_ms, write_atomic};
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::PathBuf;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Note {
+ pub id: u32,
+ pub x: f32,
+ pub y: f32,
+ #[serde(default)]
+ pub frame: u32,
+ pub text: String,
+ pub author: String,
+ pub at_ms: u64,
+ #[serde(default)]
+ pub done: bool,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Selection {
+ pub layer: Option<String>,
+ pub nodes: Vec<String>,
+ pub frame: u32,
+ pub at_ms: u64,
+}
+
+fn notes_path(bundle: &Bundle) -> PathBuf {
+ bundle.cache_dir().join("notes.json")
+}
+
+fn selection_path(bundle: &Bundle) -> PathBuf {
+ bundle.cache_dir().join("selection.json")
+}
+
+pub fn read(bundle: &Bundle) -> Vec<Note> {
+ fs::read_to_string(notes_path(bundle))
+ .ok()
+ .and_then(|t| serde_json::from_str(&t).ok())
+ .unwrap_or_default()
+}
+
+fn write(bundle: &Bundle, notes: &[Note]) -> Result<()> {
+ write_atomic(&notes_path(bundle), serde_json::to_string_pretty(notes)?.as_bytes())
+}
+
+pub fn add(bundle: &Bundle, (x, y): (f32, f32), frame: u32, text: &str, author: &str) -> Result<Note> {
+ let mut notes = read(bundle);
+ let note = Note {
+ id: notes.iter().map(|n| n.id).max().map_or(1, |m| m + 1),
+ x,
+ y,
+ frame,
+ text: text.trim().to_string(),
+ author: author.to_string(),
+ at_ms: now_ms(),
+ done: false,
+ };
+ notes.push(note.clone());
+ write(bundle, &notes)?;
+ Ok(note)
+}
+
+pub fn set_done(bundle: &Bundle, id: u32, done: bool) -> Result<bool> {
+ let mut notes = read(bundle);
+ let found = notes.iter_mut().find(|n| n.id == id).map(|n| n.done = done).is_some();
+ if found {
+ write(bundle, &notes)?;
+ }
+ Ok(found)
+}
+
+pub fn set_text(bundle: &Bundle, id: u32, text: &str) -> Result<bool> {
+ let mut notes = read(bundle);
+ let found = notes
+ .iter_mut()
+ .find(|n| n.id == id)
+ .map(|n| n.text = text.trim().to_string())
+ .is_some();
+ if found {
+ write(bundle, &notes)?;
+ }
+ Ok(found)
+}
+
+pub fn remove(bundle: &Bundle, id: u32) -> Result<()> {
+ let notes: Vec<Note> = read(bundle).into_iter().filter(|n| n.id != id).collect();
+ write(bundle, &notes)
+}
+
+pub fn read_selection(bundle: &Bundle) -> Option<Selection> {
+ serde_json::from_str(&fs::read_to_string(selection_path(bundle)).ok()?).ok()
+}
+
+pub fn write_selection(bundle: &Bundle, layer: Option<String>, nodes: Vec<String>, frame: u32) -> Result<()> {
+ let selection = Selection {
+ layer,
+ nodes,
+ frame,
+ at_ms: now_ms(),
+ };
+ write_atomic(
+ &selection_path(bundle),
+ serde_json::to_string_pretty(&selection)?.as_bytes(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::Document;
+
+ #[test]
+ fn notes_and_selection_round_trip() {
+ let dir = std::env::temp_dir().join(format!("draw-notes-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ let bundle = Bundle::create(&dir, Document::new(32, 32)).unwrap();
+ assert!(read(&bundle).is_empty());
+ let a = add(&bundle, (4.0, 5.0), 0, " too dark ", "user").unwrap();
+ let b = add(&bundle, (9.0, 9.0), 0, "move this left", "user").unwrap();
+ assert_eq!((a.id, b.id, a.text.as_str()), (1, 2, "too dark"));
+ assert!(set_done(&bundle, 1, true).unwrap());
+ assert!(!set_done(&bundle, 7, true).unwrap());
+ remove(&bundle, 2).unwrap();
+ assert_eq!(read(&bundle), vec![Note { done: true, ..a }]);
+ write_selection(&bundle, Some("l1".into()), vec!["n3".into()], 0).unwrap();
+ assert_eq!(read_selection(&bundle).unwrap().nodes, vec!["n3"]);
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
new file mode 100644
index 0000000..a415d23
--- /dev/null
+++ b/crates/core/src/ops.rs
@@ -0,0 +1,3029 @@
+use crate::color::parse_hex;
+use crate::doc::{Cel, Clip, Document, Item, Kind, Layer, LayerContent, Loc, MASK, Node, Shape, Swatch, Tween};
+use crate::fill::{self, Coverage, Fill, FillRef, FillSource, Seed};
+use crate::markedit::{LassoAction, MarkChange, MarkTransform, Source, parse_address};
+use crate::path::{flatten, length, profile, resample};
+use crate::pathedit::{self, PathEdit};
+use crate::retime::{self, Retime, RetimeSpec};
+use crate::rng::{FNV_OFFSET, fnv};
+use crate::stroke::{Author, Mark, Sample, Stroke};
+use crate::timing::{self, CelAction, CelSpec, FrameSpec};
+use crate::tween::{Match, Spacing, Unpaired};
+use anyhow::{Context, Result, anyhow, bail};
+use serde::Deserialize;
+use serde_json::{Map, Value, json};
+use std::collections::{BTreeMap, BTreeSet};
+
+const LAYER_KEYS: &[&str] = &[
+ "id",
+ "name",
+ "kind",
+ "opacity",
+ "blend",
+ "visible",
+ "locked",
+ "clip",
+ "lockAlpha",
+ "mask",
+ "cels",
+ "children",
+ "effects",
+ "adjust",
+ "depth",
+ "reference",
+];
+const CEL_KEYS: &[&str] = &["id", "frame", "hold", "link", "tween", "nodes"];
+const NODE_KEYS: &[&str] = &[
+ "id",
+ "name",
+ "type",
+ "fill",
+ "stroke",
+ "transform",
+ "opacity",
+ "blur",
+ "clip",
+ "visible",
+];
+const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];
+const STROKE_KEYS: &[&str] = &["paint", "width", "cap", "join", "dash"];
+const STRUCTURE: &[&str] = &["id", "kind", "type", "cels", "children", "nodes", "mask"];
+
+fn shape_keys(kind: &str) -> Result<&'static [&'static str]> {
+ Ok(match kind {
+ "rect" => &["x", "y", "w", "h", "radius"],
+ "ellipse" => &["cx", "cy", "rx", "ry"],
+ "path" => &["d"],
+ "group" => &["children"],
+ "rays" => &[
+ "x", "y", "angle", "spread", "count", "length", "start", "falloff", "noise", "seed",
+ ],
+ "image" => &["src", "x", "y", "w", "h"],
+ "scatter" => &["x", "y", "w", "h", "count", "seed", "size", "turn", "avoid", "children"],
+ "repeat" => &["count", "step", "turn", "pivot", "scale", "columns", "row", "children"],
+ "mirror" => &["x", "y", "angle", "children"],
+ "text" => &["text", "font", "x", "y", "size", "tracking", "leading", "align"],
+ other => bail!(
+ "unknown node type {other:?}: use rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text"
+ ),
+ })
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Place {
+ pub above: Option<String>,
+ pub below: Option<String>,
+ pub into: Option<String>,
+ pub index: Option<usize>,
+ pub frame: Option<u32>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Op {
+ AddLayer {
+ layer: Value,
+ place: Place,
+ },
+ AddNode {
+ node: Value,
+ place: Place,
+ },
+ AddCel {
+ cel: Value,
+ layer: String,
+ },
+ AddMask {
+ mask: Value,
+ layer: String,
+ hide: bool,
+ },
+ Set {
+ id: String,
+ props: Map<String, Value>,
+ },
+ Remove {
+ ids: Vec<String>,
+ },
+ Move {
+ id: String,
+ place: Place,
+ },
+ Stroke(StrokeSpec),
+ Fill(FillSpec),
+ Palette(PaletteEdit),
+ Transform {
+ ids: Vec<String>,
+ transform: MarkTransform,
+ },
+ Path {
+ id: String,
+ edit: PathEdit,
+ },
+ Lasso(LassoSpec),
+ Copy(CopySpec),
+ Timeline {
+ fps: Option<u32>,
+ frames: Option<u32>,
+ origin: Option<Option<[f32; 2]>>,
+ },
+ Atmosphere(Option<crate::look::Atmosphere>),
+ Frames(FrameSpec),
+ Cel(CelSpec),
+ Retime(RetimeSpec),
+ Inbetween(InbetweenSpec),
+ Ink(InkSpec),
+ Duplicate {
+ layer: String,
+ },
+ Part {
+ ids: Vec<String>,
+ name: String,
+ },
+ Light(LightSpec),
+ Hatch(HatchSpec),
+ Paint(PaintSpec),
+ Scatter(ScatterSpec),
+ Clip(ClipEdit),
+ Export {
+ godot: Option<String>,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum ClipEdit {
+ Add(Clip),
+ Set {
+ name: String,
+ rename: Option<String>,
+ from: Option<u32>,
+ to: Option<u32>,
+ looping: Option<bool>,
+ fps: Option<Option<u32>>,
+ },
+ Remove {
+ name: String,
+ },
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct InbetweenSpec {
+ pub layers: Vec<String>,
+ pub from: Option<u32>,
+ pub to: Option<u32>,
+ pub count: Option<u32>,
+ pub spacing: Spacing,
+ pub matching: Match,
+ pub pairs: Vec<[u32; 2]>,
+ pub redo: bool,
+ pub force: bool,
+ pub looping: bool,
+ pub keep_drawn: bool,
+ pub unpaired: Unpaired,
+ pub only: Vec<String>,
+ pub keep_cels: Vec<String>,
+ pub force_cels: Vec<String>,
+ pub resolved: Option<Inbetweens>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Inbetweens {
+ pub cels: Vec<TweenCel>,
+ pub holds: Vec<(String, u32)>,
+ pub removed: Vec<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct TweenCel {
+ pub layer: String,
+ pub cel: String,
+ pub frame: u32,
+ pub hold: Option<u32>,
+ pub tween: Tween,
+ pub marks: Vec<Mark>,
+ pub fresh: bool,
+ pub parts: BTreeMap<String, Vec<u32>>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum CopyTarget {
+ Cel(String),
+ Frame { frame: u32, layer: Option<String> },
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct CopySpec {
+ pub ids: Vec<String>,
+ pub to: CopyTarget,
+ pub transform: Option<MarkTransform>,
+ pub cut: Option<Vec<[f32; 2]>>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct LassoSpec {
+ pub layer: String,
+ pub frame: u32,
+ pub polygon: Vec<[f32; 2]>,
+ pub cut: bool,
+ pub action: LassoAction,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum PaletteEdit {
+ Add {
+ color: String,
+ name: String,
+ index: Option<usize>,
+ },
+ Remove {
+ key: String,
+ },
+ Set {
+ swatches: Vec<Swatch>,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct FillSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default)]
+ pub at: Option<[f32; 2]>,
+ #[serde(default)]
+ pub polygon: Option<Vec<[f32; 2]>>,
+ #[serde(default, rename = "ref")]
+ pub reference: Option<String>,
+ #[serde(default = "default_tolerance")]
+ pub tolerance: f32,
+ #[serde(default)]
+ pub gap: f32,
+ #[serde(default = "default_expand")]
+ pub expand: f32,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default)]
+ pub like: Option<String>,
+ #[serde(default)]
+ pub frames: Option<String>,
+ #[serde(default)]
+ pub shape: Option<String>,
+ #[serde(default)]
+ pub outside: Option<Vec<[f32; 2]>>,
+ #[serde(default)]
+ pub part: Option<String>,
+ #[serde(skip)]
+ pub coverage: Option<Coverage>,
+ #[serde(skip)]
+ pub carried: Option<Vec<(String, Vec<Mark>)>>,
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct StrokeSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default = "default_brush")]
+ pub brush: String,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "default_size")]
+ pub size: f32,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default = "full")]
+ pub flow: f32,
+ #[serde(default)]
+ pub path: Option<String>,
+ #[serde(default)]
+ pub points: Option<Vec<[f32; 3]>>,
+ #[serde(default)]
+ pub pressure: Vec<f32>,
+ #[serde(default)]
+ pub tilt: [f32; 2],
+ #[serde(default = "default_speed")]
+ pub speed: f32,
+ #[serde(default)]
+ pub seed: Option<u32>,
+ #[serde(default)]
+ pub taper: Option<[f32; 2]>,
+ #[serde(default)]
+ pub part: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub second: Option<String>,
+}
+
+fn default_brush() -> String {
+ "ink".into()
+}
+
+fn default_color() -> String {
+ "#000000".into()
+}
+
+fn default_size() -> f32 {
+ 8.0
+}
+
+fn default_speed() -> f32 {
+ 700.0
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct InkSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub from: Vec<String>,
+ #[serde(default)]
+ pub path: Option<String>,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default = "ink_weight")]
+ pub weight: f32,
+ #[serde(default = "default_light")]
+ pub light: [f32; 2],
+ #[serde(default = "ink_break", rename = "break")]
+ pub break_deg: f32,
+ #[serde(default)]
+ pub gap: f32,
+ #[serde(default = "ink_wobble")]
+ pub wobble: f32,
+ #[serde(default)]
+ pub taper: Option<[f32; 2]>,
+ #[serde(default = "default_brush")]
+ pub brush: String,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default = "full")]
+ pub hand: f32,
+ #[serde(default = "first_seed")]
+ pub seed: u32,
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct LightSpec {
+ pub from: Vec<String>,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default = "default_light")]
+ pub light: [f32; 2],
+ #[serde(default)]
+ pub lamp: Option<[f32; 3]>,
+ #[serde(default)]
+ pub shade: Option<String>,
+ #[serde(default)]
+ pub rim: Option<String>,
+ #[serde(default = "light_depth")]
+ pub depth: f32,
+ #[serde(default = "light_soft")]
+ pub soft: u32,
+ #[serde(default = "rim_width")]
+ pub rim_width: f32,
+ #[serde(default = "shade_color")]
+ pub shade_color: String,
+ #[serde(default = "rim_color")]
+ pub rim_color: String,
+ #[serde(default = "shade_opacity")]
+ pub shade_opacity: f32,
+ #[serde(default = "rim_opacity")]
+ pub rim_opacity: f32,
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct HatchSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default, rename = "in")]
+ pub within: Vec<String>,
+ #[serde(default)]
+ pub polygon: Option<Vec<[f32; 2]>>,
+ #[serde(default = "hatch_angle")]
+ pub angle: f32,
+ #[serde(default)]
+ pub along: bool,
+ #[serde(default = "hatch_spacing")]
+ pub spacing: f32,
+ #[serde(default = "hatch_length")]
+ pub length: [f32; 2],
+ #[serde(default = "hatch_jitter")]
+ pub jitter: f32,
+ #[serde(default = "texture_weight")]
+ pub weight: f32,
+ #[serde(default = "default_brush")]
+ pub brush: String,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default = "full")]
+ pub hand: f32,
+ #[serde(default = "first_seed")]
+ pub seed: u32,
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct PaintSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default, rename = "in")]
+ pub within: Vec<String>,
+ #[serde(default)]
+ pub polygon: Option<Vec<[f32; 2]>>,
+ #[serde(default = "paint_brush")]
+ pub brush: String,
+ #[serde(default = "paint_bold")]
+ pub bold: String,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "paint_form")]
+ pub form: String,
+ #[serde(default = "paint_axis")]
+ pub axis: f32,
+ #[serde(default = "paint_facing")]
+ pub facing: [f32; 3],
+ #[serde(default = "default_light")]
+ pub light: [f32; 2],
+ #[serde(default = "paint_elevation")]
+ pub elevation: f32,
+ #[serde(default)]
+ pub lamp: Option<[f32; 3]>,
+ #[serde(default = "paint_key")]
+ pub key: String,
+ #[serde(default = "paint_fill")]
+ pub fill: String,
+ #[serde(default = "paint_fill_strength")]
+ pub fill_strength: f32,
+ #[serde(default = "paint_bounce")]
+ pub bounce: String,
+ #[serde(default = "paint_bounce_strength")]
+ pub bounce_strength: f32,
+ #[serde(default = "paint_core")]
+ pub core: f32,
+ #[serde(default = "hatch_angle")]
+ pub angle: f32,
+ #[serde(default = "paint_weight")]
+ pub weight: f32,
+ #[serde(default = "full")]
+ pub decisive: f32,
+ #[serde(default = "paint_vary")]
+ pub vary: f32,
+ #[serde(default = "full")]
+ pub hand: f32,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default = "first_seed")]
+ pub seed: u32,
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ScatterSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default, rename = "in")]
+ pub within: Vec<String>,
+ #[serde(default)]
+ pub polygon: Option<Vec<[f32; 2]>>,
+ #[serde(default)]
+ pub avoid: Vec<String>,
+ #[serde(default = "scatter_mark")]
+ pub mark: String,
+ #[serde(default)]
+ pub count: Option<usize>,
+ #[serde(default = "scatter_spacing")]
+ pub spacing: f32,
+ #[serde(default = "scatter_size")]
+ pub size: [f32; 2],
+ #[serde(default = "scatter_turn")]
+ pub turn: [f32; 2],
+ #[serde(default = "texture_weight")]
+ pub weight: f32,
+ #[serde(default = "default_brush")]
+ pub brush: String,
+ #[serde(default = "default_color")]
+ pub color: String,
+ #[serde(default = "full")]
+ pub opacity: f32,
+ #[serde(default = "full")]
+ pub hand: f32,
+ #[serde(default = "first_seed")]
+ pub seed: u32,
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+fn ink_weight() -> f32 {
+ 6.0
+}
+
+fn default_light() -> [f32; 2] {
+ [-1.0, -1.0]
+}
+
+fn ink_break() -> f32 {
+ 60.0
+}
+
+fn ink_wobble() -> f32 {
+ 0.6
+}
+
+fn first_seed() -> u32 {
+ 1
+}
+
+fn light_depth() -> f32 {
+ 14.0
+}
+
+fn light_soft() -> u32 {
+ 3
+}
+
+fn rim_width() -> f32 {
+ 4.0
+}
+
+fn shade_color() -> String {
+ "#5a4a6a".into()
+}
+
+fn rim_color() -> String {
+ "#fff1cc".into()
+}
+
+fn shade_opacity() -> f32 {
+ 0.6
+}
+
+fn rim_opacity() -> f32 {
+ 0.85
+}
+
+fn hatch_angle() -> f32 {
+ 30.0
+}
+
+fn hatch_spacing() -> f32 {
+ 6.0
+}
+
+fn hatch_length() -> [f32; 2] {
+ [12.0, 30.0]
+}
+
+fn hatch_jitter() -> f32 {
+ 0.3
+}
+
+fn texture_weight() -> f32 {
+ 2.0
+}
+
+fn paint_brush() -> String {
+ "oil".into()
+}
+
+fn paint_bold() -> String {
+ "oil-load".into()
+}
+
+fn paint_form() -> String {
+ "round".into()
+}
+
+fn paint_axis() -> f32 {
+ 90.0
+}
+
+fn paint_facing() -> [f32; 3] {
+ [0.0, 0.0, 1.0]
+}
+
+fn paint_elevation() -> f32 {
+ 0.6
+}
+
+fn paint_key() -> String {
+ "#fff3e2".into()
+}
+
+fn paint_fill() -> String {
+ "#8a9ab8".into()
+}
+
+fn paint_fill_strength() -> f32 {
+ 0.16
+}
+
+fn paint_bounce() -> String {
+ "#b08a66".into()
+}
+
+fn paint_bounce_strength() -> f32 {
+ 0.1
+}
+
+fn paint_core() -> f32 {
+ 0.35
+}
+
+fn paint_weight() -> f32 {
+ 14.0
+}
+
+fn paint_vary() -> f32 {
+ 0.03
+}
+
+pub const PAINT_FORMS: [&str; 3] = ["round", "flat", "cylinder"];
+
+fn scatter_mark() -> String {
+ "M0 0 L0 -18".into()
+}
+
+fn scatter_spacing() -> f32 {
+ 14.0
+}
+
+fn scatter_size() -> [f32; 2] {
+ [0.7, 1.2]
+}
+
+fn scatter_turn() -> [f32; 2] {
+ [-15.0, 15.0]
+}
+
+fn full() -> f32 {
+ 1.0
+}
+
+fn default_tolerance() -> f32 {
+ fill::TOLERANCE
+}
+
+fn default_expand() -> f32 {
+ fill::EXPAND
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct PendingMarks {
+ pub layer: String,
+ pub cel: String,
+ pub changes: Vec<MarkChange>,
+ pub sealed: usize,
+}
+
+impl PendingMarks {
+ pub fn added(&self) -> impl Iterator<Item = &Mark> {
+ self.changes.iter().flat_map(|c| match c {
+ MarkChange::Add(marks) => &marks[..],
+ _ => &[],
+ })
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Applied {
+ pub added: Vec<String>,
+ pub changed: Vec<String>,
+ pub removed: Vec<String>,
+ pub dropped_cels: Vec<(String, String)>,
+ pub marks: Vec<PendingMarks>,
+ pub notes: Vec<String>,
+}
+
+impl Applied {
+ pub(crate) fn copy(&mut self, layer: &str, cel: &str, from_layer: &str, from_cel: &str) {
+ let upto = self
+ .marks
+ .iter_mut()
+ .find(|p| p.layer == from_layer && p.cel == from_cel)
+ .map_or(0, |p| {
+ p.sealed = p.changes.len();
+ p.sealed
+ });
+ self.push(
+ layer,
+ cel,
+ MarkChange::Copy {
+ layer: from_layer.to_string(),
+ cel: from_cel.to_string(),
+ upto,
+ },
+ );
+ }
+
+ pub(crate) fn paste(
+ &mut self,
+ layer: &str,
+ cel: &str,
+ sources: Vec<(String, String, Vec<u32>)>,
+ transform: Option<MarkTransform>,
+ cut: Option<Vec<[f32; 2]>>,
+ ) {
+ let sources = sources
+ .into_iter()
+ .map(|(from_layer, from_cel, ids)| {
+ let upto = self
+ .marks
+ .iter_mut()
+ .find(|p| p.layer == from_layer && p.cel == from_cel)
+ .map_or(0, |p| {
+ p.sealed = p.changes.len();
+ p.sealed
+ });
+ Source {
+ layer: from_layer,
+ cel: from_cel,
+ ids,
+ upto,
+ }
+ })
+ .collect();
+ self.push(
+ layer,
+ cel,
+ MarkChange::Paste {
+ sources,
+ transform,
+ cut,
+ made: Vec::new(),
+ },
+ );
+ }
+
+ fn push(&mut self, layer: &str, cel: &str, change: MarkChange) {
+ let at = match self.marks.iter().position(|p| p.layer == layer && p.cel == cel) {
+ Some(at) => at,
+ None => {
+ self.marks.push(PendingMarks {
+ layer: layer.to_string(),
+ cel: cel.to_string(),
+ changes: Vec::new(),
+ sealed: 0,
+ });
+ self.marks.len() - 1
+ }
+ };
+ let pending = &mut self.marks[at];
+ let open = pending.changes.len() > pending.sealed;
+ match (pending.changes.last_mut(), change) {
+ (Some(MarkChange::Add(last)), MarkChange::Add(more)) if open => last.extend(more),
+ (_, change) => pending.changes.push(change),
+ }
+ }
+}
+
+impl FillSpec {
+ pub fn seeded(layer: &str, at: [f32; 2]) -> Self {
+ Self {
+ layer: layer.to_string(),
+ frame: 0,
+ at: Some(at),
+ polygon: None,
+ reference: None,
+ tolerance: fill::TOLERANCE,
+ gap: 0.0,
+ expand: fill::EXPAND,
+ color: default_color(),
+ opacity: 1.0,
+ like: None,
+ frames: None,
+ shape: None,
+ outside: None,
+ part: None,
+ coverage: None,
+ carried: None,
+ }
+ }
+
+ pub fn check(&self) -> Result<()> {
+ match (&self.like, &self.at, &self.polygon) {
+ (Some(_), None, None) => return Ok(()),
+ (Some(_), _, _) => {
+ bail!("a fill like another drawing's carries that drawing's fills; leave out at and polygon")
+ }
+ (None, _, _) if self.frames.is_some() => bail!("frames goes with like: the drawing whose fills to carry"),
+ _ => {}
+ }
+ match (&self.at, &self.polygon, &self.shape) {
+ (Some(_), None, None) => {}
+ (None, Some(points), None) if points.len() >= 3 => {}
+ (None, None, Some(_)) => {}
+ (None, Some(_), None) => bail!("a polygon fill needs at least 3 points"),
+ _ => bail!(
+ "a fill needs one of \"at\": [x, y] (flood fill), \"polygon\": [[x, y], ...] (lasso fill) or \"shape\": <node id>"
+ ),
+ }
+ if self.outside.as_ref().is_some_and(|p| p.len() < 3) {
+ bail!("outside needs at least 3 points: the fill keeps what lies outside that polygon");
+ }
+ if !(0.0..=1.0).contains(&self.tolerance) || !(0.0..=1.0).contains(&self.opacity) {
+ bail!("fill tolerance and opacity must be within 0..1");
+ }
+ if !(0.0..=fill::MAX_GAP).contains(&self.gap) || !(0.0..=fill::MAX_EXPAND).contains(&self.expand) {
+ bail!(
+ "fill gap must be within 0..{} px and expand within 0..{} px",
+ fill::MAX_GAP,
+ fill::MAX_EXPAND
+ );
+ }
+ Ok(())
+ }
+
+ pub fn reference(&self, doc: &Document) -> Result<FillRef> {
+ let reference = match self.reference.as_deref().map(str::trim) {
+ None | Some("this") => FillRef::This,
+ Some("all") => FillRef::All,
+ Some(key) => FillRef::Layer(
+ doc.find_layer(key)
+ .map_err(|e| anyhow!("fill reference: {e}; or use this or all"))?
+ .id
+ .clone(),
+ ),
+ };
+ Ok(match reference {
+ FillRef::Layer(id) if id == self.layer => FillRef::This,
+ other => other,
+ })
+ }
+
+ pub fn source(&self, doc: &Document) -> Result<FillSource> {
+ self.check()?;
+ if let Some(shape) = &self.shape {
+ bail!("a fill from the shape {shape} is turned into polygons by klad fill --shape or klad apply first");
+ }
+ Ok(match (&self.at, &self.polygon) {
+ (Some([x, y]), _) => FillSource::Seed {
+ seed: Seed {
+ x: *x,
+ y: *y,
+ tolerance: self.tolerance,
+ gap: self.gap,
+ expand: self.expand,
+ },
+ reference: self.reference(doc)?,
+ },
+ (_, Some(points)) => FillSource::Polygon(points.clone()),
+ _ => unreachable!("checked above"),
+ })
+ }
+
+ pub fn build(&self, doc: &Document) -> Result<Fill> {
+ let source = self.source(doc)?;
+ let Some(coverage) = self.coverage.clone() else {
+ bail!("the fill's coverage has not been computed (klad fill and klad apply compute it)");
+ };
+ let color = parse_hex(&doc.resolve_color(&self.color)?)?;
+ let mut fill = Fill::new(0, color, source, coverage).by(Author::Agent);
+ fill.opacity = self.opacity;
+ if let Some(polygon) = &self.outside {
+ fill.cuts.push(crate::cut::Cut {
+ keep: crate::cut::Keep::Outside,
+ polygon: polygon.clone(),
+ });
+ }
+ Ok(fill)
+ }
+}
+
+impl StrokeSpec {
+ pub fn build(&self) -> Result<Vec<Stroke>> {
+ if self.size <= 0.0 || !(0.0..=1.0).contains(&self.opacity) || self.flow <= 0.0 {
+ bail!("stroke size and flow must be positive and opacity within 0..1");
+ }
+ if self.speed <= 0.0 {
+ bail!("stroke speed must be positive");
+ }
+ let taper = self.taper.unwrap_or_default();
+ if taper.iter().any(|t| !(0.0..=10_000.0).contains(t)) {
+ bail!("taper lengths must be within 0..10000 px");
+ }
+ let color = parse_hex(&self.color)?;
+ let second = self.second.as_deref().map(parse_hex).transpose()?;
+ let step = (self.speed / 200.0).clamp(1.0, 4.0);
+ let dt = step / self.speed * 1000.0;
+ let lines: Vec<Vec<[f32; 3]>> = match (&self.path, &self.points) {
+ (Some(d), None) => flatten(d)?
+ .into_iter()
+ .map(|line| {
+ let total = length(&line).max(1e-3);
+ let even = resample(&line, step);
+ let mut walked = 0.0;
+ even.iter()
+ .enumerate()
+ .map(|(i, p)| {
+ if i > 0 {
+ walked +=
+ libm::sqrtf((p[0] - even[i - 1][0]).powi(2) + (p[1] - even[i - 1][1]).powi(2));
+ }
+ [p[0], p[1], profile(&self.pressure, walked / total)]
+ })
+ .collect()
+ })
+ .collect(),
+ (None, Some(points)) => vec![points.clone()],
+ _ => bail!("a stroke needs either \"path\" (SVG path data) or \"points\" ([[x, y, pressure], ...])"),
+ };
+ let base = self.seed.unwrap_or_else(|| {
+ fnv(
+ FNV_OFFSET,
+ format!("{:?}{:?}{}", self.path, self.points, self.layer).as_bytes(),
+ ) as u32
+ });
+ Ok(lines
+ .into_iter()
+ .filter(|line| !line.is_empty())
+ .enumerate()
+ .map(|(i, line)| {
+ let mut stroke =
+ Stroke::new(0, &self.brush, color, self.size, base.wrapping_add(i as u32)).by(Author::Agent);
+ stroke.opacity = self.opacity;
+ stroke.flow = self.flow;
+ stroke.taper = taper;
+ stroke.second = second.map(crate::color::to_u16);
+ stroke.samples = line
+ .iter()
+ .enumerate()
+ .map(|(k, [x, y, p])| {
+ Sample::quantize(*x, *y, *p, (self.tilt[0], self.tilt[1]), if k == 0 { 0.0 } else { dt })
+ })
+ .collect();
+ stroke
+ })
+ .collect())
+ }
+}
+
+fn take_str(map: &mut Map<String, Value>, key: &str) -> Result<Option<String>> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(s)) => Ok(Some(s)),
+ Some(other) => bail!("{key} must be a string id, not {other}"),
+ }
+}
+
+fn take_place(map: &mut Map<String, Value>) -> Result<Place> {
+ let number = |map: &mut Map<String, Value>, key: &str| -> Result<Option<u64>> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v
+ .as_u64()
+ .map(Some)
+ .ok_or_else(|| anyhow!("{key} must be a whole number")),
+ }
+ };
+ Ok(Place {
+ above: take_str(map, "above")?,
+ below: take_str(map, "below")?,
+ into: take_str(map, "in")?,
+ index: number(map, "index")?.map(|v| v as usize),
+ frame: number(map, "frame")?.map(|v| v as u32),
+ })
+}
+
+fn no_leftovers(map: &Map<String, Value>, op: &str) -> Result<()> {
+ match map.keys().next() {
+ Some(key) => bail!("{op} does not take {key:?}"),
+ None => Ok(()),
+ }
+}
+
+impl Op {
+ pub fn parse(value: Value) -> Result<Self> {
+ let Value::Object(mut map) = value else {
+ bail!("an op must be a JSON object");
+ };
+ let op = take_str(&mut map, "op")?.ok_or_else(|| anyhow!("missing \"op\" (add, set, rm or mv)"))?;
+ let parsed = match op.as_str() {
+ "add" => {
+ if let Some(layer) = map.remove("layer") {
+ Op::AddLayer {
+ layer,
+ place: take_place(&mut map)?,
+ }
+ } else if let Some(node) = map.remove("node") {
+ Op::AddNode {
+ node,
+ place: take_place(&mut map)?,
+ }
+ } else if let Some(cel) = map.remove("cel") {
+ let layer = take_str(&mut map, "in")?.ok_or_else(|| anyhow!("add cel needs \"in\": a layer id"))?;
+ Op::AddCel { cel, layer }
+ } else if let Some(mask) = map.remove("mask") {
+ let layer = take_str(&mut map, "in")?
+ .ok_or_else(|| anyhow!("add mask needs \"in\": the layer it masks"))?;
+ let hide = match map.remove("hide") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(b)) => b,
+ Some(_) => bail!("hide must be true or false"),
+ };
+ Op::AddMask { mask, layer, hide }
+ } else {
+ bail!("add needs a \"layer\", \"node\", \"cel\" or \"mask\" object");
+ }
+ }
+ "set" => {
+ let id = take_str(&mut map, "id")?.ok_or_else(|| anyhow!("set needs an id"))?;
+ return Ok(Op::Set { id, props: map });
+ }
+ "rm" => {
+ let mut ids: Vec<String> = match map.remove("ids") {
+ Some(Value::Array(items)) => items
+ .into_iter()
+ .map(|v| {
+ v.as_str()
+ .map(String::from)
+ .ok_or_else(|| anyhow!("ids must be strings"))
+ })
+ .collect::<Result<_>>()?,
+ Some(_) => bail!("ids must be a list"),
+ None => Vec::new(),
+ };
+ ids.extend(take_str(&mut map, "id")?);
+ if ids.is_empty() {
+ bail!("rm needs an id or ids");
+ }
+ Op::Remove { ids }
+ }
+ "mv" => Op::Move {
+ id: take_str(&mut map, "id")?.ok_or_else(|| anyhow!("mv needs an id"))?,
+ place: take_place(&mut map)?,
+ },
+ "stroke" => {
+ let spec: StrokeSpec = serde_json::from_value(Value::Object(std::mem::take(&mut map)))?;
+ Op::Stroke(spec)
+ }
+ "fill" => {
+ let spec: FillSpec = serde_json::from_value(Value::Object(std::mem::take(&mut map)))?;
+ spec.check()?;
+ Op::Fill(spec)
+ }
+ "palette" => Op::Palette(parse_palette(&mut map)?),
+ "transform" => {
+ let mut ids: Vec<String> = match map.remove("ids") {
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("ids must be a list of strings"))?,
+ None => Vec::new(),
+ };
+ ids.extend(take_str(&mut map, "id")?);
+ if ids.is_empty() {
+ bail!("transform needs an id or ids (strokes and fills, <cel>:s<id>)");
+ }
+ Op::Transform {
+ ids,
+ transform: MarkTransform::parse(&mut map)?,
+ }
+ }
+ "path" => Op::Path {
+ id: take_str(&mut map, "id")?.ok_or_else(|| anyhow!("path needs the id of a path, rect or ellipse"))?,
+ edit: PathEdit::parse(&mut map)?,
+ },
+ "lasso" => Op::Lasso(parse_lasso(&mut map)?),
+ "copy" => Op::Copy(parse_copy(&mut map)?),
+ "atmosphere" => match map.remove("off") {
+ Some(Value::Bool(true)) => Op::Atmosphere(None),
+ Some(other) if other != Value::Bool(false) => bail!("atmosphere: off takes true or false"),
+ _ => Op::Atmosphere(Some(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?)),
+ },
+ "timeline" => Op::Timeline {
+ fps: whole(&mut map, "fps")?,
+ frames: whole(&mut map, "frames")?,
+ origin: match map.remove("origin") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(v) => Some(Some(
+ serde_json::from_value(v).map_err(|_| anyhow!("origin must be [x, y] or null"))?,
+ )),
+ },
+ },
+ "frames" => Op::Frames(parse_frames(&mut map)?),
+ "cel" => Op::Cel(parse_cel(&mut map)?),
+ "retime" => Op::Retime(parse_retime(&mut map)?),
+ "inbetween" => Op::Inbetween(parse_inbetween(&mut map)?),
+ "part" => {
+ let ids: Vec<String> = serde_json::from_value(
+ map.remove("ids")
+ .ok_or_else(|| anyhow!("part needs \"ids\": the marks, as c4:s12"))?,
+ )
+ .map_err(|_| anyhow!("part \"ids\" is a list of marks, as [\"c4:s12\"]"))?;
+ let name = take_str(&mut map, "name")?.ok_or_else(|| {
+ anyhow!("part needs \"name\": the part's name (\"\" takes the marks out of their part)")
+ })?;
+ Op::Part { ids, name }
+ }
+ "duplicate" => Op::Duplicate {
+ layer: take_str(&mut map, "layer")?
+ .ok_or_else(|| anyhow!("duplicate needs \"layer\": the layer to copy"))?,
+ },
+ "ink" => Op::Ink(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "light" => Op::Light(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "hatch" => Op::Hatch(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "paint" => Op::Paint(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "scatter" => Op::Scatter(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "clip" => Op::Clip(parse_clip(&mut map)?),
+ "export" => Op::Export {
+ godot: match map.remove("godot") {
+ Some(Value::Null) => None,
+ Some(Value::String(dir)) => Some(dir),
+ _ => bail!("export needs \"godot\": a folder relative to the bundle, or null"),
+ },
+ },
+ other => {
+ bail!(
+ "unknown op {other:?}: use add, set, rm, mv, stroke, fill, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter or export"
+ )
+ }
+ };
+ no_leftovers(&map, &op)?;
+ Ok(parsed)
+ }
+}
+
+fn whole(map: &mut Map<String, Value>, key: &str) -> Result<Option<u32>> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v
+ .as_u64()
+ .filter(|n| *n <= u32::MAX as u64 / 2)
+ .map(|n| Some(n as u32))
+ .ok_or_else(|| anyhow!("{key} must be a whole number")),
+ }
+}
+
+fn flag(map: &mut Map<String, Value>, key: &str) -> Result<bool> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(false),
+ Some(Value::Bool(b)) => Ok(b),
+ Some(_) => bail!("{key} must be true or false"),
+ }
+}
+
+fn parse_frames(map: &mut Map<String, Value>) -> Result<FrameSpec> {
+ let (insert, at) = match (whole(map, "insert")?, whole(map, "remove")?) {
+ (Some(at), None) => (true, at),
+ (None, Some(at)) => (false, at),
+ _ => bail!("frames needs \"insert\": <frame> or \"remove\": <frame>"),
+ };
+ let layers = match map.remove("layers") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(serde_json::from_value(v).map_err(|_| anyhow!("layers must be a list of layer ids"))?),
+ };
+ Ok(FrameSpec {
+ insert,
+ at,
+ count: whole(map, "count")?.unwrap_or(1),
+ layers,
+ })
+}
+
+fn parse_inbetween(map: &mut Map<String, Value>) -> Result<InbetweenSpec> {
+ let layers: Vec<String> = match map.remove("layers") {
+ None | Some(Value::Null) => Vec::new(),
+ Some(Value::String(one)) => vec![one],
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("layers must be a list of layer ids"))?,
+ };
+ let text = |map: &mut Map<String, Value>, key: &str| -> Result<String> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(String::new()),
+ Some(Value::String(s)) => Ok(s),
+ Some(Value::Array(values)) if key == "spacing" => {
+ Ok(values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(","))
+ }
+ Some(other) => bail!("{key} must be a string, not {other}"),
+ }
+ };
+ let spacing = Spacing::parse(&text(map, "spacing")?)?;
+ let matching = Match::parse(&text(map, "match")?)?;
+ let unpaired = Unpaired::parse(&text(map, "unpaired")?)?;
+ let cels = |map: &mut Map<String, Value>, key: &str| -> Result<Vec<String>> {
+ match map.remove(key) {
+ None | Some(Value::Null) => Ok(Vec::new()),
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("{key} must be a list of cel ids")),
+ }
+ };
+ let (only, keep_cels, force_cels) = (cels(map, "only")?, cels(map, "keepCels")?, cels(map, "forceCels")?);
+ let pairs: Vec<[u32; 2]> = match map.remove("pair") {
+ None | Some(Value::Null) => Vec::new(),
+ Some(v) => {
+ serde_json::from_value(v).map_err(|_| anyhow!("pair must be a list of [first key id, second key id]"))?
+ }
+ };
+ let spec = InbetweenSpec {
+ layers,
+ from: whole(map, "from")?,
+ to: whole(map, "to")?,
+ count: whole(map, "count")?,
+ spacing,
+ matching,
+ pairs,
+ redo: flag(map, "redo")?,
+ force: flag(map, "force")?,
+ looping: flag(map, "loop")?,
+ keep_drawn: flag(map, "keepDrawn")?,
+ unpaired,
+ only,
+ keep_cels,
+ force_cels,
+ resolved: None,
+ };
+ if !spec.redo && (spec.layers.is_empty() || spec.from.is_none() || (spec.to.is_none() && !spec.looping)) {
+ bail!(
+ "inbetween needs \"layers\", \"from\" and \"to\" (the frames of the two keys; with \"loop\" the end of the loop), or \"redo\": true"
+ );
+ }
+ if (spec.keep_drawn || !spec.only.is_empty() || !spec.keep_cels.is_empty() || !spec.force_cels.is_empty())
+ && !spec.redo
+ {
+ bail!("keepDrawn, only, keepCels and forceCels choose what a redo remakes; give \"redo\": true");
+ }
+ if spec.count == Some(0) {
+ bail!("count must be at least 1");
+ }
+ Ok(spec)
+}
+
+fn inbetweens(doc: &mut Document, made: &Inbetweens, out: &mut Applied) -> Result<()> {
+ made.removed.iter().try_for_each(|id| remove(doc, id, out))?;
+ made.holds.iter().try_for_each(|(id, hold)| {
+ let Some(Loc::Cel(path, c)) = doc.locate(id) else {
+ bail!("no cel {id}");
+ };
+ if let Some(cels) = doc.layer_at_mut(&path).cels_mut() {
+ cels[c].hold = Some(*hold);
+ }
+ Ok(())
+ })?;
+ made.cels.iter().try_for_each(|cel| {
+ let path = layer_path(doc, &cel.layer)?;
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer {} has no cels", cel.layer))?;
+ match cel.fresh {
+ true => {
+ if let Some(c) = cels.iter().find(|c| c.frame == cel.frame) {
+ bail!("layer {} already has {} at frame {}", cel.layer, c.id, cel.frame);
+ }
+ let at = cels.iter().position(|c| c.frame > cel.frame).unwrap_or(cels.len());
+ cels.insert(
+ at,
+ Cel {
+ hold: cel.hold,
+ tween: Some(cel.tween.clone()),
+ parts: cel.parts.clone(),
+ ..Cel::at(&cel.cel, cel.frame)
+ },
+ );
+ if let Some(n) = cel.cel.strip_prefix('c').and_then(|n| n.parse::<u64>().ok()) {
+ doc.next_id = doc.next_id.max(n);
+ }
+ out.added.push(cel.cel.clone());
+ }
+ false => {
+ let existing = cels
+ .iter_mut()
+ .find(|c| c.id == cel.cel)
+ .ok_or_else(|| anyhow!("no cel {} on layer {}", cel.cel, cel.layer))?;
+ existing.tween = Some(cel.tween.clone());
+ existing.parts = cel.parts.clone();
+ out.changed.push(cel.cel.clone());
+ }
+ }
+ out.push(&cel.layer, &cel.cel, MarkChange::Put(cel.marks.clone()));
+ Ok(())
+ })
+}
+
+fn parse_retime(map: &mut Map<String, Value>) -> Result<RetimeSpec> {
+ let (Some(from), Some(to)) = (whole(map, "from")?, whole(map, "to")?) else {
+ bail!("retime needs \"from\" and \"to\": the frames to retime, both included");
+ };
+ let on = whole(map, "on")?;
+ let fit = whole(map, "fit")?;
+ let (reverse, pingpong) = (flag(map, "reverse")?, flag(map, "pingpong")?);
+ let action = match (on, fit, reverse, pingpong) {
+ (Some(n), None, false, false) => Retime::On(n),
+ (None, Some(n), false, false) => Retime::Fit(n),
+ (None, None, true, false) => Retime::Reverse,
+ (None, None, false, true) => Retime::Pingpong,
+ _ => bail!(
+ "retime needs one of \"on\": <frames per drawing>, \"fit\": <frames>, \"reverse\": true or \"pingpong\": true"
+ ),
+ };
+ let layers = match map.remove("layers") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(serde_json::from_value(v).map_err(|_| anyhow!("layers must be a list of layer ids"))?),
+ };
+ Ok(RetimeSpec {
+ from,
+ to,
+ action,
+ layers,
+ })
+}
+
+fn parse_cel(map: &mut Map<String, Value>) -> Result<CelSpec> {
+ let actions = [
+ ("new", take_str(map, "new")?),
+ ("dup", take_str(map, "dup")?),
+ ("link", take_str(map, "link")?),
+ ("unlink", take_str(map, "unlink")?),
+ ("move", take_str(map, "move")?),
+ ];
+ let chosen: Vec<(&str, String)> = actions
+ .into_iter()
+ .filter_map(|(name, value)| value.map(|v| (name, v)))
+ .collect();
+ let action = match &chosen[..] {
+ [("new", layer)] => CelAction::New { layer: layer.clone() },
+ [("dup", cel)] => CelAction::Dup { cel: cel.clone() },
+ [("link", cel)] => CelAction::Link { cel: cel.clone() },
+ [("unlink", cel)] => CelAction::Unlink { cel: cel.clone() },
+ [("move", cel)] => CelAction::Move { cel: cel.clone() },
+ _ => bail!(
+ "cel needs one of \"new\": <layer>, \"dup\": <cel>, \"link\": <cel>, \"unlink\": <cel> or \"move\": <cel>"
+ ),
+ };
+ let hold = whole(map, "hold")?;
+ if hold == Some(0) {
+ bail!("hold must be at least 1");
+ }
+ Ok(CelSpec {
+ action,
+ id: take_str(map, "id")?,
+ frame: whole(map, "frame")?,
+ hold,
+ insert: flag(map, "insert")?,
+ })
+}
+
+fn parse_clip(map: &mut Map<String, Value>) -> Result<ClipEdit> {
+ let fps = match map.remove("fps") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(v) => Some(Some(
+ v.as_u64()
+ .filter(|n| (1..=240).contains(n))
+ .ok_or_else(|| anyhow!("fps must be 1 to 240, or null for the document's"))? as u32,
+ )),
+ };
+ let looping = match map.remove("loop") {
+ None | Some(Value::Null) => None,
+ Some(Value::Bool(b)) => Some(b),
+ Some(_) => bail!("loop must be true or false"),
+ };
+ let (from, to) = (whole(map, "from")?, whole(map, "to")?);
+ if let Some(name) = take_str(map, "add")? {
+ let (Some(from), Some(to)) = (from, to) else {
+ bail!("clip add needs \"from\" and \"to\" (frames, both included)");
+ };
+ return Ok(ClipEdit::Add(Clip {
+ fps: fps.flatten(),
+ ..Clip::new(&name, from, to, looping.unwrap_or(false))
+ }));
+ }
+ if let Some(name) = take_str(map, "set")? {
+ return Ok(ClipEdit::Set {
+ name,
+ rename: take_str(map, "name")?,
+ from,
+ to,
+ looping,
+ fps,
+ });
+ }
+ if let Some(name) = take_str(map, "rm")? {
+ return Ok(ClipEdit::Remove { name });
+ }
+ bail!(
+ "clip needs \"add\": <name> (with from, to, loop, fps), \"set\": <name> (from, to, loop, fps, name) or \"rm\": <name>"
+ )
+}
+
+fn clip_index(doc: &Document, name: &str) -> Result<usize> {
+ doc.timeline.clips.iter().position(|c| c.name == name).ok_or_else(|| {
+ let names: Vec<&str> = doc.timeline.clips.iter().map(|c| c.name.as_str()).collect();
+ match names.is_empty() {
+ true => anyhow!("no clip {name:?}: the document has no clips"),
+ false => anyhow!("no clip {name:?}: clips are {}", names.join(", ")),
+ }
+ })
+}
+
+fn edit_clip(doc: &mut Document, edit: &ClipEdit) -> Result<()> {
+ let clips = &doc.timeline.clips;
+ match edit {
+ ClipEdit::Add(clip) => {
+ if clips.iter().any(|c| c.name == clip.name) {
+ bail!("there is a clip {:?} already; use set to change it", clip.name);
+ }
+ let at = clips.iter().position(|c| c.from > clip.from).unwrap_or(clips.len());
+ doc.timeline.clips.insert(at, clip.clone());
+ }
+ ClipEdit::Set {
+ name,
+ rename,
+ from,
+ to,
+ looping,
+ fps,
+ } => {
+ let at = clip_index(doc, name)?;
+ let clip = &mut doc.timeline.clips[at];
+ if let Some(new) = rename {
+ clip.name = new.clone();
+ }
+ clip.from = from.unwrap_or(clip.from);
+ clip.to = to.unwrap_or(clip.to);
+ clip.looping = looping.unwrap_or(clip.looping);
+ clip.fps = fps.unwrap_or(clip.fps);
+ let moved = doc.timeline.clips.remove(at);
+ let clips = &doc.timeline.clips;
+ let at = clips.iter().position(|c| c.from > moved.from).unwrap_or(clips.len());
+ doc.timeline.clips.insert(at, moved);
+ }
+ ClipEdit::Remove { name } => {
+ let at = clip_index(doc, name)?;
+ doc.timeline.clips.remove(at);
+ }
+ }
+ Ok(())
+}
+
+fn parse_copy(map: &mut Map<String, Value>) -> Result<CopySpec> {
+ let mut ids: Vec<String> = match map.remove("ids") {
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("ids must be a list of strings"))?,
+ None => Vec::new(),
+ };
+ ids.extend(take_str(map, "id")?);
+ if ids.is_empty() {
+ bail!("copy needs ids: the strokes and fills to copy (<cel>:s<id>)");
+ }
+ let to = match (take_str(map, "to")?, whole(map, "frame")?) {
+ (Some(cel), None) => {
+ if map.contains_key("layer") {
+ bail!("copy takes \"layer\" with \"frame\"; \"to\" names the cel itself");
+ }
+ CopyTarget::Cel(cel)
+ }
+ (None, Some(frame)) => CopyTarget::Frame {
+ frame,
+ layer: take_str(map, "layer")?,
+ },
+ _ => {
+ bail!("copy needs \"to\": <cel> or \"frame\": <n> (with \"layer\" when the marks come from another layer)")
+ }
+ };
+ let cut = match map.remove("cut") {
+ None | Some(Value::Null) => None,
+ Some(v) => {
+ let polygon: Vec<[f32; 2]> =
+ serde_json::from_value(v).map_err(|_| anyhow!("cut must be a polygon [[x, y], ...]"))?;
+ if polygon.len() < 3 {
+ bail!("a cut polygon needs at least 3 points");
+ }
+ Some(polygon)
+ }
+ };
+ let transform = MarkTransform::parse(map)?;
+ let moved = MarkTransform {
+ pivot: None,
+ ..transform
+ } != MarkTransform::default();
+ Ok(CopySpec {
+ ids,
+ to,
+ transform: moved.then_some(transform),
+ cut,
+ })
+}
+
+fn copy(doc: &mut Document, spec: &CopySpec, out: &mut Applied) -> Result<String> {
+ let mut sources: Vec<(String, String, Vec<u32>)> = Vec::new();
+ spec.ids.iter().try_for_each(|id| {
+ let (cel, mark) =
+ parse_address(id).ok_or_else(|| anyhow!("copy takes strokes and fills (<cel>:s<id>), not {id}"))?;
+ let layer = mark_owner(doc, cel)?;
+ match sources.iter_mut().find(|(_, c, _)| c == cel) {
+ Some((_, _, ids)) if ids.contains(&mark) => {}
+ Some((_, _, ids)) => ids.push(mark),
+ None => sources.push((layer, cel.to_string(), vec![mark])),
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let (layer, cel) = match &spec.to {
+ CopyTarget::Cel(cel) => {
+ if let Some(Item::Cel(_, c)) = doc.item(cel)
+ && let Some(source) = &c.link
+ {
+ bail!("cel {cel} links to {source}; copy into {source} instead");
+ }
+ (mark_owner(doc, cel)?, cel.clone())
+ }
+ CopyTarget::Frame { frame, layer } => {
+ let layer = match layer {
+ Some(key) => doc.find_layer(key)?.id.clone(),
+ None => {
+ let layers: BTreeSet<&str> = sources.iter().map(|(l, _, _)| l.as_str()).collect();
+ match layers.len() {
+ 1 => sources[0].0.clone(),
+ _ => bail!(
+ "the marks come from layers {}; say which layer they go to with \"layer\"",
+ layers.into_iter().collect::<Vec<_>>().join(" and ")
+ ),
+ }
+ }
+ };
+ let cel = paint_cel_at(doc, &layer, *frame, out)?;
+ (layer, cel)
+ }
+ };
+ out.paste(&layer, &cel, sources, spec.transform, spec.cut.clone());
+ out.changed.push(cel.clone());
+ Ok(cel)
+}
+
+fn parse_lasso(map: &mut Map<String, Value>) -> Result<LassoSpec> {
+ let layer = take_str(map, "layer")?.ok_or_else(|| anyhow!("lasso needs \"layer\": a paint layer id"))?;
+ let frame = match map.remove("frame") {
+ None | Some(Value::Null) => 0,
+ Some(v) => v.as_u64().ok_or_else(|| anyhow!("frame must be a whole number"))? as u32,
+ };
+ let polygon: Vec<[f32; 2]> = match map.remove("polygon") {
+ Some(v) => serde_json::from_value(v).map_err(|_| anyhow!("polygon must be [[x, y], ...]"))?,
+ None => bail!("lasso needs \"polygon\": [[x, y], ...]"),
+ };
+ if polygon.len() < 3 {
+ bail!("a lasso polygon needs at least 3 points");
+ }
+ let cut = flag(map, "cut")?;
+ let action = if flag(map, "rm")? {
+ LassoAction::Remove
+ } else {
+ LassoAction::Transform(MarkTransform::parse(map)?)
+ };
+ Ok(LassoSpec {
+ layer,
+ frame,
+ polygon,
+ cut,
+ action,
+ })
+}
+
+fn parse_palette(map: &mut Map<String, Value>) -> Result<PaletteEdit> {
+ if let Some(color) = map.remove("add") {
+ let color = color
+ .as_str()
+ .ok_or_else(|| anyhow!("palette add takes a colour string, #rrggbb or #rrggbbaa"))?
+ .to_string();
+ let name = take_str(map, "name")?.unwrap_or_default();
+ let index = match map.remove("index") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(v.as_u64().ok_or_else(|| anyhow!("index must be a whole number"))? as usize),
+ };
+ return Ok(PaletteEdit::Add { color, name, index });
+ }
+ if let Some(key) = map.remove("rm") {
+ let key = match key {
+ Value::String(s) => s,
+ Value::Number(n) => n.to_string(),
+ other => bail!("palette rm takes a name, a colour or an index, not {other}"),
+ };
+ return Ok(PaletteEdit::Remove { key });
+ }
+ if let Some(list) = map.remove("set") {
+ let swatches: Vec<Swatch> = serde_json::from_value(list)
+ .context("palette set takes a list like [{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]")?;
+ return Ok(PaletteEdit::Set { swatches });
+ }
+ bail!("palette needs \"add\" (with \"name\"), \"rm\" or \"set\"")
+}
+
+fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {
+ match edit {
+ PaletteEdit::Add { color, name, index } => {
+ parse_hex(color)?;
+ let same_name = (!name.is_empty())
+ .then(|| doc.palette.iter().position(|s| &s.name == name))
+ .flatten();
+ if let Some(at) = same_name {
+ doc.palette[at].color = color.clone();
+ return Ok(());
+ }
+ if name.is_empty()
+ && doc
+ .palette
+ .iter()
+ .any(|s| s.name.is_empty() && s.color.eq_ignore_ascii_case(color))
+ {
+ return Ok(());
+ }
+ let at = index.unwrap_or(doc.palette.len()).min(doc.palette.len());
+ doc.palette.insert(
+ at,
+ Swatch {
+ color: color.clone(),
+ name: name.clone(),
+ },
+ );
+ }
+ PaletteEdit::Remove { key } => {
+ let at = doc
+ .swatch(key)
+ .ok_or_else(|| anyhow!("the palette has no {key:?} (give a name, a colour or an index)"))?;
+ doc.palette.remove(at);
+ }
+ PaletteEdit::Set { swatches } => doc.palette = swatches.clone(),
+ }
+ Ok(())
+}
+
+fn check_keys(value: &Value, allowed: &[&str], what: &str) -> Result<()> {
+ let Some(map) = value.as_object() else {
+ bail!("{what} must be a JSON object");
+ };
+ map.keys().try_for_each(|key| {
+ if allowed.contains(&key.as_str()) {
+ Ok(())
+ } else {
+ bail!("{what} has no {key:?}; it takes {}", allowed.join(", "))
+ }
+ })
+}
+
+fn check_node_keys(value: &Value) -> Result<()> {
+ let kind = value
+ .get("type")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("a node needs a type"))?;
+ let allowed: Vec<&str> = NODE_KEYS.iter().chain(shape_keys(kind)?).copied().collect();
+ check_keys(value, &allowed, &format!("a {kind} node"))?;
+ if let Some(t) = value.get("transform") {
+ check_keys(t, TRANSFORM_KEYS, "transform")?;
+ }
+ if let Some(s) = value.get("stroke") {
+ check_keys(s, STROKE_KEYS, "stroke")?;
+ }
+ value
+ .get("children")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .try_for_each(check_node_keys)
+}
+
+fn ensure_id(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mut Value, prefix: char) -> Result<String> {
+ match value.get("id").and_then(Value::as_str) {
+ Some(id) if !taken.insert(id.to_string()) => bail!("id {id} is already used"),
+ Some(id) => Ok(id.to_string()),
+ None => {
+ let id = doc.alloc_id_in(prefix, taken);
+ value["id"] = Value::String(id.clone());
+ Ok(id)
+ }
+ }
+}
+
+fn assign_node_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mut Value) -> Result<String> {
+ let id = ensure_id(doc, taken, value, 'n')?;
+ if let Some(children) = value.get_mut("children").and_then(Value::as_array_mut) {
+ children
+ .iter_mut()
+ .try_for_each(|c| assign_node_ids(doc, taken, c).map(|_| ()))?;
+ }
+ Ok(id)
+}
+
+fn assign_layer_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mut Value) -> Result<String> {
+ check_keys(value, LAYER_KEYS, "a layer")?;
+ let kind = value
+ .get("kind")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("a layer needs a kind: paint, vector, group or adjust"))?
+ .to_string();
+ let id = ensure_id(doc, taken, value, 'l')?;
+ if value.get("name").is_none() {
+ value["name"] = Value::String(format!("{kind} {id}"));
+ }
+ match kind.as_str() {
+ "paint" | "vector" => {
+ if value.get("cels").is_none_or(|c| c.as_array().is_none_or(Vec::is_empty)) {
+ value["cels"] = serde_json::json!([{ "frame": 0 }]);
+ }
+ if let Some(cels) = value.get_mut("cels").and_then(Value::as_array_mut) {
+ cels.iter_mut().try_for_each(|cel| {
+ check_keys(cel, CEL_KEYS, "a cel")?;
+ ensure_id(doc, taken, cel, 'c')?;
+ cel.get_mut("nodes")
+ .and_then(Value::as_array_mut)
+ .into_iter()
+ .flatten()
+ .try_for_each(|n| {
+ check_node_keys(n)?;
+ assign_node_ids(doc, taken, n).map(|_| ())
+ })
+ })?;
+ }
+ }
+ "group" => {
+ if let Some(children) = value.get_mut("children").and_then(Value::as_array_mut) {
+ children
+ .iter_mut()
+ .try_for_each(|c| assign_layer_ids(doc, taken, c).map(|_| ()))?;
+ }
+ }
+ "adjust" => {
+ if value.get("adjust").is_none() {
+ bail!(
+ "an adjustment layer needs adjust: {}",
+ crate::look::ADJUSTMENTS.map(|a| format!("{{\"{a}\":{{}}}}")).join(", ")
+ );
+ }
+ }
+ other => bail!("unknown layer kind {other:?}: use paint, vector, group or adjust"),
+ }
+ if let Some(mask) = value.get_mut("mask").filter(|m| !m.is_null()) {
+ mask_defaults(mask)?;
+ assign_layer_ids(doc, taken, mask)?;
+ }
+ Ok(id)
+}
+
+fn mask_defaults(mask: &mut Value) -> Result<()> {
+ let Some(map) = mask.as_object_mut() else {
+ bail!("a mask must be a JSON object");
+ };
+ match map.get("kind").and_then(Value::as_str) {
+ None => {
+ map.insert("kind".into(), json!("paint"));
+ }
+ Some("paint") => {}
+ Some(other) => bail!("a mask is a paint layer, not {other}"),
+ }
+ map.entry("name").or_insert_with(|| json!("mask"));
+ Ok(())
+}
+
+fn layer_path(doc: &Document, id: &str) -> Result<Vec<usize>> {
+ match doc.locate(id) {
+ Some(Loc::Layer(path)) => Ok(path),
+ Some(_) => bail!("{id} is not a layer"),
+ None => bail!("no item {id}"),
+ }
+}
+
+fn fresh_layer(
+ doc: &mut Document,
+ taken: &mut BTreeSet<String>,
+ layer: &Layer,
+ copies: &mut Vec<(String, String, String, String)>,
+) -> Layer {
+ let mut copy = layer.clone();
+ copy.id = doc.alloc_id_in('l', taken);
+ let paint = layer.kind() == Kind::Paint;
+ let fresh: Vec<(String, String)> = layer
+ .cels()
+ .iter()
+ .map(|c| (c.id.clone(), doc.alloc_id_in('c', taken)))
+ .collect();
+ let rename = |id: &str| {
+ fresh
+ .iter()
+ .find(|(old, _)| old == id)
+ .map_or(id.to_string(), |(_, new)| new.clone())
+ };
+ let nodes: Vec<Vec<Node>> = layer
+ .cels()
+ .iter()
+ .map(|c| crate::timing::renumbered(doc, &c.nodes))
+ .collect();
+ let copy_id = copy.id.clone();
+ if let Some(cels) = copy.cels_mut() {
+ cels.iter_mut().zip(nodes).for_each(|(c, nodes)| {
+ let old = c.id.clone();
+ c.id = rename(&old);
+ c.link = c.link.as_deref().map(rename);
+ if let Some(t) = c.tween.as_mut() {
+ t.from = rename(&t.from);
+ t.to = rename(&t.to);
+ }
+ c.nodes = nodes;
+ if paint && c.link.is_none() {
+ copies.push((copy_id.clone(), c.id.clone(), layer.id.clone(), old));
+ }
+ });
+ }
+ if let LayerContent::Group { children } = &mut copy.content {
+ *children = layer
+ .children()
+ .iter()
+ .map(|child| fresh_layer(doc, taken, child, copies))
+ .collect();
+ }
+ copy.mask = layer
+ .mask
+ .as_deref()
+ .map(|m| Box::new(fresh_layer(doc, taken, m, copies)));
+ copy
+}
+
+fn duplicate_layer(doc: &mut Document, id: &str, out: &mut Applied) -> Result<String> {
+ let path = layer_path(doc, id)?;
+ if path.last() == Some(&MASK) {
+ bail!("{id} is a mask; duplicate the layer it masks");
+ }
+ let source = doc.layer_at(&path).clone();
+ let mut taken = doc.ids();
+ let mut copies = Vec::new();
+ let mut copy = fresh_layer(doc, &mut taken, &source, &mut copies);
+ copy.name = format!("{} copy", source.name);
+ let new_id = copy.id.clone();
+ let (parent, index) = (path[..path.len() - 1].to_vec(), path[path.len() - 1] + 1);
+ doc.layer_list_mut(&parent)
+ .ok_or_else(|| anyhow!("{id} has no list to go into"))?
+ .insert(index, copy);
+ copies
+ .iter()
+ .for_each(|(layer, cel, from_layer, from_cel)| out.copy(layer, cel, from_layer, from_cel));
+ Ok(new_id)
+}
+
+fn layer_slot(doc: &Document, place: &Place) -> Result<(Vec<usize>, usize)> {
+ let sibling = |id: &str, offset: usize| -> Result<(Vec<usize>, usize)> {
+ let mut path = layer_path(doc, id)?;
+ let index = path.pop().unwrap_or_default();
+ if index == MASK {
+ bail!("{id} is a mask; layers go above or below the layer it masks");
+ }
+ Ok((path, index + offset))
+ };
+ let (parent, index) = match (&place.above, &place.below, &place.into) {
+ (Some(id), _, _) => sibling(id, 1)?,
+ (_, Some(id), _) => sibling(id, 0)?,
+ (_, _, Some(id)) => {
+ let path = layer_path(doc, id)?;
+ let group = doc.layer_at(&path);
+ if group.kind() != Kind::Group {
+ bail!("{id} is a {} layer; layers go into group layers", group.kind().name());
+ }
+ let len = group.children().len();
+ (path, place.index.unwrap_or(len))
+ }
+ _ => (Vec::new(), place.index.unwrap_or(doc.layers.len())),
+ };
+ let len = if parent.is_empty() {
+ doc.layers.len()
+ } else {
+ doc.layer_at(&parent).children().len()
+ };
+ if index > len {
+ bail!("index {index} is past the end ({len} layers)");
+ }
+ Ok((parent, index))
+}
+
+struct NodeSlot {
+ layer: Vec<usize>,
+ cel: usize,
+ parent: Vec<usize>,
+ index: Option<usize>,
+}
+
+fn node_list<'a>(doc: &'a mut Document, layer: &[usize], cel: usize, parent: &[usize]) -> Result<&'a mut Vec<Node>> {
+ let cels = doc
+ .layer_at_mut(layer)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("not a layer with cels"))?;
+ parent
+ .iter()
+ .try_fold(&mut cels[cel].nodes, |list, &i| match list[i].shape.children_mut() {
+ Some(children) => Ok(children),
+ None => bail!("node path runs through a non-group node"),
+ })
+}
+
+fn cel_for_nodes(doc: &mut Document, path: &[usize], frame: u32) -> Result<usize> {
+ let layer = doc.layer_at(path);
+ if layer.kind() != Kind::Vector {
+ bail!(
+ "{} is a {} layer; shapes go into vector layers",
+ layer.id,
+ layer.kind().name()
+ );
+ }
+ if let Some(cel) = layer.cel_at(frame).filter(|_| frame < doc.timeline.frames) {
+ if let Some(target) = &cel.link {
+ bail!(
+ "cel {} at frame {frame} links to {target}; add to {target} instead",
+ cel.id
+ );
+ }
+ let id = cel.id.clone();
+ return Ok(layer.cels().iter().position(|c| c.id == id).unwrap_or_default());
+ }
+ let id = doc.alloc_id('c');
+ let cels = doc
+ .layer_at_mut(path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer has no cels"))?;
+ let index = cels.iter().position(|c| c.frame > frame).unwrap_or(cels.len());
+ cels.insert(index, Cel::at(&id, frame));
+ Ok(index)
+}
+
+fn node_slot(doc: &mut Document, place: &Place) -> Result<NodeSlot> {
+ let sibling = |doc: &Document, id: &str, offset: usize| -> Result<NodeSlot> {
+ match doc.locate(id) {
+ Some(Loc::Node(layer, cel, mut nodes)) => {
+ let index = nodes.pop().unwrap_or_default();
+ Ok(NodeSlot {
+ layer,
+ cel,
+ parent: nodes,
+ index: Some(index + offset),
+ })
+ }
+ Some(_) => bail!("{id} is not a node"),
+ None => bail!("no item {id}"),
+ }
+ };
+ if let Some(id) = &place.above {
+ return sibling(doc, id, 1);
+ }
+ if let Some(id) = &place.below {
+ return sibling(doc, id, 0);
+ }
+ let Some(id) = &place.into else {
+ bail!("say where the node goes: in=<vector layer, cel or group node>, above=<node> or below=<node>");
+ };
+ let slot = match doc.locate(id) {
+ Some(Loc::Layer(layer)) => NodeSlot {
+ cel: cel_for_nodes(doc, &layer, place.frame.unwrap_or(0))?,
+ layer,
+ parent: Vec::new(),
+ index: place.index,
+ },
+ Some(Loc::Cel(layer, cel)) => {
+ let owner = doc.layer_at(&layer);
+ let target = &owner.cels()[cel];
+ if owner.kind() != Kind::Vector {
+ bail!(
+ "cel {id} belongs to a {} layer; shapes go into vector layers",
+ owner.kind().name()
+ );
+ }
+ if let Some(source) = &target.link {
+ bail!("cel {id} links to {source}; add to {source} instead");
+ }
+ NodeSlot {
+ layer,
+ cel,
+ parent: Vec::new(),
+ index: place.index,
+ }
+ }
+ Some(Loc::Node(layer, cel, nodes)) => NodeSlot {
+ layer,
+ cel,
+ parent: nodes,
+ index: place.index,
+ },
+ None => bail!("no item {id}"),
+ };
+ Ok(slot)
+}
+
+fn insert_node(doc: &mut Document, slot: NodeSlot, node: Node) -> Result<()> {
+ let list = node_list(doc, &slot.layer, slot.cel, &slot.parent)?;
+ let index = slot.index.unwrap_or(list.len());
+ if index > list.len() {
+ bail!("index {index} is past the end ({} nodes)", list.len());
+ }
+ list.insert(index, node);
+ Ok(())
+}
+
+fn set_path(target: &mut Value, path: &str, value: Value) -> Result<()> {
+ let parts: Vec<&str> = path.split('.').collect();
+ if parts.first().is_some_and(|p| STRUCTURE.contains(p)) {
+ bail!("{path} cannot be set; use add, rm or mv for structure");
+ }
+ let (last, parents) = parts.split_last().ok_or_else(|| anyhow!("empty property name"))?;
+ let parent = parents.iter().try_fold(target, |node, part| {
+ let map = node
+ .as_object_mut()
+ .ok_or_else(|| anyhow!("{path}: {part} is not an object"))?;
+ let child = map.entry(part.to_string()).or_insert_with(|| Value::Object(Map::new()));
+ if child.is_null() {
+ *child = Value::Object(Map::new());
+ }
+ Ok::<_, anyhow::Error>(child)
+ })?;
+ let map = parent
+ .as_object_mut()
+ .ok_or_else(|| anyhow!("{path}: parent is not an object"))?;
+ if value.is_null() {
+ map.remove(*last);
+ } else {
+ map.insert(last.to_string(), value);
+ }
+ Ok(())
+}
+
+fn patched<T: serde::Serialize + serde::de::DeserializeOwned>(
+ item: &T,
+ props: &Map<String, Value>,
+ check: impl Fn(&Value) -> Result<()>,
+) -> Result<T> {
+ let mut value = serde_json::to_value(item)?;
+ props.iter().try_for_each(|(k, v)| set_path(&mut value, k, v.clone()))?;
+ check(&value)?;
+ Ok(serde_json::from_value(value)?)
+}
+
+fn set(doc: &mut Document, id: &str, props: &Map<String, Value>) -> Result<()> {
+ match doc.locate(id).ok_or_else(|| anyhow!("no item {id}"))? {
+ Loc::Layer(path) => {
+ let layer = doc.layer_at_mut(&path);
+ *layer = patched(&*layer, props, |v| check_keys(v, LAYER_KEYS, "a layer"))?;
+ }
+ Loc::Cel(path, c) => {
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer has no cels"))?;
+ cels[c] = patched(&cels[c], props, |v| check_keys(v, CEL_KEYS, "a cel"))?;
+ cels.sort_by_key(|c| c.frame);
+ }
+ Loc::Node(path, c, mut nodes) => {
+ let index = nodes.pop().unwrap_or_default();
+ let list = node_list(doc, &path, c, &nodes)?;
+ list[index] = patched(&list[index], props, check_node_keys)?;
+ }
+ }
+ Ok(())
+}
+
+fn paint_cels_of(layer: &Layer) -> Vec<(String, String)> {
+ let own = layer
+ .cels()
+ .iter()
+ .filter(|c| layer.kind() == Kind::Paint && c.link.is_none())
+ .map(|c| (layer.id.clone(), c.id.clone()));
+ own.chain(layer.mask.iter().flat_map(|m| paint_cels_of(m)))
+ .chain(layer.children().iter().flat_map(paint_cels_of))
+ .collect()
+}
+
+fn remove(doc: &mut Document, id: &str, out: &mut Applied) -> Result<()> {
+ let Some(loc) = doc.locate(id) else {
+ return Ok(());
+ };
+ match loc {
+ Loc::Layer(mut path) if path.last() == Some(&MASK) => {
+ path.pop();
+ if let Some(mask) = doc.layer_at_mut(&path).mask.take() {
+ out.dropped_cels.extend(paint_cels_of(&mask));
+ }
+ }
+ Loc::Layer(mut path) => {
+ let index = path.pop().unwrap_or_default();
+ let list = doc
+ .layer_list_mut(&path)
+ .ok_or_else(|| anyhow!("parent is not a group"))?;
+ let layer = list.remove(index);
+ out.dropped_cels.extend(paint_cels_of(&layer));
+ }
+ Loc::Cel(path, c) => {
+ let layer = doc.layer_at_mut(&path);
+ let cel = layer.cels_mut().ok_or_else(|| anyhow!("layer has no cels"))?.remove(c);
+ timing::hand_over(layer, vec![cel], out);
+ }
+ Loc::Node(path, c, mut nodes) => {
+ let index = nodes.pop().unwrap_or_default();
+ node_list(doc, &path, c, &nodes)?.remove(index);
+ }
+ }
+ out.removed.push(id.to_string());
+ Ok(())
+}
+
+fn move_item(doc: &mut Document, id: &str, place: &Place) -> Result<()> {
+ match doc.locate(id).ok_or_else(|| anyhow!("no item {id}"))? {
+ Loc::Layer(path) if path.last() == Some(&MASK) => {
+ bail!("{id} is a mask and stays with its layer; rm it and add a mask to the other layer")
+ }
+ Loc::Layer(mut path) => {
+ let index = path.pop().unwrap_or_default();
+ let layer = doc
+ .layer_list_mut(&path)
+ .ok_or_else(|| anyhow!("parent is not a group"))?
+ .remove(index);
+ let (parent, at) = layer_slot(doc, place).map_err(|e| anyhow!("{e} (a layer cannot move into itself)"))?;
+ doc.layer_list_mut(&parent)
+ .ok_or_else(|| anyhow!("target is not a group"))?
+ .insert(at, layer);
+ }
+ Loc::Node(path, c, mut nodes) => {
+ let index = nodes.pop().unwrap_or_default();
+ let node = node_list(doc, &path, c, &nodes)?.remove(index);
+ let slot = node_slot(doc, place).map_err(|e| anyhow!("{e} (a node cannot move into itself)"))?;
+ insert_node(doc, slot, node)?;
+ }
+ Loc::Cel(..) => bail!("cels move by setting their frame: set {id} frame=<n>"),
+ }
+ Ok(())
+}
+
+pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
+ match op {
+ Op::AddLayer { layer, place } => {
+ let mut value = layer.clone();
+ let id = assign_layer_ids(doc, &mut doc.ids(), &mut value)?;
+ let layer: Layer = serde_json::from_value(value)?;
+ let (parent, index) = layer_slot(doc, place)?;
+ doc.layer_list_mut(&parent)
+ .ok_or_else(|| anyhow!("target is not a group"))?
+ .insert(index, layer);
+ out.added.push(id);
+ }
+ Op::AddNode { node, place } => {
+ let mut value = node.clone();
+ check_node_keys(&value)?;
+ let id = assign_node_ids(doc, &mut doc.ids(), &mut value)?;
+ let node: Node = serde_json::from_value(value)?;
+ let slot = node_slot(doc, place)?;
+ insert_node(doc, slot, node)?;
+ out.added.push(id);
+ }
+ Op::AddCel { cel, layer } => {
+ let mut value = cel.clone();
+ check_keys(&value, CEL_KEYS, "a cel")?;
+ let id = ensure_id(doc, &mut doc.ids(), &mut value, 'c')?;
+ let cel: Cel = serde_json::from_value(value)?;
+ let path = layer_path(doc, layer)?;
+ let target = doc.layer_at_mut(&path);
+ let cels = match &mut target.content {
+ LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,
+ LayerContent::Group { .. } => bail!("{layer} is a group; cels go into paint or vector layers"),
+ LayerContent::Adjust { .. } => bail!("{layer} is an adjustment; cels go into paint or vector layers"),
+ };
+ if cels.iter().any(|c| c.frame == cel.frame) {
+ bail!("layer {layer} already has a cel starting at frame {}", cel.frame);
+ }
+ let index = cels.iter().position(|c| c.frame > cel.frame).unwrap_or(cels.len());
+ cels.insert(index, cel);
+ out.added.push(id);
+ }
+ Op::AddMask { mask, layer, hide } => {
+ let path = layer_path(doc, layer)?;
+ if path.last() == Some(&MASK) {
+ bail!("{layer} is a mask itself");
+ }
+ if doc.layer_at(&path).mask.is_some() {
+ bail!("layer {layer} already has a mask; rm it first");
+ }
+ let mut value = mask.clone();
+ mask_defaults(&mut value)?;
+ let id = assign_layer_ids(doc, &mut doc.ids(), &mut value)?;
+ let added: Layer = serde_json::from_value(value)?;
+ let cel = added.cels().first().map(|c| c.id.clone());
+ doc.layer_at_mut(&path).mask = Some(Box::new(added));
+ out.added.push(id.clone());
+ if let (true, Some(cel)) = (*hide, cel) {
+ out.push(&id, &cel, MarkChange::Add(vec![Mark::Fill(everything(doc))]));
+ }
+ }
+ Op::Lasso(spec) => {
+ let path = layer_path(doc, &spec.layer)?;
+ let target = doc.layer_at(&path);
+ let cel = target
+ .content_at(spec.frame)
+ .ok_or_else(|| anyhow!("layer {} has no cel at frame {}", spec.layer, spec.frame))?;
+ let cel = cel.id.clone();
+ let layer = mark_owner(doc, &cel)?;
+ out.push(
+ &layer,
+ &cel,
+ MarkChange::Lasso {
+ polygon: spec.polygon.clone(),
+ cut: spec.cut,
+ action: spec.action.clone(),
+ chosen: Vec::new(),
+ },
+ );
+ out.changed.push(spec.layer.clone());
+ }
+ Op::Set { id, props } => {
+ match parse_address(id) {
+ Some((cel, mark)) => {
+ let layer = mark_owner(doc, cel)?;
+ let mut props = props.clone();
+ if let Some(color) = props.get("color").and_then(Value::as_str) {
+ let hex = doc.resolve_color(color).with_context(|| format!("set {id}"))?;
+ props.insert("color".into(), Value::String(hex));
+ }
+ out.push(&layer, cel, MarkChange::Set { id: mark, props });
+ }
+ None => set(doc, id, props).with_context(|| format!("set {id}"))?,
+ }
+ out.changed.push(id.clone());
+ }
+ Op::Remove { ids } => {
+ ids.iter().try_for_each(|id| {
+ if parse_address(id).is_none() && doc.locate(id).is_none() && !out.removed.contains(id) {
+ bail!("no item {id}");
+ }
+ Ok(())
+ })?;
+ ids.iter().try_for_each(|id| match parse_address(id) {
+ Some((cel, mark)) => {
+ let layer = mark_owner(doc, cel)?;
+ out.push(&layer, cel, MarkChange::Remove { id: mark });
+ out.removed.push(id.clone());
+ Ok(())
+ }
+ None => remove(doc, id, out),
+ })?;
+ }
+ Op::Transform { ids, transform } => {
+ let mut cels: Vec<(String, Vec<u32>)> = Vec::new();
+ ids.iter().try_for_each(|id| {
+ let (cel, mark) = parse_address(id)
+ .ok_or_else(|| anyhow!("transform takes strokes and fills (<cel>:s<id>), not {id}; shapes take set {id} transform.x=..."))?;
+ match cels.iter_mut().find(|(c, _)| c == cel) {
+ Some((_, marks)) => marks.push(mark),
+ None => cels.push((cel.to_string(), vec![mark])),
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ if cels.len() > 1 && transform.pivot.is_none() {
+ bail!(
+ "the ids span cels {}; give a pivot so they turn and scale about one point",
+ cels.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(" and ")
+ );
+ }
+ cels.into_iter().try_for_each(|(cel, marks)| {
+ let layer = mark_owner(doc, &cel)?;
+ out.push(
+ &layer,
+ &cel,
+ MarkChange::Transform {
+ ids: marks,
+ transform: *transform,
+ },
+ );
+ Ok::<_, anyhow::Error>(())
+ })?;
+ out.changed.extend(ids.iter().cloned());
+ }
+ Op::Move { id, place } => {
+ move_item(doc, id, place).with_context(|| format!("mv {id}"))?;
+ out.changed.push(id.clone());
+ }
+ Op::Stroke(spec) => {
+ let resolved = StrokeSpec {
+ color: doc.resolve_color(&spec.color)?,
+ second: spec.second.as_deref().map(|c| doc.resolve_color(c)).transpose()?,
+ ..spec.clone()
+ };
+ let strokes = resolved.build().with_context(|| format!("stroke on {}", spec.layer))?;
+ let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
+ let lock = locks_alpha(doc, &spec.layer);
+ out.push(
+ &spec.layer,
+ &cel,
+ MarkChange::Add(
+ strokes
+ .iter()
+ .cloned()
+ .map(|s| Mark::Stroke(Stroke { lock, ..s }))
+ .collect(),
+ ),
+ );
+ if let Some(name) = &spec.part {
+ out.push(
+ &spec.layer,
+ &cel,
+ MarkChange::Part {
+ name: name.clone(),
+ count: strokes.len(),
+ ids: Vec::new(),
+ },
+ );
+ }
+ }
+ Op::Fill(spec) if spec.like.is_some() => {
+ let Some(carried) = &spec.carried else {
+ bail!(
+ "fills like another drawing's are carried by klad fill --like (or klad apply), which computes them first"
+ );
+ };
+ carried.iter().try_for_each(|(cel, marks)| {
+ let layer = mark_owner(doc, cel)?;
+ out.push(&layer, cel, MarkChange::Put(marks.clone()));
+ out.changed.push(cel.clone());
+ Ok::<_, anyhow::Error>(())
+ })?;
+ }
+ Op::Fill(spec) => {
+ let mut fill = spec.build(doc).with_context(|| format!("fill on {}", spec.layer))?;
+ fill.lock = locks_alpha(doc, &spec.layer);
+ let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
+ out.push(&spec.layer, &cel, MarkChange::Add(vec![Mark::Fill(fill)]));
+ if let Some(name) = &spec.part {
+ out.push(
+ &spec.layer,
+ &cel,
+ MarkChange::Part {
+ name: name.clone(),
+ count: 1,
+ ids: Vec::new(),
+ },
+ );
+ }
+ }
+ Op::Part { ids, name } => {
+ let mut by_cel: BTreeMap<String, Vec<u32>> = BTreeMap::new();
+ ids.iter().try_for_each(|text| {
+ let (cel, id) = crate::markedit::parse_address(text)
+ .ok_or_else(|| anyhow!("{text:?} is not a mark address like c4:s12"))?;
+ by_cel.entry(cel.to_string()).or_default().push(id);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ if by_cel.is_empty() {
+ bail!("part needs at least one mark");
+ }
+ by_cel.into_iter().try_for_each(|(cel, ids)| {
+ let layer = mark_owner(doc, &cel)?;
+ out.push(
+ &layer,
+ &cel,
+ MarkChange::Part {
+ name: name.clone(),
+ count: 0,
+ ids,
+ },
+ );
+ out.changed.push(cel);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ }
+ Op::Copy(spec) => {
+ copy(doc, spec, out)?;
+ }
+ Op::Path { id, edit } => {
+ edit_path(doc, id, edit).with_context(|| format!("path {id}"))?;
+ out.changed.push(id.clone());
+ }
+ Op::Palette(edit) => {
+ edit_palette(doc, edit)?;
+ if !out.changed.iter().any(|c| c == "palette") {
+ out.changed.push("palette".into());
+ }
+ }
+ Op::Atmosphere(air) => {
+ if let Some(air) = air {
+ air.validate()?;
+ }
+ doc.atmosphere = air.clone();
+ out.changed.push("atmosphere".into());
+ }
+ Op::Timeline { fps, frames, origin } => {
+ timing::timeline(doc, *fps, *frames)?;
+ if let Some(origin) = origin {
+ doc.timeline.origin = *origin;
+ }
+ out.changed.push("timeline".into());
+ }
+ Op::Frames(spec) => timing::frames(doc, spec, out)?,
+ Op::Retime(spec) => {
+ let note = retime::retime(doc, spec, out)?;
+ out.notes.push(note);
+ }
+ Op::Duplicate { layer } => {
+ let id = duplicate_layer(doc, layer, out)?;
+ out.added.push(id);
+ }
+ Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) => {
+ bail!(
+ "ink, light, hatch, paint and scatter are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter or klad apply first"
+ );
+ }
+ Op::Inbetween(spec) => {
+ let Some(made) = &spec.resolved else {
+ bail!(
+ "in-betweens are made by klad inbetween (or klad apply), which computes their strokes and fills first"
+ );
+ };
+ inbetweens(doc, made, out)?;
+ }
+ Op::Cel(spec) => {
+ timing::cel(doc, spec, out)?;
+ }
+ Op::Clip(edit) => {
+ edit_clip(doc, edit)?;
+ out.changed.push("timeline".into());
+ }
+ Op::Export { godot } => {
+ doc.export.godot = godot.clone();
+ out.changed.push("export".into());
+ }
+ }
+ Ok(())
+}
+
+fn edit_path(doc: &mut Document, id: &str, edit: &PathEdit) -> Result<()> {
+ let Some(Loc::Node(path, c, mut nodes)) = doc.locate(id) else {
+ bail!("{id} is not a shape; path edits work on path, rect and ellipse nodes");
+ };
+ let index = nodes.pop().unwrap_or_default();
+ let node = &mut node_list(doc, &path, c, &nodes)?[index];
+ let mut subs = pathedit::from_shape(&node.shape)?;
+ edit.apply(&mut subs)?;
+ node.shape = Shape::Path {
+ d: pathedit::to_d(&subs),
+ };
+ Ok(())
+}
+
+fn locks_alpha(doc: &Document, layer: &str) -> bool {
+ doc.layer(layer).is_some_and(|l| l.lock_alpha)
+}
+
+pub fn everything(doc: &Document) -> Fill {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let (fw, fh) = (w as f32, h as f32);
+ let coverage = Coverage {
+ x: 0,
+ y: 0,
+ width: w,
+ height: h,
+ alpha: vec![255; w as usize * h as usize],
+ };
+ Fill::new(
+ 0,
+ [0.0, 0.0, 0.0, 1.0],
+ FillSource::Polygon(vec![[0.0, 0.0], [fw, 0.0], [fw, fh], [0.0, fh]]),
+ coverage,
+ )
+ .by(Author::Agent)
+}
+
+fn mark_owner(doc: &Document, cel: &str) -> Result<String> {
+ match doc.locate(cel) {
+ Some(Loc::Cel(path, c)) => {
+ let layer = doc.layer_at(&path);
+ if layer.kind() != Kind::Paint {
+ bail!(
+ "{cel} belongs to {} layer {}; strokes and fills live in paint cels",
+ layer.kind().name(),
+ layer.id
+ );
+ }
+ if let Some(source) = &layer.cels()[c].link {
+ bail!("cel {cel} links to {source}; its strokes are {source}:s<id>");
+ }
+ Ok(layer.id.clone())
+ }
+ Some(_) => bail!("{cel} is not a cel; strokes are addressed as <cel>:s<id>"),
+ None => bail!("no cel {cel}"),
+ }
+}
+
+fn paint_cel_at(doc: &mut Document, layer: &str, frame: u32, out: &mut Applied) -> Result<String> {
+ let path = layer_path(doc, layer)?;
+ let target = doc.layer_at(&path);
+ if target.kind() != Kind::Paint {
+ bail!(
+ "{layer} is a {} layer; strokes and fills go into paint layers",
+ target.kind().name()
+ );
+ }
+ if let Some(cel) = target.cel_at(frame).filter(|_| frame < doc.timeline.frames) {
+ if let Some(source) = &cel.link {
+ bail!(
+ "cel {} at frame {frame} links to {source}; paint into {source} instead",
+ cel.id
+ );
+ }
+ return Ok(cel.id.clone());
+ }
+ let id = doc.alloc_id('c');
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer has no cels"))?;
+ let index = cels.iter().position(|c| c.frame > frame).unwrap_or(cels.len());
+ cels.insert(index, Cel::at(&id, frame));
+ out.added.push(id.clone());
+ Ok(id)
+}
+
+pub fn apply_all(doc: &Document, ops: &[Op]) -> Result<(Document, Applied)> {
+ let mut next = doc.clone();
+ let mut applied = Applied::default();
+ ops.iter().enumerate().try_for_each(|(i, op)| {
+ apply(&mut next, op, &mut applied).with_context(|| format!("op {}", i + 1))?;
+ timing::grow(&mut next);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ next.validate()?;
+ Ok((next, applied))
+}
+
+pub fn parse_lines(text: &str) -> Result<Vec<Op>> {
+ text.lines()
+ .enumerate()
+ .filter(|(_, line)| !line.trim().is_empty() && !line.trim_start().starts_with("//"))
+ .map(|(n, line)| {
+ let value: Value = serde_json::from_str(line).with_context(|| format!("line {}", n + 1))?;
+ Op::parse(value).with_context(|| format!("line {}", n + 1))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::Paint;
+ use crate::stroke::{Author, Sample};
+ use serde_json::json;
+
+ fn ops(lines: &[Value]) -> Vec<Op> {
+ lines.iter().map(|v| Op::parse(v.clone()).unwrap()).collect()
+ }
+
+ fn base() -> Document {
+ let mut doc = Document::new(512, 512);
+ let (doc2, _) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"add","layer":{"kind":"vector","name":"shapes"}}),
+ json!({"op":"add","layer":{"kind":"paint","name":"ink"}}),
+ ]),
+ )
+ .unwrap();
+ doc = doc2;
+ doc
+ }
+
+ #[test]
+ fn layers_and_nodes_get_ids_and_land_where_asked() {
+ let doc = base();
+ let (doc, applied) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"add","node":{"type":"rect","x":0,"y":0,"w":10,"h":10,"fill":"#ff0000"},"in":"l1"}),
+ json!({"op":"add","node":{"type":"group","children":[{"type":"ellipse","cx":5,"cy":5,"rx":2,"ry":2}]},"in":"l1"}),
+ json!({"op":"add","layer":{"kind":"group","name":"fx"},"below":"l1"}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(applied.added.len(), 3);
+ assert_eq!(doc.layers[0].name, "fx");
+ let cel = &doc.layer("l1").unwrap().cels()[0];
+ assert_eq!(cel.nodes.len(), 2);
+ assert_eq!(cel.nodes[1].children().len(), 1);
+ assert!(doc.locate(&cel.nodes[1].children()[0].id).is_some());
+ }
+
+ #[test]
+ fn set_patches_nested_values_and_rejects_typos() {
+ let (doc, applied) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"add","node":{"id":"sun","type":"ellipse","cx":5,"cy":5,"rx":2,"ry":2},"in":"l1"}),
+ json!({"op":"set","id":"sun","fill":"#ffcc00","transform.rotate":15,"stroke.width":3}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(applied.changed, vec!["sun"]);
+ let Some(Item::Node(_, _, sun)) = doc.item("sun") else {
+ panic!()
+ };
+ assert_eq!(sun.fill, Some(Paint::Solid("#ffcc00".into())));
+ assert_eq!(sun.transform.rotate, 15.0);
+ assert_eq!(sun.stroke.as_ref().unwrap().width, 3.0);
+ let typo = apply_all(&doc, &ops(&[json!({"op":"set","id":"sun","fil":"#000000"})]));
+ assert!(format!("{:#}", typo.unwrap_err()).contains("has no \"fil\""));
+ let structural = apply_all(&doc, &ops(&[json!({"op":"set","id":"l1","cels":[]})]));
+ assert!(format!("{:#}", structural.unwrap_err()).contains("cannot be set"));
+ let (cleared, _) = apply_all(&doc, &ops(&[json!({"op":"set","id":"sun","stroke":null})])).unwrap();
+ let Some(Item::Node(_, _, sun)) = cleared.item("sun") else {
+ panic!()
+ };
+ assert!(sun.stroke.is_none());
+ }
+
+ #[test]
+ fn failed_batches_change_nothing() {
+ let doc = base();
+ let result = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"add","layer":{"kind":"paint"}}),
+ json!({"op":"set","id":"nope","name":"x"}),
+ ]),
+ );
+ assert!(format!("{:#}", result.unwrap_err()).contains("op 2"));
+ assert_eq!(doc.layers.len(), 2);
+ }
+
+ #[test]
+ fn removing_paint_layers_reports_their_cels() {
+ let doc = base();
+ let ink = doc.layer("l3").unwrap().cels()[0].id.clone();
+ let (doc, applied) = apply_all(&doc, &ops(&[json!({"op":"rm","id":"l3"})])).unwrap();
+ assert_eq!(applied.dropped_cels, vec![("l3".to_string(), ink)]);
+ assert_eq!(doc.layers.len(), 1);
+ }
+
+ #[test]
+ fn cels_add_link_and_guard_their_links() {
+ let doc = base();
+ let first = doc.layer("l3").unwrap().cels()[0].id.clone();
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"set","id": first, "hold": 2}),
+ json!({"op":"add","cel":{"frame":2,"link": first},"in":"l3"}),
+ ]),
+ )
+ .unwrap();
+ let layer = doc.layer("l3").unwrap();
+ assert_eq!(layer.cels().len(), 2);
+ assert_eq!(layer.content_at(3).unwrap().id, first);
+ let (handed, applied) = apply_all(&doc, &ops(&[json!({"op":"rm","id": first})])).unwrap();
+ let heir = &handed.layer("l3").unwrap().cels()[0];
+ assert_eq!((heir.frame, heir.link.as_deref()), (2, None));
+ assert!(matches!(&applied.marks[0].changes[0], MarkChange::Copy { cel, .. } if *cel == first));
+ assert_eq!(applied.dropped_cels, [("l3".to_string(), first.clone())]);
+ let overlap = apply_all(&doc, &ops(&[json!({"op":"set","id": first, "hold": 5})]));
+ assert!(format!("{:#}", overlap.unwrap_err()).contains("overlaps"));
+ }
+
+ #[test]
+ fn moves_reorder_layers_and_nodes() {
+ let (doc, _) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"add","node":{"id":"a","type":"path","d":"M0 0 L1 1"},"in":"l1"}),
+ json!({"op":"add","node":{"id":"b","type":"path","d":"M0 0 L1 1"},"in":"l1"}),
+ json!({"op":"add","layer":{"id":"g","kind":"group"}}),
+ json!({"op":"mv","id":"l1","in":"g"}),
+ json!({"op":"mv","id":"b","below":"a"}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(doc.locate("l1"), Some(Loc::Layer(vec![1, 0])));
+ let cel = &doc.layer("l1").unwrap().cels()[0];
+ assert_eq!(cel.nodes.iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), ["b", "a"]);
+ let into_self = apply_all(&doc, &ops(&[json!({"op":"mv","id":"g","in":"l1"})]));
+ assert!(into_self.is_err());
+ }
+
+ #[test]
+ fn nodes_need_a_vector_home() {
+ let mut doc = base();
+ let (past, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"add","node":{"type":"path","d":"M0 0 L2 2"},"in":"l1","frame":3})]),
+ )
+ .unwrap();
+ assert_eq!((past.layer("l1").unwrap().cels().len(), past.timeline.frames), (2, 4));
+ doc.timeline.frames = 8;
+ let paint = apply_all(
+ &doc,
+ &ops(&[json!({"op":"add","node":{"type":"path","d":"M0 0"},"in":"l3"})]),
+ );
+ assert!(format!("{:#}", paint.unwrap_err()).contains("vector layers"));
+ let nowhere = apply_all(&doc, &ops(&[json!({"op":"add","node":{"type":"path","d":"M0 0"}})]));
+ assert!(format!("{:#}", nowhere.unwrap_err()).contains("say where"));
+ let add_at_3 = json!({"op":"add","node":{"type":"path","d":"M0 0 L2 2"},"in":"l1","frame":3});
+ let (held, _) = apply_all(&doc, &ops(std::slice::from_ref(&add_at_3))).unwrap();
+ let cels = held.layer("l1").unwrap().cels();
+ assert_eq!((cels.len(), cels[0].nodes.len()), (1, 1));
+ let first = doc.layer("l1").unwrap().cels()[0].id.clone();
+ let (framed, _) = apply_all(&doc, &ops(&[json!({"op":"set","id": first,"hold":2}), add_at_3])).unwrap();
+ let cels = framed.layer("l1").unwrap().cels();
+ assert_eq!(cels.len(), 2);
+ assert_eq!((cels[1].frame, cels[1].nodes.len()), (3, 1));
+ }
+
+ #[test]
+ fn stroke_ops_build_agent_strokes_into_paint_cels() {
+ let doc = base();
+ let line = json!({"op":"stroke","layer":"l3","brush":"ink","color":"#112233","size":10,
+ "path":"M10 10 C 50 0 100 50 150 20 M 0 100 L 100 100","pressure":[0.2,1,0.1]});
+ let (_, applied) = apply_all(&doc, &ops(&[line])).unwrap();
+ let pending = &applied.marks[0];
+ assert_eq!(pending.layer, "l3");
+ let added: Vec<&Mark> = pending.added().collect();
+ assert_eq!(added.len(), 2);
+ let Mark::Stroke(first) = added[0] else { panic!() };
+ assert_eq!(first.author, Author::Agent);
+ assert!(first.samples.len() > 30);
+ let pressures: Vec<f32> = first.samples.iter().map(Sample::pressure).collect();
+ assert!(pressures[0] < 0.25 && pressures[pressures.len() / 2] > 0.8 && *pressures.last().unwrap() < 0.15);
+ let vector = apply_all(&doc, &ops(&[json!({"op":"stroke","layer":"l1","path":"M0 0 L1 1"})]));
+ assert!(format!("{:#}", vector.unwrap_err()).contains("paint layers"));
+ let tapered = apply_all(
+ &doc,
+ &ops(&[json!({"op":"stroke","layer":"l3","path":"M0 0 L90 0","taper":[12,30]})]),
+ )
+ .unwrap()
+ .1;
+ assert_eq!(
+ tapered.marks[0].added().next().unwrap().as_stroke().unwrap().taper,
+ [12.0, 30.0]
+ );
+ assert!(
+ apply_all(
+ &doc,
+ &ops(&[json!({"op":"stroke","layer":"l3","path":"M0 0 L9 0","taper":[-1,3]})])
+ )
+ .is_err()
+ );
+ let typo = Op::parse(json!({"op":"stroke","layer":"l3","path":"M0 0 L1 1","colour":"#fff"}));
+ assert!(typo.is_err());
+ let (framed, applied) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"set","id": doc.layer("l3").unwrap().cels()[0].id,"hold":1}),
+ json!({"op":"stroke","layer":"l3","frame":2,"points":[[1,1,1],[5,5,0.5]]}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(framed.layer("l3").unwrap().cels().len(), 2);
+ assert_eq!(
+ applied.marks[0]
+ .added()
+ .next()
+ .unwrap()
+ .as_stroke()
+ .unwrap()
+ .samples
+ .len(),
+ 2
+ );
+ }
+
+ #[test]
+ fn palette_ops_add_rename_remove_and_name_stroke_colours() {
+ let (doc, applied) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"palette","add":"#1b1b1b","name":"ink"}),
+ json!({"op":"palette","add":"#f0c8a0","name":"skin"}),
+ json!({"op":"palette","add":"#ffffff"}),
+ json!({"op":"palette","add":"#ffffff"}),
+ json!({"op":"palette","add":"#d0a080","name":"skin"}),
+ json!({"op":"palette","add":"#ff0000","index":0}),
+ json!({"op":"palette","rm":0}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(applied.changed, vec!["palette"]);
+ let colors: Vec<(&str, &str)> = doc
+ .palette
+ .iter()
+ .map(|s| (s.color.as_str(), s.name.as_str()))
+ .collect();
+ assert_eq!(colors, [("#1b1b1b", "ink"), ("#d0a080", "skin"), ("#ffffff", "")]);
+ let (_, applied) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"stroke","layer":"l3","path":"M0 0 L9 9","color":"skin"})]),
+ )
+ .unwrap();
+ let stroke = applied.marks[0].added().next().unwrap().as_stroke().unwrap();
+ assert_eq!(stroke.color, crate::color::to_u16(parse_hex("#d0a080").unwrap()));
+ let unknown = apply_all(
+ &doc,
+ &ops(&[json!({"op":"stroke","layer":"l3","path":"M0 0 L9 9","color":"teal"})]),
+ );
+ assert!(format!("{:#}", unknown.unwrap_err()).contains("ink, skin"));
+ let missing = apply_all(&doc, &ops(&[json!({"op":"palette","rm":"teal"})]));
+ assert!(format!("{:#}", missing.unwrap_err()).contains("teal"));
+ let (set, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"palette","set":[{"color":"#000000","name":"night"}]})]),
+ )
+ .unwrap();
+ assert_eq!(set.palette.len(), 1);
+ assert!(Op::parse(json!({"op":"palette","add":"#000000","colour":"x"})).is_err());
+ assert!(apply_all(&doc, &ops(&[json!({"op":"palette","add":"black"})])).is_err());
+ }
+
+ #[test]
+ fn fill_ops_need_coverage_and_resolve_their_reference() {
+ let doc = base();
+ let parsed = Op::parse(json!({"op":"fill","layer":"l3","at":[10,10],"ref":"shapes","gap":4})).unwrap();
+ let Op::Fill(mut spec) = parsed else { panic!() };
+ assert_eq!(spec.reference(&doc).unwrap(), FillRef::Layer("l1".into()));
+ let missing = apply_all(&doc, &[Op::Fill(spec.clone())]);
+ assert!(format!("{:#}", missing.unwrap_err()).contains("coverage"));
+ spec.coverage = Some(Coverage::from_mask(2, 2, &[255, 0, 0, 255]));
+ let (_, applied) = apply_all(&doc, &[Op::Fill(spec.clone())]).unwrap();
+ let Some(Mark::Fill(fill)) = applied.marks[0].added().next() else {
+ panic!()
+ };
+ assert_eq!(fill.author, Author::Agent);
+ assert_eq!(fill.reference(), Some(&FillRef::Layer("l1".into())));
+ let own = FillSpec {
+ reference: Some("l3".into()),
+ ..spec.clone()
+ };
+ assert_eq!(own.reference(&doc).unwrap(), FillRef::This);
+ let nowhere = FillSpec {
+ reference: Some("lines".into()),
+ ..spec.clone()
+ };
+ let err = nowhere.reference(&doc).unwrap_err().to_string();
+ assert!(err.contains("l1 (shapes)") && err.contains("this or all"), "{err}");
+ assert!(Op::parse(json!({"op":"fill","layer":"l3"})).is_err());
+ assert!(Op::parse(json!({"op":"fill","layer":"l3","at":[1,1],"gap":-1})).is_err());
+ assert!(Op::parse(json!({"op":"fill","layer":"l3","polygon":[[0,0],[5,5]]})).is_err());
+ let lasso =
+ Op::parse(json!({"op":"fill","layer":"l3","polygon":[[0,0],[5,0],[5,5]],"color":"#ff0000"})).unwrap();
+ let Op::Fill(lasso) = lasso else { panic!() };
+ assert!(matches!(lasso.source(&doc).unwrap(), FillSource::Polygon(p) if p.len() == 3));
+ }
+
+ #[test]
+ fn path_ops_reshape_paths_and_convert_shapes() {
+ let (doc, applied) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"add","node":{"id":"ridge","type":"path","d":"M0 100 L50 60 L100 100"},"in":"l1"}),
+ json!({"op":"add","node":{"id":"box","type":"rect","x":0,"y":0,"w":10,"h":10},"in":"l1"}),
+ json!({"op":"path","id":"ridge","move":1,"to":[50,40]}),
+ json!({"op":"path","id":"box"}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(applied.changed, ["ridge", "box"]);
+ let shape = |id: &str| match doc.item(id) {
+ Some(Item::Node(_, _, n)) => n.shape.clone(),
+ _ => panic!(),
+ };
+ assert_eq!(
+ shape("ridge"),
+ Shape::Path {
+ d: "M0 100 L50 40 L100 100".into()
+ }
+ );
+ assert_eq!(
+ shape("box"),
+ Shape::Path {
+ d: "M0 0 L10 0 L10 10 L0 10 Z".into()
+ }
+ );
+ assert!(Op::parse(json!({"op":"path","id":"ridge","to":[1,1]})).is_err());
+ let group = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"add","node":{"id":"g","type":"group","children":[]},"in":"l1"}),
+ json!({"op":"path","id":"g","corner":0}),
+ ]),
+ );
+ assert!(format!("{:#}", group.unwrap_err()).contains("groups have no points"));
+ }
+
+ #[test]
+ fn clip_ops_add_set_rename_and_remove_clips_in_frame_order() {
+ let mut doc = base();
+ doc.timeline.frames = 24;
+ let (doc, applied) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"clip","add":"run","from":12,"to":19,"loop":true,"fps":24}),
+ json!({"op":"clip","add":"idle","from":0,"to":5}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(applied.changed, vec!["timeline", "timeline"]);
+ let t = &doc.timeline;
+ assert_eq!(
+ t.clips.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
+ ["idle", "run"]
+ );
+ assert_eq!((t.fps_of(&t.clips[0]), t.fps_of(&t.clips[1])), (12, 24));
+ assert!(!t.clips[0].looping && t.clips[1].looping);
+ assert_eq!(t.clip_at(14).map(|c| c.name.as_str()), Some("run"));
+ assert_eq!(t.clip_at(8), None);
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"clip","set":"run","name":"sprint","from":1,"loop":false,"fps":null})]),
+ )
+ .unwrap();
+ let sprint = doc.timeline.clip("sprint").unwrap();
+ assert_eq!(
+ (sprint.from, sprint.to, sprint.looping, sprint.fps),
+ (1, 19, false, None)
+ );
+ assert_eq!(
+ doc.timeline.clips[1].name, "sprint",
+ "kept in order of their first frame"
+ );
+ let text = serde_json::to_string(&doc.timeline).unwrap();
+ assert!(text.contains(r#""name":"idle","from":0,"to":5,"loop":false"#), "{text}");
+ let (gone, _) = apply_all(&doc, &ops(&[json!({"op":"clip","rm":"idle"})])).unwrap();
+ assert_eq!(gone.timeline.clips.len(), 1);
+ let fails = |line: Value| format!("{:#}", apply_all(&doc, &ops(&[line])).unwrap_err());
+ assert!(fails(json!({"op":"clip","add":"idle","from":0,"to":1})).contains("already"));
+ assert!(fails(json!({"op":"clip","set":"walk","to":3})).contains("idle, sprint"));
+ assert!(fails(json!({"op":"clip","set":"idle","to":24})).contains("outside 0 to 23"));
+ assert!(fails(json!({"op":"clip","set":"idle","from":9})).contains("spans frames 9 to 5"));
+ assert!(fails(json!({"op":"clip","set":"idle","name":"sprint"})).contains("used twice"));
+ assert!(Op::parse(json!({"op":"clip","add":"x","from":0})).is_err());
+ assert!(Op::parse(json!({"op":"clip","add":"x","from":0,"to":1,"fps":0})).is_err());
+ assert!(Op::parse(json!({"op":"clip","add":"x","from":0,"to":1,"speed":2})).is_err());
+ }
+
+ #[test]
+ fn frame_ops_stretch_clips_and_a_shorter_timeline_trims_them() {
+ let mut doc = base();
+ doc.timeline.frames = 12;
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"clip","add":"a","from":0,"to":3,"loop":true}),
+ json!({"op":"clip","add":"b","from":4,"to":11}),
+ ]),
+ )
+ .unwrap();
+ let spans = |d: &Document| d.timeline.clips.iter().map(|c| (c.from, c.to)).collect::<Vec<_>>();
+ let (inserted, _) = apply_all(&doc, &ops(&[json!({"op":"frames","insert":3,"count":2})])).unwrap();
+ assert_eq!(spans(&inserted), [(0, 5), (6, 13)]);
+ let (removed, _) = apply_all(&doc, &ops(&[json!({"op":"frames","remove":2,"count":4})])).unwrap();
+ assert_eq!(spans(&removed), [(0, 1), (2, 7)]);
+ let (listed, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"frames","insert":3,"count":2,"layers":["ink"]})]),
+ )
+ .unwrap();
+ assert_eq!(spans(&listed), spans(&doc), "an insert on some layers leaves the clips");
+ let (short, _) = apply_all(&doc, &ops(&[json!({"op":"timeline","frames":8})])).unwrap();
+ assert_eq!(spans(&short), [(0, 3), (4, 7)]);
+ let refused = apply_all(&doc, &ops(&[json!({"op":"timeline","frames":4})]));
+ assert!(format!("{:#}", refused.unwrap_err()).contains("clip b starts at frame 4"));
+ }
+
+ #[test]
+ fn the_origin_and_the_godot_folder_are_document_settings() {
+ let (doc, _) = apply_all(
+ &base(),
+ &ops(&[
+ json!({"op":"timeline","origin":[256,480]}),
+ json!({"op":"export","godot":"../game/art/ball"}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(doc.timeline.origin, Some([256.0, 480.0]));
+ assert_eq!(doc.export.godot.as_deref(), Some("../game/art/ball"));
+ let text = serde_json::to_string(&doc).unwrap();
+ assert!(text.contains(r#""export":{"godot":"../game/art/ball"}"#), "{text}");
+ let back: Document = serde_json::from_str(&text).unwrap();
+ assert_eq!(back, doc);
+ let (cleared, _) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"timeline","origin":null}),
+ json!({"op":"export","godot":null}),
+ ]),
+ )
+ .unwrap();
+ assert_eq!((cleared.timeline.origin, cleared.export.godot), (None, None));
+ assert!(!serde_json::to_string(&base()).unwrap().contains("export"));
+ assert!(Op::parse(json!({"op":"export","unity":"x"})).is_err());
+ assert!(Op::parse(json!({"op":"timeline","origin":[1]})).is_err());
+ }
+
+ #[test]
+ fn json_lines_parse_with_comments_and_report_line_numbers() {
+ let parsed = parse_lines("// setup\n{\"op\":\"rm\",\"id\":\"x\"}\n\n{\"op\":\"mv\",\"id\":\"y\",\"top\":1}\n");
+ assert!(format!("{:#}", parsed.unwrap_err()).contains("line 4"));
+ assert_eq!(parse_lines("{\"op\":\"rm\",\"ids\":[\"a\",\"b\"]}").unwrap().len(), 1);
+ }
+}
diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rs
new file mode 100644
index 0000000..7932d13
--- /dev/null
+++ b/crates/core/src/patch.rs
@@ -0,0 +1,591 @@
+use crate::doc::{Cel, Document, Layer, LayerContent, Node};
+use anyhow::{Context, Result, anyhow, bail};
+use serde::de::DeserializeOwned;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value};
+
+const LIST_KEYS: &[&str] = &["layers", "cels", "children", "nodes", "rev"];
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Change {
+ pub at: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub index: Option<usize>,
+ pub old: Value,
+ pub new: Value,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct Patch(pub Vec<Change>);
+
+type Out = Vec<Change>;
+
+fn to_map<T: Serialize>(item: &T) -> Result<Map<String, Value>> {
+ match serde_json::to_value(item)? {
+ Value::Object(mut map) => {
+ LIST_KEYS.iter().for_each(|k| {
+ map.remove(*k);
+ });
+ Ok(map)
+ }
+ _ => bail!("expected an object"),
+ }
+}
+
+fn shell(out: &mut Out, at: &str, a: Map<String, Value>, b: Map<String, Value>) {
+ let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).collect();
+ let (old, new): (Map<String, Value>, Map<String, Value>) = keys
+ .into_iter()
+ .filter(|k| a.get(*k) != b.get(*k))
+ .map(|k| {
+ let pick = |m: &Map<String, Value>| m.get(k).cloned().unwrap_or(Value::Null);
+ ((k.clone(), pick(&a)), (k.clone(), pick(&b)))
+ })
+ .unzip();
+ if !old.is_empty() {
+ out.push(Change {
+ at: at.to_string(),
+ index: None,
+ old: Value::Object(old),
+ new: Value::Object(new),
+ });
+ }
+}
+
+fn list<T: PartialEq + Serialize>(
+ out: &mut Out,
+ at: &str,
+ a: &[T],
+ b: &[T],
+ same: fn(&T, &T) -> bool,
+ inner: fn(&mut Out, &str, &T, &T) -> Result<()>,
+) -> Result<()> {
+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
+ let room = a.len().min(b.len()) - prefix;
+ let suffix = a
+ .iter()
+ .rev()
+ .zip(b.iter().rev())
+ .take(room)
+ .take_while(|(x, y)| x == y)
+ .count();
+ let (ma, mb) = (&a[prefix..a.len() - suffix], &b[prefix..b.len() - suffix]);
+ if ma.is_empty() && mb.is_empty() {
+ return Ok(());
+ }
+ if ma.len() == mb.len() && ma.iter().zip(mb).all(|(x, y)| same(x, y)) {
+ return ma
+ .iter()
+ .zip(mb)
+ .enumerate()
+ .filter(|(_, (x, y))| x != y)
+ .try_for_each(|(i, (x, y))| inner(out, &format!("{at}/{}", prefix + i), x, y));
+ }
+ out.push(Change {
+ at: at.to_string(),
+ index: Some(prefix),
+ old: serde_json::to_value(ma)?,
+ new: serde_json::to_value(mb)?,
+ });
+ Ok(())
+}
+
+fn doc_shell(doc: &Document) -> Document {
+ Document {
+ format: doc.format.clone(),
+ rev: 0,
+ canvas: doc.canvas.clone(),
+ timeline: doc.timeline.clone(),
+ palette: doc.palette.clone(),
+ layers: Vec::new(),
+ export: doc.export.clone(),
+ atmosphere: doc.atmosphere.clone(),
+ next_id: doc.next_id,
+ }
+}
+
+fn layer_shell(layer: &Layer) -> Layer {
+ let content = match &layer.content {
+ LayerContent::Paint { .. } => LayerContent::Paint { cels: Vec::new() },
+ LayerContent::Vector { .. } => LayerContent::Vector { cels: Vec::new() },
+ LayerContent::Group { .. } => LayerContent::Group { children: Vec::new() },
+ LayerContent::Adjust { adjust } => LayerContent::Adjust { adjust: adjust.clone() },
+ };
+ Layer {
+ id: layer.id.clone(),
+ name: layer.name.clone(),
+ content,
+ opacity: layer.opacity,
+ blend: layer.blend,
+ visible: layer.visible,
+ locked: layer.locked,
+ clip: layer.clip,
+ lock_alpha: layer.lock_alpha,
+ mask: layer.mask.clone(),
+ effects: layer.effects.clone(),
+ depth: layer.depth,
+ reference: layer.reference,
+ }
+}
+
+fn cel_shell(cel: &Cel) -> Cel {
+ Cel {
+ id: cel.id.clone(),
+ frame: cel.frame,
+ hold: cel.hold,
+ link: cel.link.clone(),
+ tween: cel.tween.clone(),
+ nodes: Vec::new(),
+ parts: cel.parts.clone(),
+ }
+}
+
+fn node_shell(node: &Node) -> Node {
+ let mut shape = node.shape.clone();
+ if let Some(children) = shape.children_mut() {
+ children.clear();
+ }
+ Node {
+ id: node.id.clone(),
+ name: node.name.clone(),
+ shape,
+ fill: node.fill.clone(),
+ stroke: node.stroke.clone(),
+ transform: node.transform,
+ opacity: node.opacity,
+ blur: node.blur,
+ clip: node.clip.clone(),
+ visible: node.visible,
+ }
+}
+
+fn same_layer(a: &Layer, b: &Layer) -> bool {
+ a.id == b.id && a.kind() == b.kind()
+}
+
+fn same_cel(a: &Cel, b: &Cel) -> bool {
+ a.id == b.id
+}
+
+fn same_node(a: &Node, b: &Node) -> bool {
+ a.id == b.id && a.type_name() == b.type_name()
+}
+
+fn layer(out: &mut Out, at: &str, a: &Layer, b: &Layer) -> Result<()> {
+ shell(out, at, to_map(&layer_shell(a))?, to_map(&layer_shell(b))?);
+ match (&a.content, &b.content) {
+ (LayerContent::Group { children: x }, LayerContent::Group { children: y }) => {
+ list(out, &format!("{at}/children"), x, y, same_layer, layer)
+ }
+ (
+ LayerContent::Paint { cels: x } | LayerContent::Vector { cels: x },
+ LayerContent::Paint { cels: y } | LayerContent::Vector { cels: y },
+ ) => list(out, &format!("{at}/cels"), x, y, same_cel, cel),
+ (LayerContent::Adjust { .. }, LayerContent::Adjust { .. }) => Ok(()),
+ _ => bail!("layer {} changed kind", a.id),
+ }
+}
+
+fn cel(out: &mut Out, at: &str, a: &Cel, b: &Cel) -> Result<()> {
+ shell(out, at, to_map(&cel_shell(a))?, to_map(&cel_shell(b))?);
+ list(out, &format!("{at}/nodes"), &a.nodes, &b.nodes, same_node, node)
+}
+
+fn node(out: &mut Out, at: &str, a: &Node, b: &Node) -> Result<()> {
+ shell(out, at, to_map(&node_shell(a))?, to_map(&node_shell(b))?);
+ list(
+ out,
+ &format!("{at}/children"),
+ a.children(),
+ b.children(),
+ same_node,
+ node,
+ )
+}
+
+pub fn diff(from: &Document, to: &Document) -> Result<Patch> {
+ let mut out = Vec::new();
+ shell(&mut out, "", to_map(&doc_shell(from))?, to_map(&doc_shell(to))?);
+ list(&mut out, "/layers", &from.layers, &to.layers, same_layer, layer)?;
+ Ok(Patch(out))
+}
+
+enum Target<'a> {
+ Doc(&'a mut Document),
+ Layers(&'a mut Vec<Layer>),
+ Layer(&'a mut Layer),
+ Cels(&'a mut Vec<Cel>),
+ Cel(&'a mut Cel),
+ Nodes(&'a mut Vec<Node>),
+ Node(&'a mut Node),
+}
+
+fn nth<'a, T>(list: &'a mut [T], part: &str) -> Result<&'a mut T> {
+ let index: usize = part.parse().map_err(|_| anyhow!("{part:?} is not an index"))?;
+ let len = list.len();
+ list.get_mut(index)
+ .ok_or_else(|| anyhow!("index {index} is past the end ({len})"))
+}
+
+fn step<'a>(target: Target<'a>, part: &str) -> Result<Target<'a>> {
+ Ok(match (target, part) {
+ (Target::Doc(doc), "layers") => Target::Layers(&mut doc.layers),
+ (Target::Layers(list), part) => Target::Layer(nth(list, part)?),
+ (Target::Layer(layer), "cels") => match &mut layer.content {
+ LayerContent::Paint { cels } | LayerContent::Vector { cels } => Target::Cels(cels),
+ LayerContent::Group { .. } | LayerContent::Adjust { .. } => bail!("layer {} has no cels", layer.id),
+ },
+ (Target::Layer(layer), "children") => match &mut layer.content {
+ LayerContent::Group { children } => Target::Layers(children),
+ _ => bail!("layer {} is not a group", layer.id),
+ },
+ (Target::Cels(list), part) => Target::Cel(nth(list, part)?),
+ (Target::Cel(cel), "nodes") => Target::Nodes(&mut cel.nodes),
+ (Target::Nodes(list), part) => Target::Node(nth(list, part)?),
+ (Target::Node(node), "children") => match node.shape.children_mut() {
+ Some(children) => Target::Nodes(children),
+ None => bail!("node {} is not a group", node.id),
+ },
+ (_, part) => bail!("no {part:?} there"),
+ })
+}
+
+fn splice<T: PartialEq + DeserializeOwned>(list: &mut Vec<T>, index: usize, old: &Value, new: &Value) -> Result<()> {
+ let old: Vec<T> = serde_json::from_value(old.clone())?;
+ let new: Vec<T> = serde_json::from_value(new.clone())?;
+ let end = index + old.len();
+ if end > list.len() || list[index..end] != old[..] {
+ bail!("the items there are not the ones this change expects");
+ }
+ list.splice(index..end, new);
+ Ok(())
+}
+
+fn same(a: &Value, b: &Value) -> bool {
+ match (a, b) {
+ (Value::Number(x), Value::Number(y)) if x.is_f64() || y.is_f64() => {
+ x.as_f64().zip(y.as_f64()).is_some_and(|(x, y)| x as f32 == y as f32)
+ }
+ (Value::Object(x), Value::Object(y)) => {
+ x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same(v, w)))
+ }
+ (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(v, w)| same(v, w)),
+ _ => a == b,
+ }
+}
+
+fn merge<T: Serialize + DeserializeOwned>(item: &T, old: &Value, new: &Value) -> Result<T> {
+ let (Value::Object(old), Value::Object(new)) = (old, new) else {
+ bail!("an item change needs objects");
+ };
+ let Value::Object(mut map) = serde_json::to_value(item)? else {
+ bail!("expected an object");
+ };
+ old.iter().try_for_each(|(key, value)| {
+ if !same(map.get(key).unwrap_or(&Value::Null), value) {
+ bail!("{key} is not what this change expects");
+ }
+ Ok(())
+ })?;
+ new.iter().for_each(|(key, value)| match value {
+ Value::Null => {
+ map.remove(key);
+ }
+ v => {
+ map.insert(key.clone(), v.clone());
+ }
+ });
+ Ok(serde_json::from_value(Value::Object(map))?)
+}
+
+fn lists(content: &mut LayerContent) -> (Option<&mut Vec<Cel>>, Option<&mut Vec<Layer>>) {
+ match content {
+ LayerContent::Paint { cels } | LayerContent::Vector { cels } => (Some(cels), None),
+ LayerContent::Group { children } => (None, Some(children)),
+ LayerContent::Adjust { .. } => (None, None),
+ }
+}
+
+fn merge_layer(layer: &mut Layer, old: &Value, new: &Value) -> Result<()> {
+ let (cels, children) = lists(&mut layer.content);
+ let (cels, children) = (cels.map(std::mem::take), children.map(std::mem::take));
+ let mut merged: Layer = merge(&*layer, old, new)?;
+ match (lists(&mut merged.content), cels, children) {
+ ((Some(slot), _), Some(cels), _) => *slot = cels,
+ ((_, Some(slot)), _, Some(children)) => *slot = children,
+ ((None, None), None, None) => {}
+ _ => bail!("layer {} changed kind", layer.id),
+ }
+ *layer = merged;
+ Ok(())
+}
+
+fn merge_doc(doc: &mut Document, old: &Value, new: &Value) -> Result<()> {
+ let layers = std::mem::take(&mut doc.layers);
+ *doc = Document {
+ layers,
+ ..merge(&*doc, old, new)?
+ };
+ Ok(())
+}
+
+fn merge_cel(cel: &mut Cel, old: &Value, new: &Value) -> Result<()> {
+ let nodes = std::mem::take(&mut cel.nodes);
+ *cel = Cel {
+ nodes,
+ ..merge(&*cel, old, new)?
+ };
+ Ok(())
+}
+
+fn merge_node(node: &mut Node, old: &Value, new: &Value) -> Result<()> {
+ let children = node.shape.children_mut().map(std::mem::take).unwrap_or_default();
+ let mut merged: Node = merge(&*node, old, new)?;
+ if let Some(slot) = merged.shape.children_mut() {
+ *slot = children;
+ }
+ *node = merged;
+ Ok(())
+}
+
+fn apply_change(doc: &mut Document, change: &Change) -> Result<()> {
+ let target = change.at.split('/').skip(1).try_fold(Target::Doc(doc), step)?;
+ let (old, new) = (&change.old, &change.new);
+ match (target, change.index) {
+ (Target::Layers(list), Some(i)) => splice(list, i, old, new),
+ (Target::Cels(list), Some(i)) => splice(list, i, old, new),
+ (Target::Nodes(list), Some(i)) => splice(list, i, old, new),
+ (Target::Doc(doc), None) => merge_doc(doc, old, new),
+ (Target::Layer(layer), None) => merge_layer(layer, old, new),
+ (Target::Cel(cel), None) => merge_cel(cel, old, new),
+ (Target::Node(node), None) => merge_node(node, old, new),
+ _ => bail!("the change does not fit what is there"),
+ }
+}
+
+fn touched_cel(doc: &Document, at: &str) -> Option<String> {
+ let parts: Vec<&str> = at.split('/').skip(1).collect();
+ let mut layers: &[Layer] = &doc.layers;
+ let mut rest = &parts[..];
+ loop {
+ match rest {
+ ["layers" | "children", i, tail @ ..] => {
+ let layer = layers.get(i.parse::<usize>().ok()?)?;
+ match tail {
+ ["cels", c, "nodes", ..] => return Some(layer.cels().get(c.parse::<usize>().ok()?)?.id.clone()),
+ ["children", ..] => {
+ layers = layer.children();
+ rest = tail;
+ }
+ _ => return None,
+ }
+ }
+ _ => return None,
+ }
+ }
+}
+
+impl Patch {
+ pub fn touched_cels(&self, doc: &Document) -> Option<std::collections::BTreeSet<String>> {
+ self.0.iter().map(|c| touched_cel(doc, &c.at)).collect()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.0.is_empty()
+ }
+
+ pub fn reversed(&self) -> Self {
+ Self(
+ self.0
+ .iter()
+ .rev()
+ .map(|c| Change {
+ at: c.at.clone(),
+ index: c.index,
+ old: c.new.clone(),
+ new: c.old.clone(),
+ })
+ .collect(),
+ )
+ }
+
+ pub fn apply_in_place(&self, doc: &mut Document) -> Result<()> {
+ self.0.iter().try_for_each(|change| {
+ let at = if change.at.is_empty() {
+ "the document"
+ } else {
+ &change.at
+ };
+ apply_change(doc, change).with_context(|| format!("at {at}"))
+ })
+ }
+
+ pub fn applied(&self, doc: &Document) -> Result<Document> {
+ let mut next = doc.clone();
+ self.apply_in_place(&mut next)?;
+ next.validate()?;
+ Ok(next)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ops::{apply_all, parse_lines};
+
+ fn edited(doc: &Document, lines: &str) -> Document {
+ apply_all(doc, &parse_lines(lines).unwrap()).unwrap().0
+ }
+
+ fn sample() -> Document {
+ edited(
+ &Document::new(512, 512),
+ r##"{"op":"add","layer":{"id":"v","kind":"vector","name":"shapes"}}
+{"op":"add","layer":{"id":"g","kind":"group","name":"fx","children":[{"id":"p","kind":"paint","name":"ink"}]}}
+{"op":"add","node":{"id":"a","type":"rect","x":0,"y":0,"w":10,"h":10,"fill":"#ff0000"},"in":"v"}
+{"op":"add","node":{"id":"grp","type":"group","children":[{"id":"b","type":"ellipse","cx":5,"cy":5,"rx":2,"ry":2},{"id":"c","type":"path","d":"M0 0 L5 5"}]},"in":"v"}
+{"op":"add","node":{"id":"d","type":"rect","x":1,"y":1,"w":2,"h":2},"in":"v"}
+{"op":"palette","add":"#102030","name":"ink"}"##,
+ )
+ }
+
+ fn round_trip(before: &Document, after: &Document) -> Patch {
+ let forward = diff(before, after).unwrap();
+ let text = serde_json::to_string(&forward).unwrap();
+ let forward: Patch = serde_json::from_str(&text).unwrap();
+ let doc = forward.applied(before).unwrap();
+ assert_eq!(
+ &Document {
+ rev: after.rev,
+ ..doc.clone()
+ },
+ after
+ );
+ let doc = forward.reversed().applied(&doc).unwrap();
+ assert_eq!(&Document { rev: before.rev, ..doc }, before);
+ forward
+ }
+
+ #[test]
+ fn small_edits_make_small_patches_that_undo_and_redo() {
+ let doc = sample();
+ let cases = [
+ r#"{"op":"set","id":"c","d":"M0 0 L9 9","transform.rotate":15}"#,
+ r#"{"op":"set","id":"v","name":"renamed","opacity":0.5}"#,
+ r#"{"op":"set","id":"a","fill":null}"#,
+ r#"{"op":"rm","id":"b"}"#,
+ r#"{"op":"add","node":{"type":"rect","x":0,"y":0,"w":3,"h":3},"below":"d"}"#,
+ r#"{"op":"mv","id":"d","below":"a"}"#,
+ r#"{"op":"add","layer":{"kind":"paint","name":"new"},"in":"g"}"#,
+ r#"{"op":"mv","id":"p","above":"g"}"#,
+ r#"{"op":"set","id":"p","visible":false}"#,
+ r##"{"op":"palette","add":"#ffffff","name":"paper"}"##,
+ r#"{"op":"add","cel":{"frame":3},"in":"p"}"#,
+ ];
+ cases.iter().for_each(|line| {
+ let after = edited(&doc, line);
+ let patch = round_trip(&doc, &after);
+ assert!(!patch.is_empty(), "{line}");
+ let size = serde_json::to_string(&patch).unwrap().len();
+ assert!(size < 800, "{line}: {size} bytes");
+ });
+ assert!(diff(&doc, &doc).unwrap().is_empty());
+ }
+
+ #[test]
+ fn effects_and_adjustments_undo_and_redo() {
+ let doc = edited(
+ &sample(),
+ r#"{"op":"add","layer":{"id":"k","kind":"adjust","name":"dusk","adjust":{"curves":{}}}}"#,
+ );
+ [
+ r#"{"op":"set","id":"v","effects":[{"glow":{"radius":8}},{"outline":{"width":2}}]}"#,
+ r#"{"op":"set","id":"k","adjust":{"levels":{"black":0.1}},"opacity":0.6}"#,
+ r#"{"op":"set","id":"k","adjust":{"curves":{"points":[[0,0],[0.5,0.2],[1,1]]}}}"#,
+ r#"{"op":"set","id":"g","blend":"soft-light"}"#,
+ r#"{"op":"add","node":{"type":"rays","x":10,"y":0,"count":5},"in":"v"}"#,
+ r##"{"op":"atmosphere","color":"#a0b0c0","density":0.8}"##,
+ r#"{"op":"set","id":"g","depth":2.5,"reference":true}"#,
+ r##"{"op":"add","node":{"type":"scatter","w":100,"h":50,"count":9,"children":[{"type":"ellipse","cx":0,"cy":0,"rx":4,"ry":3,"fill":"#406020"}]},"in":"v"}"##,
+ r#"{"op":"add","node":{"type":"mirror","x":50,"children":[{"type":"path","d":"M10 10 L40 30"}]},"in":"v"}"#,
+ r#"{"op":"add","node":{"type":"text","text":"Inn","font":"sign.ttf","size":40},"in":"v"}"#,
+ r#"{"op":"add","node":{"type":"image","src":"ab12.png","w":64,"h":32},"in":"v"}"#,
+ ]
+ .iter()
+ .for_each(|line| {
+ let after = edited(&doc, line);
+ assert!(!round_trip(&doc, &after).is_empty(), "{line}");
+ });
+ }
+
+ #[test]
+ fn nested_changes_point_at_the_node() {
+ let doc = sample();
+ let after = edited(&doc, r#"{"op":"set","id":"c","d":"M1 1 L2 2"}"#);
+ let patch = diff(&doc, &after).unwrap();
+ assert_eq!(patch.0.len(), 1);
+ assert_eq!(patch.0[0].at, "/layers/0/cels/0/nodes/1/children/1");
+ assert_eq!(patch.0[0].new, serde_json::json!({"d": "M1 1 L2 2"}));
+ }
+
+ #[test]
+ fn patches_name_the_cels_whose_nodes_they_touch() {
+ let doc = sample();
+ let cels = |line: &str| diff(&doc, &edited(&doc, line)).unwrap().touched_cels(&doc);
+ let first = doc.layers[0].cels()[0].id.clone();
+ assert_eq!(
+ cels(r#"{"op":"set","id":"c","d":"M1 1 L2 2"}"#),
+ Some([first.clone()].into())
+ );
+ assert_eq!(cels(r#"{"op":"rm","id":"d"}"#), Some([first].into()));
+ assert_eq!(cels(r#"{"op":"set","id":"v","opacity":0.5}"#), None);
+ assert_eq!(cels(r#"{"op":"add","cel":{"frame":3},"in":"p"}"#), None);
+ }
+
+ #[test]
+ fn a_stored_patch_still_matches_after_its_numbers_go_through_text() {
+ let doc = sample();
+ let moved = edited(
+ &doc,
+ r#"{"op":"set","id":"d","transform.x":17.841812133789062,"transform.y":121.22406005859375,"transform.sx":0.6802818775177002,"transform.sy":0.6802818775177002}"#,
+ );
+ let scaled = edited(&moved, r#"{"op":"set","id":"d","transform.sx":1.9749854803085327}"#);
+ let restore = diff(&scaled, &moved).unwrap();
+ let text = serde_json::to_string(&restore).unwrap();
+ let stored: Patch = serde_json::from_str(&text).unwrap();
+ let reloaded: Document = serde_json::from_str(&serde_json::to_string(&scaled).unwrap()).unwrap();
+ assert_eq!(
+ stored.applied(&reloaded).unwrap(),
+ Document {
+ rev: reloaded.rev,
+ ..moved
+ }
+ );
+ assert!(same(
+ &serde_json::json!(121.22406005859375),
+ &serde_json::json!(121.22406005859376)
+ ));
+ assert!(!same(&serde_json::json!(121.2), &serde_json::json!(121.3)));
+ }
+
+ #[test]
+ fn patches_refuse_a_document_that_moved_on() {
+ let doc = sample();
+ let after = edited(&doc, r#"{"op":"set","id":"a","x":5}"#);
+ let patch = diff(&doc, &after).unwrap();
+ let other = edited(&doc, r#"{"op":"set","id":"a","x":7}"#);
+ let err = patch.applied(&other).unwrap_err();
+ assert!(format!("{err:#}").contains("not what this change expects"), "{err:#}");
+ let removed = edited(&doc, r#"{"op":"rm","id":"d"}"#);
+ let add_back = diff(&removed, &doc).unwrap();
+ assert!(add_back.applied(&doc).is_err());
+ assert_eq!(
+ add_back.applied(&removed).unwrap(),
+ Document {
+ rev: removed.rev,
+ ..doc
+ }
+ );
+ }
+}
diff --git a/crates/core/src/path.rs b/crates/core/src/path.rs
new file mode 100644
index 0000000..4ce8e6d
--- /dev/null
+++ b/crates/core/src/path.rs
@@ -0,0 +1,296 @@
+use anyhow::{Result, bail};
+
+type Point = [f32; 2];
+
+pub(crate) fn tokens(d: &str) -> Result<Vec<Token>> {
+ let mut out = Vec::new();
+ let chars: Vec<char> = d.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ let c = chars[i];
+ if c.is_ascii_alphabetic() && c != 'e' && c != 'E' {
+ out.push(Token::Command(c));
+ i += 1;
+ } else if c.is_ascii_digit() || c == '-' || c == '+' || c == '.' {
+ let start = i;
+ let mut seen_dot = false;
+ let mut seen_exp = false;
+ i += 1;
+ if c == '.' {
+ seen_dot = true;
+ }
+ while i < chars.len() {
+ let n = chars[i];
+ let after_exp = matches!(chars[i - 1], 'e' | 'E');
+ if n.is_ascii_digit() || ((n == '-' || n == '+') && after_exp) {
+ i += 1;
+ } else if n == '.' && !seen_dot && !seen_exp {
+ seen_dot = true;
+ i += 1;
+ } else if (n == 'e' || n == 'E') && !seen_exp {
+ seen_exp = true;
+ i += 1;
+ } else {
+ break;
+ }
+ }
+ let text: String = chars[start..i].iter().collect();
+ match text.parse::<f32>() {
+ Ok(v) => out.push(Token::Number(v)),
+ Err(_) => bail!("bad number {text:?} in path"),
+ }
+ } else if c.is_whitespace() || c == ',' {
+ i += 1;
+ } else {
+ bail!("unexpected {c:?} in path");
+ }
+ }
+ Ok(out)
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum Token {
+ Command(char),
+ Number(f32),
+}
+
+fn cubic(out: &mut Vec<Point>, p0: Point, c1: Point, c2: Point, p3: Point) {
+ let hull = dist(p0, c1) + dist(c1, c2) + dist(c2, p3);
+ let n = (hull / 3.0).ceil().clamp(2.0, 200.0) as usize;
+ (1..=n).for_each(|i| {
+ let t = i as f32 / n as f32;
+ let u = 1.0 - t;
+ let (a, b, c, e) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
+ out.push([
+ a * p0[0] + b * c1[0] + c * c2[0] + e * p3[0],
+ a * p0[1] + b * c1[1] + c * c2[1] + e * p3[1],
+ ]);
+ });
+}
+
+fn quad(out: &mut Vec<Point>, p0: Point, c: Point, p2: Point) {
+ let c1 = [p0[0] + (c[0] - p0[0]) * 2.0 / 3.0, p0[1] + (c[1] - p0[1]) * 2.0 / 3.0];
+ let c2 = [p2[0] + (c[0] - p2[0]) * 2.0 / 3.0, p2[1] + (c[1] - p2[1]) * 2.0 / 3.0];
+ cubic(out, p0, c1, c2, p2);
+}
+
+fn dist(a: Point, b: Point) -> f32 {
+ libm::sqrtf((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2))
+}
+
+pub fn flatten(d: &str) -> Result<Vec<Vec<Point>>> {
+ let tokens = tokens(d)?;
+ let mut paths: Vec<Vec<Point>> = Vec::new();
+ let mut current: Vec<Point> = Vec::new();
+ let mut pos: Point = [0.0, 0.0];
+ let mut start: Point = [0.0, 0.0];
+ let mut last_control: Option<Point> = None;
+ let mut command = ' ';
+ let mut i = 0;
+ let take = |i: &mut usize, n: usize| -> Result<Vec<f32>> {
+ let values: Vec<f32> = tokens
+ .get(*i..*i + n)
+ .unwrap_or(&[])
+ .iter()
+ .map_while(|t| match t {
+ Token::Number(v) => Some(*v),
+ Token::Command(_) => None,
+ })
+ .collect();
+ if values.len() != n {
+ bail!("path command needs {n} numbers");
+ }
+ *i += n;
+ Ok(values)
+ };
+ while i < tokens.len() {
+ if let Token::Command(c) = tokens[i] {
+ command = c;
+ i += 1;
+ if matches!(c, 'Z' | 'z') {
+ if !current.is_empty() {
+ current.push(start);
+ paths.push(std::mem::take(&mut current));
+ }
+ pos = start;
+ last_control = None;
+ continue;
+ }
+ }
+ if command == ' ' {
+ bail!("path must start with a command");
+ }
+ if !matches!(command, 'M' | 'm') && current.is_empty() {
+ bail!("path must start with M");
+ }
+ let rel = command.is_ascii_lowercase();
+ let at = |p: Point, v: f32, w: f32| if rel { [p[0] + v, p[1] + w] } else { [v, w] };
+ match command.to_ascii_uppercase() {
+ 'M' => {
+ let v = take(&mut i, 2)?;
+ if current.len() > 1 {
+ paths.push(std::mem::take(&mut current));
+ }
+ current.clear();
+ pos = at(pos, v[0], v[1]);
+ start = pos;
+ current.push(pos);
+ command = if rel { 'l' } else { 'L' };
+ last_control = None;
+ }
+ 'L' => {
+ let v = take(&mut i, 2)?;
+ pos = at(pos, v[0], v[1]);
+ current.push(pos);
+ last_control = None;
+ }
+ 'H' => {
+ let v = take(&mut i, 1)?;
+ pos = [if rel { pos[0] + v[0] } else { v[0] }, pos[1]];
+ current.push(pos);
+ last_control = None;
+ }
+ 'V' => {
+ let v = take(&mut i, 1)?;
+ pos = [pos[0], if rel { pos[1] + v[0] } else { v[0] }];
+ current.push(pos);
+ last_control = None;
+ }
+ 'C' => {
+ let v = take(&mut i, 6)?;
+ let (c1, c2, end) = (at(pos, v[0], v[1]), at(pos, v[2], v[3]), at(pos, v[4], v[5]));
+ cubic(&mut current, pos, c1, c2, end);
+ last_control = Some(c2);
+ pos = end;
+ }
+ 'S' => {
+ let v = take(&mut i, 4)?;
+ let c1 = last_control.map_or(pos, |c| [2.0 * pos[0] - c[0], 2.0 * pos[1] - c[1]]);
+ let (c2, end) = (at(pos, v[0], v[1]), at(pos, v[2], v[3]));
+ cubic(&mut current, pos, c1, c2, end);
+ last_control = Some(c2);
+ pos = end;
+ }
+ 'Q' => {
+ let v = take(&mut i, 4)?;
+ let (c, end) = (at(pos, v[0], v[1]), at(pos, v[2], v[3]));
+ quad(&mut current, pos, c, end);
+ last_control = Some(c);
+ pos = end;
+ }
+ 'T' => {
+ let v = take(&mut i, 2)?;
+ let c = last_control.map_or(pos, |c| [2.0 * pos[0] - c[0], 2.0 * pos[1] - c[1]]);
+ let end = at(pos, v[0], v[1]);
+ quad(&mut current, pos, c, end);
+ last_control = Some(c);
+ pos = end;
+ }
+ 'A' => bail!("arcs are not supported in stroke paths; use C curves"),
+ other => bail!("unknown path command {other:?}"),
+ }
+ }
+ if !current.is_empty() {
+ paths.push(current);
+ }
+ Ok(paths)
+}
+
+pub fn length(points: &[Point]) -> f32 {
+ points.windows(2).map(|w| dist(w[0], w[1])).sum()
+}
+
+pub fn resample(points: &[Point], step: f32) -> Vec<Point> {
+ let Some(&first) = points.first() else {
+ return Vec::new();
+ };
+ let mut out = vec![first];
+ let mut carry = 0.0f32;
+ points.windows(2).for_each(|w| {
+ let (a, b) = (w[0], w[1]);
+ let seg = dist(a, b);
+ let mut t = step - carry;
+ while t <= seg {
+ let k = t / seg;
+ out.push([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]);
+ t += step;
+ }
+ carry = seg - (t - step);
+ });
+ let last = *points.last().unwrap_or(&first);
+ if out.last().is_none_or(|p| dist(*p, last) > step * 0.25) {
+ out.push(last);
+ }
+ out
+}
+
+pub fn profile(values: &[f32], t: f32) -> f32 {
+ match values {
+ [] => 1.0,
+ [v] => *v,
+ _ => {
+ let x = t.clamp(0.0, 1.0) * (values.len() - 1) as f32;
+ let i = (x as usize).min(values.len() - 2);
+ values[i] + (values[i + 1] - values[i]) * (x - i as f32)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn near(a: Point, b: Point) -> bool {
+ dist(a, b) < 0.01
+ }
+
+ #[test]
+ fn lines_relative_and_closed_paths_flatten() {
+ let paths = flatten("M10 10 L20 10 l0 10 H5 v-5 Z m 100 0 h10").unwrap();
+ assert_eq!(paths.len(), 2);
+ let first = &paths[0];
+ assert!(near(first[1], [20.0, 10.0]));
+ assert!(near(first[2], [20.0, 20.0]));
+ assert!(near(first[3], [5.0, 20.0]));
+ assert!(near(first[4], [5.0, 15.0]));
+ assert!(near(*first.last().unwrap(), [10.0, 10.0]));
+ assert!(near(paths[1][0], [110.0, 10.0]));
+ assert!(near(paths[1][1], [120.0, 10.0]));
+ }
+
+ #[test]
+ fn curves_pass_through_their_ends() {
+ let paths = flatten("M0 0 C 0 100 100 100 100 0 S 200 -100 200 0 Q 250 50 300 0 T 400 0").unwrap();
+ let line = &paths[0];
+ assert!(near(*line.last().unwrap(), [400.0, 0.0]));
+ assert!(line.iter().any(|p| near(*p, [100.0, 0.0])));
+ assert!(line.iter().any(|p| p[1] > 70.0));
+ assert!(line.iter().any(|p| p[1] < -70.0));
+ }
+
+ #[test]
+ fn compact_numbers_and_errors() {
+ let paths = flatten("M1.5.5L-2-3e1").unwrap();
+ assert!(near(paths[0][0], [1.5, 0.5]));
+ assert!(near(paths[0][1], [-2.0, -30.0]));
+ assert!(flatten("L1 2").is_err());
+ assert!(flatten("M0 0 A 5 5 0 0 1 10 10").is_err());
+ assert!(flatten("M0 0 L5").is_err());
+ }
+
+ #[test]
+ fn resampling_spaces_points_evenly() {
+ let points = resample(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], 2.5);
+ assert_eq!(points.len(), 9);
+ assert!(points.windows(2).all(|w| (dist(w[0], w[1]) - 2.5).abs() < 0.01));
+ assert!((length(&points) - 20.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn profiles_interpolate() {
+ assert_eq!(profile(&[], 0.3), 1.0);
+ assert_eq!(profile(&[0.4], 0.9), 0.4);
+ assert!((profile(&[0.2, 1.0, 0.0], 0.25) - 0.6).abs() < 1e-6);
+ assert_eq!(profile(&[0.2, 1.0, 0.0], 1.0), 0.0);
+ }
+}
diff --git a/crates/core/src/pathedit.rs b/crates/core/src/pathedit.rs
new file mode 100644
index 0000000..ccfae3b
--- /dev/null
+++ b/crates/core/src/pathedit.rs
@@ -0,0 +1,1166 @@
+use crate::doc::Shape;
+use crate::path::{Token, resample, tokens};
+use anyhow::{Result, anyhow, bail};
+use serde_json::{Map, Value};
+use std::f32::consts::PI;
+
+pub type P = [f32; 2];
+
+const KAPPA: f32 = 0.552_284_8;
+const NEAR: f32 = 1e-3;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Anchor {
+ pub at: P,
+ pub inn: P,
+ pub out: P,
+}
+
+impl Anchor {
+ pub fn corner(at: P) -> Self {
+ Self { at, inn: at, out: at }
+ }
+
+ pub fn has_in(&self) -> bool {
+ dist(self.inn, self.at) > NEAR
+ }
+
+ pub fn has_out(&self) -> bool {
+ dist(self.out, self.at) > NEAR
+ }
+
+ pub fn smooth(&self) -> bool {
+ if !self.has_in() || !self.has_out() {
+ return false;
+ }
+ let (a, b) = (sub(self.inn, self.at), sub(self.out, self.at));
+ let cross = a[0] * b[1] - a[1] * b[0];
+ let dot = a[0] * b[0] + a[1] * b[1];
+ dot < 0.0 && cross.abs() <= 0.02 * len(a) * len(b)
+ }
+
+ fn shift(&mut self, by: P) {
+ self.at = add(self.at, by);
+ self.inn = add(self.inn, by);
+ self.out = add(self.out, by);
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Subpath {
+ pub anchors: Vec<Anchor>,
+ pub closed: bool,
+}
+
+fn add(a: P, b: P) -> P {
+ [a[0] + b[0], a[1] + b[1]]
+}
+
+fn sub(a: P, b: P) -> P {
+ [a[0] - b[0], a[1] - b[1]]
+}
+
+fn mul(a: P, k: f32) -> P {
+ [a[0] * k, a[1] * k]
+}
+
+fn len(a: P) -> f32 {
+ libm::sqrtf(a[0] * a[0] + a[1] * a[1])
+}
+
+fn dist(a: P, b: P) -> f32 {
+ len(sub(a, b))
+}
+
+fn unit(a: P) -> P {
+ let l = len(a);
+ if l < 1e-9 { [0.0, 0.0] } else { mul(a, 1.0 / l) }
+}
+
+fn lerp(a: P, b: P, t: f32) -> P {
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
+}
+
+fn cubic_at(p: [P; 4], t: f32) -> P {
+ let u = 1.0 - t;
+ let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
+ [
+ a * p[0][0] + b * p[1][0] + c * p[2][0] + d * p[3][0],
+ a * p[0][1] + b * p[1][1] + c * p[2][1] + d * p[3][1],
+ ]
+}
+
+pub fn point_on(p: [P; 4], t: f32) -> P {
+ if dist(p[1], p[0]) <= NEAR && dist(p[2], p[3]) <= NEAR {
+ lerp(p[0], p[3], t)
+ } else {
+ cubic_at(p, t)
+ }
+}
+
+struct Builder {
+ subs: Vec<Subpath>,
+ current: Option<Subpath>,
+}
+
+impl Builder {
+ fn start(&mut self, at: P) {
+ self.finish();
+ self.current = Some(Subpath {
+ anchors: vec![Anchor::corner(at)],
+ closed: false,
+ });
+ }
+
+ fn last(&mut self) -> Result<&mut Subpath> {
+ self.current.as_mut().ok_or_else(|| anyhow!("path must start with M"))
+ }
+
+ fn line(&mut self, to: P) -> Result<()> {
+ self.last()?.anchors.push(Anchor::corner(to));
+ Ok(())
+ }
+
+ fn cubic(&mut self, c1: P, c2: P, to: P) -> Result<()> {
+ let sub = self.last()?;
+ if let Some(prev) = sub.anchors.last_mut() {
+ prev.out = c1;
+ }
+ sub.anchors.push(Anchor {
+ at: to,
+ inn: c2,
+ out: to,
+ });
+ Ok(())
+ }
+
+ fn close(&mut self) {
+ if let Some(mut path) = self.current.take() {
+ let n = path.anchors.len();
+ if n > 1 && dist(path.anchors[n - 1].at, path.anchors[0].at) <= NEAR {
+ let last = path.anchors.pop().expect("two anchors");
+ path.anchors[0].inn = add(path.anchors[0].at, sub(last.inn, last.at));
+ }
+ path.closed = true;
+ self.subs.push(path);
+ }
+ }
+
+ fn finish(&mut self) {
+ if let Some(sub) = self.current.take() {
+ self.subs.push(sub);
+ }
+ }
+}
+
+fn angle(u: P, v: P) -> f32 {
+ libm::atan2f(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1])
+}
+
+#[allow(clippy::too_many_arguments)]
+fn arc(b: &mut Builder, from: P, r: P, rotation: f32, large: bool, sweep: bool, to: P) -> Result<()> {
+ let (mut rx, mut ry) = (r[0].abs(), r[1].abs());
+ if dist(from, to) < 1e-6 {
+ return Ok(());
+ }
+ if rx < 1e-6 || ry < 1e-6 {
+ return b.line(to);
+ }
+ let phi = rotation.to_radians();
+ let (s, c) = (libm::sinf(phi), libm::cosf(phi));
+ let (dx, dy) = ((from[0] - to[0]) / 2.0, (from[1] - to[1]) / 2.0);
+ let (x1, y1) = (c * dx + s * dy, -s * dx + c * dy);
+ let lambda = x1 * x1 / (rx * rx) + y1 * y1 / (ry * ry);
+ if lambda > 1.0 {
+ rx *= libm::sqrtf(lambda);
+ ry *= libm::sqrtf(lambda);
+ }
+ let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
+ let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
+ let sign = if large == sweep { -1.0 } else { 1.0 };
+ let coef = sign * libm::sqrtf((num / den).max(0.0));
+ let (cxp, cyp) = (coef * rx * y1 / ry, -coef * ry * x1 / rx);
+ let (cx, cy) = (
+ c * cxp - s * cyp + (from[0] + to[0]) / 2.0,
+ s * cxp + c * cyp + (from[1] + to[1]) / 2.0,
+ );
+ let start = [(x1 - cxp) / rx, (y1 - cyp) / ry];
+ let end = [(-x1 - cxp) / rx, (-y1 - cyp) / ry];
+ let theta = angle([1.0, 0.0], start);
+ let mut delta = angle(start, end);
+ if !sweep && delta > 0.0 {
+ delta -= 2.0 * PI;
+ } else if sweep && delta < 0.0 {
+ delta += 2.0 * PI;
+ }
+ let pieces = (delta.abs() / (PI / 2.0)).ceil().max(1.0) as usize;
+ let step = delta / pieces as f32;
+ let k = 4.0 / 3.0 * libm::tanf(step / 4.0);
+ let point = |t: f32| {
+ let (st, ct) = (libm::sinf(t), libm::cosf(t));
+ [cx + rx * ct * c - ry * st * s, cy + rx * ct * s + ry * st * c]
+ };
+ let slope = |t: f32| {
+ let (st, ct) = (libm::sinf(t), libm::cosf(t));
+ [-rx * st * c - ry * ct * s, -rx * st * s + ry * ct * c]
+ };
+ (0..pieces).try_for_each(|i| {
+ let (t1, t2) = (theta + step * i as f32, theta + step * (i + 1) as f32);
+ let end = if i + 1 == pieces { to } else { point(t2) };
+ b.cubic(add(point(t1), mul(slope(t1), k)), sub(end, mul(slope(t2), k)), end)
+ })
+}
+
+pub fn parse(d: &str) -> Result<Vec<Subpath>> {
+ let tokens = tokens(d)?;
+ let mut b = Builder {
+ subs: Vec::new(),
+ current: None,
+ };
+ let (mut pos, mut start): (P, P) = ([0.0, 0.0], [0.0, 0.0]);
+ let (mut last_cubic, mut last_quad): (Option<P>, Option<P>) = (None, None);
+ let mut command = ' ';
+ let mut i = 0;
+ let take = |i: &mut usize, n: usize| -> Result<Vec<f32>> {
+ let values: Vec<f32> = tokens
+ .get(*i..*i + n)
+ .unwrap_or(&[])
+ .iter()
+ .map_while(|t| match t {
+ Token::Number(v) => Some(*v),
+ Token::Command(_) => None,
+ })
+ .collect();
+ if values.len() != n {
+ bail!("a path command needs {n} numbers there");
+ }
+ *i += n;
+ Ok(values)
+ };
+ while i < tokens.len() {
+ if let Token::Command(c) = tokens[i] {
+ command = c;
+ i += 1;
+ if matches!(c, 'Z' | 'z') {
+ b.close();
+ pos = start;
+ last_cubic = None;
+ last_quad = None;
+ continue;
+ }
+ }
+ if command == ' ' {
+ bail!("path must start with a command");
+ }
+ let upper = command.to_ascii_uppercase();
+ if upper != 'M' && b.current.is_none() {
+ b.start(pos);
+ }
+ let rel = command.is_ascii_lowercase();
+ let at = |p: P, x: f32, y: f32| if rel { [p[0] + x, p[1] + y] } else { [x, y] };
+ let (mut cubic_control, mut quad_control) = (None, None);
+ match upper {
+ 'M' => {
+ let v = take(&mut i, 2)?;
+ pos = at(pos, v[0], v[1]);
+ start = pos;
+ b.start(pos);
+ command = if rel { 'l' } else { 'L' };
+ }
+ 'L' => {
+ let v = take(&mut i, 2)?;
+ pos = at(pos, v[0], v[1]);
+ b.line(pos)?;
+ }
+ 'H' => {
+ let v = take(&mut i, 1)?;
+ pos = [if rel { pos[0] + v[0] } else { v[0] }, pos[1]];
+ b.line(pos)?;
+ }
+ 'V' => {
+ let v = take(&mut i, 1)?;
+ pos = [pos[0], if rel { pos[1] + v[0] } else { v[0] }];
+ b.line(pos)?;
+ }
+ 'C' | 'S' => {
+ let (c1, rest) = if upper == 'C' {
+ let v = take(&mut i, 6)?;
+ (at(pos, v[0], v[1]), v[2..].to_vec())
+ } else {
+ let v = take(&mut i, 4)?;
+ (last_cubic.map_or(pos, |c| sub(mul(pos, 2.0), c)), v)
+ };
+ let (c2, end) = (at(pos, rest[0], rest[1]), at(pos, rest[2], rest[3]));
+ b.cubic(c1, c2, end)?;
+ cubic_control = Some(c2);
+ pos = end;
+ }
+ 'Q' | 'T' => {
+ let (q, end) = if upper == 'Q' {
+ let v = take(&mut i, 4)?;
+ (at(pos, v[0], v[1]), at(pos, v[2], v[3]))
+ } else {
+ let v = take(&mut i, 2)?;
+ (last_quad.map_or(pos, |c| sub(mul(pos, 2.0), c)), at(pos, v[0], v[1]))
+ };
+ b.cubic(lerp(pos, q, 2.0 / 3.0), lerp(end, q, 2.0 / 3.0), end)?;
+ quad_control = Some(q);
+ pos = end;
+ }
+ 'A' => {
+ let v = take(&mut i, 7)?;
+ let end = at(pos, v[5], v[6]);
+ arc(&mut b, pos, [v[0], v[1]], v[2], v[3] != 0.0, v[4] != 0.0, end)?;
+ pos = end;
+ }
+ other => bail!("unknown path command {other:?}"),
+ }
+ last_cubic = cubic_control;
+ last_quad = quad_control;
+ }
+ b.finish();
+ if b.subs.iter().all(|s| s.anchors.len() < 2) {
+ bail!("the path has no segments");
+ }
+ Ok(b.subs)
+}
+
+fn num(v: f32) -> String {
+ let text = format!("{:.2}", v);
+ let text = text.trim_end_matches('0').trim_end_matches('.');
+ match text {
+ "-0" | "" => "0".into(),
+ t => t.into(),
+ }
+}
+
+fn segment(out: &mut String, a: &Anchor, b: &Anchor) {
+ if !a.has_out() && !b.has_in() {
+ out.push_str(&format!(" L{} {}", num(b.at[0]), num(b.at[1])));
+ } else {
+ out.push_str(&format!(
+ " C{} {} {} {} {} {}",
+ num(a.out[0]),
+ num(a.out[1]),
+ num(b.inn[0]),
+ num(b.inn[1]),
+ num(b.at[0]),
+ num(b.at[1])
+ ));
+ }
+}
+
+pub fn to_d(subs: &[Subpath]) -> String {
+ let mut out = String::new();
+ subs.iter().filter(|s| !s.anchors.is_empty()).for_each(|s| {
+ let first = &s.anchors[0];
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.push_str(&format!("M{} {}", num(first.at[0]), num(first.at[1])));
+ s.anchors.windows(2).for_each(|w| segment(&mut out, &w[0], &w[1]));
+ if s.closed {
+ let last = &s.anchors[s.anchors.len() - 1];
+ if last.has_out() || first.has_in() {
+ segment(&mut out, last, first);
+ }
+ out.push_str(" Z");
+ }
+ });
+ out
+}
+
+fn rect(x: f32, y: f32, w: f32, h: f32, radius: f32) -> Subpath {
+ let r = radius.min(w / 2.0).min(h / 2.0).max(0.0);
+ if r <= 0.0 {
+ return Subpath {
+ anchors: [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]
+ .into_iter()
+ .map(Anchor::corner)
+ .collect(),
+ closed: true,
+ };
+ }
+ let k = r * KAPPA;
+ let round = |at: P, inn: P, out: P| Anchor {
+ at,
+ inn: add(at, inn),
+ out: add(at, out),
+ };
+ let (x1, y1) = (x + w, y + h);
+ Subpath {
+ anchors: vec![
+ round([x + r, y], [-k, 0.0], [0.0, 0.0]),
+ round([x1 - r, y], [0.0, 0.0], [k, 0.0]),
+ round([x1, y + r], [0.0, -k], [0.0, 0.0]),
+ round([x1, y1 - r], [0.0, 0.0], [0.0, k]),
+ round([x1 - r, y1], [k, 0.0], [0.0, 0.0]),
+ round([x + r, y1], [0.0, 0.0], [-k, 0.0]),
+ round([x, y1 - r], [0.0, k], [0.0, 0.0]),
+ round([x, y + r], [0.0, 0.0], [0.0, -k]),
+ ],
+ closed: true,
+ }
+}
+
+fn ellipse(cx: f32, cy: f32, rx: f32, ry: f32) -> Subpath {
+ let (kx, ky) = (rx * KAPPA, ry * KAPPA);
+ let anchor = |at: P, inn: P| Anchor {
+ at,
+ inn: add(at, inn),
+ out: sub(at, inn),
+ };
+ Subpath {
+ anchors: vec![
+ anchor([cx + rx, cy], [0.0, -ky]),
+ anchor([cx, cy + ry], [kx, 0.0]),
+ anchor([cx - rx, cy], [0.0, ky]),
+ anchor([cx, cy - ry], [-kx, 0.0]),
+ ],
+ closed: true,
+ }
+}
+
+pub fn from_shape(shape: &Shape) -> Result<Vec<Subpath>> {
+ Ok(match shape {
+ Shape::Path { d } => parse(d)?,
+ Shape::Rect { x, y, w, h, radius } => vec![rect(*x, *y, *w, *h, *radius)],
+ Shape::Ellipse { cx, cy, rx, ry } => vec![ellipse(*cx, *cy, *rx, *ry)],
+ Shape::Group { .. } => bail!("groups have no points; edit the paths inside"),
+ Shape::Rays(_) => bail!("rays have no points; set their origin, angle, spread and length"),
+ Shape::Image(_) => bail!("a picture has no points; V moves and scales it"),
+ Shape::Text(_) => bail!("text has no points; change it in the inspector"),
+ Shape::Scatter(_) | Shape::Repeat(_) | Shape::Mirror(_) => {
+ bail!("a generator has no points; edit the shapes inside it")
+ }
+ })
+}
+
+pub fn locate(subs: &[Subpath], index: usize) -> Result<(usize, usize)> {
+ let mut left = index;
+ subs.iter()
+ .enumerate()
+ .find_map(|(s, sub)| {
+ if left < sub.anchors.len() {
+ Some((s, left))
+ } else {
+ left -= sub.anchors.len();
+ None
+ }
+ })
+ .ok_or_else(|| {
+ let total: usize = subs.iter().map(|s| s.anchors.len()).sum();
+ anyhow!(
+ "point {index} does not exist; the path has points 0 to {}",
+ total.saturating_sub(1)
+ )
+ })
+}
+
+pub fn anchors(subs: &[Subpath]) -> Vec<(usize, Anchor)> {
+ subs.iter()
+ .enumerate()
+ .flat_map(|(s, sub)| sub.anchors.iter().map(move |a| (s, *a)))
+ .collect()
+}
+
+fn neighbours(sub: &Subpath, i: usize) -> (Option<usize>, Option<usize>) {
+ let n = sub.anchors.len();
+ let prev = if i > 0 {
+ Some(i - 1)
+ } else {
+ (sub.closed && n > 2).then_some(n - 1)
+ };
+ let next = if i + 1 < n {
+ Some(i + 1)
+ } else {
+ (sub.closed && n > 2).then_some(0)
+ };
+ (prev, next)
+}
+
+pub fn segment_points(sub: &Subpath, i: usize) -> Option<[P; 4]> {
+ let (_, next) = neighbours(sub, i);
+ let (a, b) = (sub.anchors[i], sub.anchors[next?]);
+ Some([a.at, a.out, b.inn, b.at])
+}
+
+pub fn flatten(subs: &[Subpath], step: f32) -> Vec<Vec<P>> {
+ subs.iter()
+ .map(|sub| {
+ let count = if sub.closed {
+ sub.anchors.len()
+ } else {
+ sub.anchors.len().saturating_sub(1)
+ };
+ let mut points = vec![sub.anchors[0].at];
+ (0..count).filter_map(|i| segment_points(sub, i)).for_each(|p| {
+ let hull = dist(p[0], p[1]) + dist(p[1], p[2]) + dist(p[2], p[3]);
+ let n = (hull / step.max(0.1)).ceil().clamp(1.0, 400.0) as usize;
+ points.extend((1..=n).map(|k| cubic_at(p, k as f32 / n as f32)));
+ });
+ points
+ })
+ .collect()
+}
+
+pub fn nearest(subs: &[Subpath], to: P) -> Option<(usize, f32, f32)> {
+ let mut base = 0;
+ subs.iter()
+ .flat_map(|sub| {
+ let first = base;
+ base += sub.anchors.len();
+ (0..sub.anchors.len()).filter_map(move |i| segment_points(sub, i).map(|p| (first + i, p)))
+ })
+ .map(|(index, p)| {
+ let hull = dist(p[0], p[1]) + dist(p[1], p[2]) + dist(p[2], p[3]);
+ let n = (hull / 2.0).ceil().clamp(8.0, 400.0) as usize;
+ let (t, d) = (0..=n)
+ .map(|k| {
+ let t = k as f32 / n as f32;
+ (t, dist(point_on(p, t), to))
+ })
+ .fold((0.0, f32::MAX), |best, c| if c.1 < best.1 { c } else { best });
+ (index, t, d)
+ })
+ .fold(None, |best: Option<(usize, f32, f32)>, c| match best {
+ Some(b) if b.2 <= c.2 => Some(b),
+ _ => Some(c),
+ })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Side {
+ In,
+ Out,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum PathEdit {
+ Convert,
+ Move {
+ points: Vec<usize>,
+ by: P,
+ },
+ MoveTo {
+ point: usize,
+ to: P,
+ },
+ Handle {
+ point: usize,
+ side: Side,
+ to: P,
+ free: bool,
+ },
+ Insert {
+ segment: usize,
+ t: f32,
+ },
+ Add {
+ at: P,
+ },
+ Remove {
+ points: Vec<usize>,
+ },
+ Corner {
+ points: Vec<usize>,
+ },
+ Smooth {
+ points: Vec<usize>,
+ },
+ Simplify {
+ tolerance: f32,
+ },
+}
+
+fn indices(value: Value, key: &str) -> Result<Vec<usize>> {
+ match value {
+ Value::Number(n) => Ok(vec![
+ n.as_u64().ok_or_else(|| anyhow!("{key} takes point numbers"))? as usize
+ ]),
+ other => serde_json::from_value(other).map_err(|_| anyhow!("{key} takes a point number or a list of them")),
+ }
+}
+
+fn point(map: &mut Map<String, Value>, key: &str) -> Result<Option<P>> {
+ map.remove(key)
+ .map(|v| serde_json::from_value(v).map_err(|_| anyhow!("{key} takes [x, y]")))
+ .transpose()
+}
+
+impl PathEdit {
+ pub fn parse(map: &mut Map<String, Value>) -> Result<Self> {
+ if let Some(v) = map.remove("move") {
+ let points = indices(v, "move")?;
+ return match (point(map, "to")?, point(map, "by")?, &points[..]) {
+ (Some(to), None, [one]) => Ok(PathEdit::MoveTo { point: *one, to }),
+ (None, Some(by), _) => Ok(PathEdit::Move { points, by }),
+ (Some(_), None, _) => bail!("move with \"to\" takes one point; use \"by\": [dx, dy] for several"),
+ _ => bail!("move needs \"to\": [x, y] or \"by\": [dx, dy]"),
+ };
+ }
+ if let Some(v) = map.remove("handle") {
+ let point_index = indices(v, "handle")?;
+ let [one] = point_index[..] else {
+ bail!("handle takes one point");
+ };
+ let free = map.remove("free").and_then(|v| v.as_bool()).unwrap_or(false);
+ return match (point(map, "in")?, point(map, "out")?) {
+ (Some(to), None) => Ok(PathEdit::Handle {
+ point: one,
+ side: Side::In,
+ to,
+ free,
+ }),
+ (None, Some(to)) => Ok(PathEdit::Handle {
+ point: one,
+ side: Side::Out,
+ to,
+ free,
+ }),
+ _ => bail!("handle needs \"in\": [x, y] or \"out\": [x, y]"),
+ };
+ }
+ if let Some(v) = map.remove("insert") {
+ let segment = indices(v, "insert")?;
+ let [one] = segment[..] else {
+ bail!("insert takes one segment (the point it starts at)");
+ };
+ let t = map.remove("t").and_then(|v| v.as_f64()).unwrap_or(0.5) as f32;
+ if !(0.0..=1.0).contains(&t) {
+ bail!("t must be within 0..1");
+ }
+ return Ok(PathEdit::Insert { segment: one, t });
+ }
+ if let Some(at) = point(map, "add")? {
+ return Ok(PathEdit::Add { at });
+ }
+ if let Some(v) = map.remove("rm") {
+ return Ok(PathEdit::Remove {
+ points: indices(v, "rm")?,
+ });
+ }
+ if let Some(v) = map.remove("corner") {
+ return Ok(PathEdit::Corner {
+ points: indices(v, "corner")?,
+ });
+ }
+ if let Some(v) = map.remove("smooth") {
+ return Ok(PathEdit::Smooth {
+ points: indices(v, "smooth")?,
+ });
+ }
+ if let Some(v) = map.remove("simplify") {
+ let tolerance = v.as_f64().ok_or_else(|| anyhow!("simplify takes a tolerance in px"))? as f32;
+ if !(0.01..=100.0).contains(&tolerance) {
+ bail!("simplify tolerance must be within 0.01..100 px");
+ }
+ return Ok(PathEdit::Simplify { tolerance });
+ }
+ Ok(PathEdit::Convert)
+ }
+
+ pub fn apply(&self, subs: &mut Vec<Subpath>) -> Result<()> {
+ match self {
+ PathEdit::Convert => {}
+ PathEdit::Move { points, by } => points.iter().try_for_each(|&i| {
+ let (s, a) = locate(subs, i)?;
+ subs[s].anchors[a].shift(*by);
+ Ok::<_, anyhow::Error>(())
+ })?,
+ PathEdit::MoveTo { point, to } => {
+ let (s, a) = locate(subs, *point)?;
+ let anchor = &mut subs[s].anchors[a];
+ anchor.shift(sub(*to, anchor.at));
+ }
+ PathEdit::Handle { point, side, to, free } => {
+ let (s, a) = locate(subs, *point)?;
+ let anchor = &mut subs[s].anchors[a];
+ let keep = anchor.smooth() && !free;
+ let (moved, other) = match side {
+ Side::In => (&mut anchor.inn, &mut anchor.out),
+ Side::Out => (&mut anchor.out, &mut anchor.inn),
+ };
+ *moved = *to;
+ if keep {
+ let reach = dist(*other, anchor.at);
+ *other = add(anchor.at, mul(unit(sub(anchor.at, *to)), reach));
+ }
+ }
+ PathEdit::Insert { segment, t } => {
+ let (s, a) = locate(subs, *segment)?;
+ let sub_path = &mut subs[s];
+ let p = segment_points(sub_path, a)
+ .ok_or_else(|| anyhow!("point {segment} ends an open path; there is no segment after it"))?;
+ let next = (a + 1) % sub_path.anchors.len();
+ let straight = !sub_path.anchors[a].has_out() && !sub_path.anchors[next].has_in();
+ let fresh = if straight {
+ Anchor::corner(lerp(p[0], p[3], *t))
+ } else {
+ let (p01, p12, p23) = (lerp(p[0], p[1], *t), lerp(p[1], p[2], *t), lerp(p[2], p[3], *t));
+ let (p012, p123) = (lerp(p01, p12, *t), lerp(p12, p23, *t));
+ sub_path.anchors[a].out = p01;
+ sub_path.anchors[next].inn = p23;
+ Anchor {
+ at: lerp(p012, p123, *t),
+ inn: p012,
+ out: p123,
+ }
+ };
+ sub_path.anchors.insert(a + 1, fresh);
+ }
+ PathEdit::Add { at } => {
+ let (segment, t, _) = nearest(subs, *at).ok_or_else(|| anyhow!("the path has no segments"))?;
+ PathEdit::Insert { segment, t }.apply(subs)?;
+ }
+ PathEdit::Remove { points } => {
+ let mut found: Vec<(usize, usize)> = points.iter().map(|&i| locate(subs, i)).collect::<Result<_>>()?;
+ found.sort();
+ found.dedup();
+ found.iter().rev().for_each(|&(s, a)| {
+ subs[s].anchors.remove(a);
+ });
+ subs.retain(|s| s.anchors.len() >= 2);
+ if subs.is_empty() {
+ bail!("that leaves no segments; remove the shape instead");
+ }
+ }
+ PathEdit::Corner { points } => points.iter().try_for_each(|&i| {
+ let (s, a) = locate(subs, i)?;
+ let anchor = &mut subs[s].anchors[a];
+ anchor.inn = anchor.at;
+ anchor.out = anchor.at;
+ Ok::<_, anyhow::Error>(())
+ })?,
+ PathEdit::Smooth { points } => points.iter().try_for_each(|&i| {
+ let (s, a) = locate(subs, i)?;
+ let sub_path = &subs[s];
+ let (prev, next) = neighbours(sub_path, a);
+ let here = sub_path.anchors[a].at;
+ let before = prev.map(|p| sub_path.anchors[p].at);
+ let after = next.map(|n| sub_path.anchors[n].at);
+ let dir = unit(sub(after.unwrap_or(here), before.unwrap_or(here)));
+ let anchor = &mut subs[s].anchors[a];
+ anchor.inn = before.map_or(here, |b| sub(here, mul(dir, dist(here, b) / 3.0)));
+ anchor.out = after.map_or(here, |n| add(here, mul(dir, dist(here, n) / 3.0)));
+ Ok::<_, anyhow::Error>(())
+ })?,
+ PathEdit::Simplify { tolerance } => {
+ *subs = subs.iter().map(|s| simplify(s, *tolerance)).collect();
+ }
+ }
+ Ok(())
+ }
+}
+
+fn turn(sub: &Subpath, i: usize) -> f32 {
+ let (prev, next) = neighbours(sub, i);
+ let (Some(p), Some(n)) = (prev, next) else {
+ return PI;
+ };
+ let a = &sub.anchors[i];
+ let into = if a.has_in() {
+ sub_dir(a.at, a.inn)
+ } else {
+ sub_dir(a.at, sub.anchors[p].at)
+ };
+ let from = if a.has_out() {
+ sub_dir(a.out, a.at)
+ } else {
+ sub_dir(sub.anchors[n].at, a.at)
+ };
+ angle(into, from).abs()
+}
+
+fn sub_dir(a: P, b: P) -> P {
+ unit(sub(a, b))
+}
+
+pub fn fit_polyline(points: &[P], tolerance: f32) -> Subpath {
+ let spaced = match points.len() {
+ 0 | 1 => points.to_vec(),
+ _ => resample(points, tolerance.max(1.0)),
+ };
+ let rough = Subpath {
+ anchors: spaced.iter().map(|p| Anchor::corner(*p)).collect(),
+ closed: false,
+ };
+ match rough.anchors.len() {
+ 0..=2 => rough,
+ _ => simplify(&rough, tolerance),
+ }
+}
+
+fn simplify(source: &Subpath, tolerance: f32) -> Subpath {
+ let n = source.anchors.len();
+ let corners: Vec<usize> = (0..n).filter(|&i| turn(source, i) > 0.9).collect();
+ let starts: Vec<usize> = match (source.closed, corners.first()) {
+ (true, Some(_)) => corners.clone(),
+ (true, None) => vec![0],
+ (false, _) => std::iter::once(0)
+ .chain(corners.iter().copied().filter(|&c| c > 0 && c + 1 < n))
+ .collect(),
+ };
+ let runs: Vec<Vec<P>> = starts
+ .iter()
+ .enumerate()
+ .map(|(k, &from)| {
+ let to = match starts.get(k + 1) {
+ Some(&next) => next,
+ None if source.closed => starts[0] + n,
+ None => n - 1,
+ };
+ let mut points = vec![source.anchors[from % n].at];
+ (from..to).for_each(|i| {
+ if let Some(p) = segment_points(source, i % n) {
+ let hull = dist(p[0], p[1]) + dist(p[1], p[2]) + dist(p[2], p[3]);
+ let steps = (hull / 2.0).ceil().clamp(1.0, 400.0) as usize;
+ points.extend((1..=steps).map(|s| cubic_at(p, s as f32 / steps as f32)));
+ }
+ });
+ resample(&points, (tolerance / 2.0).clamp(0.5, 4.0))
+ })
+ .collect();
+ let mut anchors: Vec<Anchor> = Vec::new();
+ runs.iter().filter(|r| r.len() >= 2).for_each(|run| {
+ let (first, last) = (run[0], run[run.len() - 1]);
+ let curves = if straight(run, tolerance / 2.0) {
+ vec![[first, first, last, last]]
+ } else {
+ fit(
+ run,
+ sub_dir(run[1], first),
+ sub_dir(run[run.len() - 2], last),
+ tolerance,
+ )
+ };
+ curves.iter().for_each(|c| {
+ match anchors.last_mut() {
+ Some(last) if dist(last.at, c[0]) <= NEAR => last.out = c[1],
+ _ => anchors.push(Anchor {
+ at: c[0],
+ inn: c[0],
+ out: c[1],
+ }),
+ }
+ anchors.push(Anchor {
+ at: c[3],
+ inn: c[2],
+ out: c[3],
+ });
+ });
+ });
+ if source.closed && anchors.len() > 1 && dist(anchors[0].at, anchors[anchors.len() - 1].at) <= NEAR {
+ let last = anchors.pop().expect("two anchors");
+ anchors[0].inn = last.inn;
+ }
+ let tidy = |p: P, at: P| if dist(p, at) < 0.05 { at } else { p };
+ anchors.iter_mut().for_each(|a| {
+ a.inn = tidy(a.inn, a.at);
+ a.out = tidy(a.out, a.at);
+ });
+ Subpath {
+ anchors,
+ closed: source.closed,
+ }
+}
+
+fn straight(points: &[P], within: f32) -> bool {
+ let (a, b) = (points[0], points[points.len() - 1]);
+ let along = unit(sub(b, a));
+ let span = dist(a, b);
+ span > NEAR
+ && points.iter().all(|p| {
+ let v = sub(*p, a);
+ let t = v[0] * along[0] + v[1] * along[1];
+ (v[0] * along[1] - v[1] * along[0]).abs() <= within && (-within..=span + within).contains(&t)
+ })
+}
+
+fn chord(points: &[P]) -> Vec<f32> {
+ let mut u = vec![0.0f32];
+ points
+ .windows(2)
+ .for_each(|w| u.push(u[u.len() - 1] + dist(w[0], w[1])));
+ let total = u[u.len() - 1].max(1e-9);
+ u.iter_mut().for_each(|v| *v /= total);
+ u
+}
+
+fn generate(points: &[P], u: &[f32], t1: P, t2: P) -> [P; 4] {
+ let (first, last) = (points[0], points[points.len() - 1]);
+ let (mut c00, mut c01, mut c11, mut x0, mut x1) = (0.0f32, 0.0f32, 0.0f32, 0.0f32, 0.0f32);
+ points.iter().zip(u).for_each(|(p, &t)| {
+ let s = 1.0 - t;
+ let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
+ let (a1, a2) = (mul(t1, b1), mul(t2, b2));
+ c00 += a1[0] * a1[0] + a1[1] * a1[1];
+ c01 += a1[0] * a2[0] + a1[1] * a2[1];
+ c11 += a2[0] * a2[0] + a2[1] * a2[1];
+ let rest = sub(*p, add(mul(first, b0 + b1), mul(last, b2 + b3)));
+ x0 += a1[0] * rest[0] + a1[1] * rest[1];
+ x1 += a2[0] * rest[0] + a2[1] * rest[1];
+ });
+ let det = c00 * c11 - c01 * c01;
+ let span = dist(first, last);
+ let (mut l, mut r) = if det.abs() > 1e-12 {
+ ((x0 * c11 - c01 * x1) / det, (c00 * x1 - c01 * x0) / det)
+ } else {
+ (span / 3.0, span / 3.0)
+ };
+ if l < span * 1e-6 || r < span * 1e-6 {
+ l = span / 3.0;
+ r = span / 3.0;
+ }
+ [first, add(first, mul(t1, l)), add(last, mul(t2, r)), last]
+}
+
+fn worst(points: &[P], curve: [P; 4], u: &[f32]) -> (f32, usize) {
+ points
+ .iter()
+ .zip(u)
+ .enumerate()
+ .map(|(i, (p, &t))| (dist(cubic_at(curve, t), *p), i))
+ .fold((0.0, points.len() / 2), |best, c| if c.0 > best.0 { c } else { best })
+}
+
+fn reparameterize(points: &[P], u: &[f32], c: [P; 4]) -> Vec<f32> {
+ let d1 = [
+ mul(sub(c[1], c[0]), 3.0),
+ mul(sub(c[2], c[1]), 3.0),
+ mul(sub(c[3], c[2]), 3.0),
+ ];
+ let d2 = [mul(sub(d1[1], d1[0]), 2.0), mul(sub(d1[2], d1[1]), 2.0)];
+ points
+ .iter()
+ .zip(u)
+ .map(|(p, &t)| {
+ let s = 1.0 - t;
+ let q = cubic_at(c, t);
+ let q1 = add(add(mul(d1[0], s * s), mul(d1[1], 2.0 * s * t)), mul(d1[2], t * t));
+ let q2 = add(mul(d2[0], s), mul(d2[1], t));
+ let diff = sub(q, *p);
+ let num = diff[0] * q1[0] + diff[1] * q1[1];
+ let den = q1[0] * q1[0] + q1[1] * q1[1] + diff[0] * q2[0] + diff[1] * q2[1];
+ if den.abs() < 1e-9 {
+ t
+ } else {
+ (t - num / den).clamp(0.0, 1.0)
+ }
+ })
+ .collect()
+}
+
+fn fit(points: &[P], t1: P, t2: P, tolerance: f32) -> Vec<[P; 4]> {
+ if points.len() == 2 {
+ let span = dist(points[0], points[1]) / 3.0;
+ return vec![[
+ points[0],
+ add(points[0], mul(t1, span)),
+ add(points[1], mul(t2, span)),
+ points[1],
+ ]];
+ }
+ let mut u = chord(points);
+ let mut curve = generate(points, &u, t1, t2);
+ let (mut error, mut split) = worst(points, curve, &u);
+ if error <= tolerance {
+ return vec![curve];
+ }
+ if error <= tolerance * 4.0 {
+ for _ in 0..4 {
+ u = reparameterize(points, &u, curve);
+ curve = generate(points, &u, t1, t2);
+ (error, split) = worst(points, curve, &u);
+ if error <= tolerance {
+ return vec![curve];
+ }
+ }
+ }
+ let split = split.clamp(1, points.len() - 2);
+ let center = sub_dir(points[split - 1], points[split + 1]);
+ let mut left = fit(&points[..=split], t1, center, tolerance);
+ left.extend(fit(&points[split..], mul(center, -1.0), t2, tolerance));
+ left
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn near(a: P, b: P) -> bool {
+ dist(a, b) < 0.02
+ }
+
+ fn edit(d: &str, value: Value) -> String {
+ let mut subs = parse(d).unwrap();
+ let mut map = value.as_object().unwrap().clone();
+ PathEdit::parse(&mut map).unwrap().apply(&mut subs).unwrap();
+ to_d(&subs)
+ }
+
+ #[test]
+ fn paths_parse_to_anchors_and_write_back() {
+ let d = "M10 10 L20 10 C25 10 30 15 30 20 Q30 30 20 30 Z M100 100 h10 v10";
+ let subs = parse(d).unwrap();
+ assert_eq!(subs.len(), 2);
+ assert!(subs[0].closed && !subs[1].closed);
+ assert_eq!(subs[0].anchors.len(), 4);
+ assert!(near(subs[0].anchors[1].out, [25.0, 10.0]));
+ assert!(near(subs[0].anchors[3].inn, [26.67, 30.0]));
+ assert_eq!(subs[1].anchors.len(), 3);
+ let text = to_d(&subs);
+ assert_eq!(parse(&text).unwrap(), parse(&to_d(&parse(&text).unwrap())).unwrap());
+ assert!(text.starts_with("M10 10 L20 10 C25 10 30 15 30 20 C"), "{text}");
+ assert!(text.ends_with("M100 100 L110 100 L110 110"), "{text}");
+ let closing = parse("M0 0 L10 0 L10 10 L0 0 Z").unwrap();
+ assert_eq!(closing[0].anchors.len(), 3);
+ assert_eq!(to_d(&closing), "M0 0 L10 0 L10 10 Z");
+ }
+
+ #[test]
+ fn arcs_become_curves_that_end_where_they_should() {
+ let subs = parse("M0 50 A50 50 0 0 1 100 50").unwrap();
+ let line = &flatten(&subs, 1.0)[0];
+ assert!(near(*line.last().unwrap(), [100.0, 50.0]));
+ let top = line.iter().map(|p| p[1]).fold(f32::MAX, f32::min);
+ assert!((top - 0.0).abs() < 0.2, "{top}");
+ assert!(line.iter().all(|p| (dist(*p, [50.0, 50.0]) - 50.0).abs() < 0.1));
+ }
+
+ #[test]
+ fn points_move_handles_follow_and_smooth_points_stay_smooth() {
+ let d = "M0 0 C10 -10 20 -10 30 0 C40 10 50 10 60 0";
+ assert_eq!(
+ edit(d, json!({"move":1,"to":[30,5]})),
+ "M0 0 C10 -10 20 -5 30 5 C40 15 50 10 60 0"
+ );
+ let subs = parse(&edit(d, json!({"handle":1,"out":[30,20]}))).unwrap();
+ let a = subs[0].anchors[1];
+ assert!(
+ near(a.out, [30.0, 20.0]) && near(a.inn, [30.0, -14.14]) && a.smooth(),
+ "{a:?}"
+ );
+ let free = parse(&edit(d, json!({"handle":1,"out":[30,20],"free":true}))).unwrap();
+ assert!(!free[0].anchors[1].smooth());
+ assert_eq!(
+ edit(d, json!({"move":[0,2],"by":[1,2]})),
+ "M1 2 C11 -8 20 -10 30 0 C40 10 51 12 61 2"
+ );
+ assert_eq!(edit("M0 0 L10 0 L20 0", json!({"corner":1})), "M0 0 L10 0 L20 0");
+ let smooth = parse(&edit("M0 0 L10 10 L20 0", json!({"smooth":1}))).unwrap();
+ assert!(smooth[0].anchors[1].smooth());
+ }
+
+ #[test]
+ fn inserting_splits_a_curve_without_changing_it() {
+ let d = "M0 0 C0 100 100 100 100 0";
+ let split = parse(&edit(d, json!({"insert":0,"t":0.5}))).unwrap();
+ assert_eq!(split[0].anchors.len(), 3);
+ assert!(near(split[0].anchors[1].at, [50.0, 75.0]));
+ let before = flatten(&parse(d).unwrap(), 0.5);
+ let after = flatten(&split, 0.5);
+ before[0].iter().step_by(7).for_each(|p| {
+ let closest = after[0].iter().map(|q| dist(*p, *q)).fold(f32::MAX, f32::min);
+ assert!(closest < 0.6, "{p:?} {closest}");
+ });
+ assert_eq!(edit("M0 0 L10 0", json!({"insert":0,"t":0.25})), "M0 0 L2.5 0 L10 0");
+ assert_eq!(
+ edit("M0 0 L10 0 L10 10 Z", json!({"insert":2})),
+ "M0 0 L10 0 L10 10 L5 5 Z"
+ );
+ assert!(
+ PathEdit::parse(&mut json!({"insert":1}).as_object().unwrap().clone())
+ .unwrap()
+ .apply(&mut parse("M0 0 L10 0").unwrap())
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn adding_a_point_near_a_segment_splits_it_there() {
+ assert_eq!(
+ edit("M0 0 L100 0 L100 100", json!({"add":[103,40]})),
+ "M0 0 L100 0 L100 40 L100 100"
+ );
+ }
+
+ #[test]
+ fn removing_points_joins_their_neighbours() {
+ assert_eq!(edit("M0 0 L10 0 L20 0 L30 5", json!({"rm":[1,2]})), "M0 0 L30 5");
+ let mut subs = parse("M0 0 L10 0").unwrap();
+ let mut map = json!({"rm":0}).as_object().unwrap().clone();
+ assert!(PathEdit::parse(&mut map).unwrap().apply(&mut subs).is_err());
+ }
+
+ #[test]
+ fn shapes_convert_to_the_same_outline() {
+ let rect = from_shape(&Shape::Rect {
+ x: 10.0,
+ y: 20.0,
+ w: 100.0,
+ h: 50.0,
+ radius: 0.0,
+ })
+ .unwrap();
+ assert_eq!(to_d(&rect), "M10 20 L110 20 L110 70 L10 70 Z");
+ let ellipse = from_shape(&Shape::Ellipse {
+ cx: 0.0,
+ cy: 0.0,
+ rx: 40.0,
+ ry: 20.0,
+ })
+ .unwrap();
+ let outline = flatten(&ellipse, 0.5);
+ assert!(outline[0].iter().all(|p| {
+ let r = (p[0] / 40.0).powi(2) + (p[1] / 20.0).powi(2);
+ (r - 1.0).abs() < 0.002
+ }));
+ let round = from_shape(&Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 100.0,
+ h: 40.0,
+ radius: 10.0,
+ })
+ .unwrap();
+ assert_eq!(round[0].anchors.len(), 8);
+ assert!(
+ round[0].anchors[1..]
+ .iter()
+ .step_by(2)
+ .all(|a| !a.has_in() || !a.has_out())
+ );
+ }
+
+ #[test]
+ fn simplify_turns_a_dense_polyline_into_few_smooth_points() {
+ let points: Vec<String> = (0..=250)
+ .map(|i| {
+ let x = i as f32 * 4.0;
+ let y = 300.0 + 80.0 * libm::sinf(x / 160.0) + 20.0 * libm::sinf(x / 37.0);
+ format!("{x} {y:.2}")
+ })
+ .collect();
+ let d = format!("M{} L{} L1000 600 L0 600 Z", points[0], points[1..].join(" L"));
+ let dense = parse(&d).unwrap();
+ let simple = parse(&edit(&d, json!({"simplify":1.0}))).unwrap();
+ let (before, after) = (dense[0].anchors.len(), simple[0].anchors.len());
+ assert!(after * 8 < before, "{before} -> {after}");
+ let fine = flatten(&simple, 0.5);
+ dense[0].anchors.iter().for_each(|a| {
+ let closest = fine[0].iter().map(|q| dist(a.at, *q)).fold(f32::MAX, f32::min);
+ assert!(closest < 1.6, "{:?} is {closest} away", a.at);
+ });
+ assert!(simple[0].anchors.iter().any(|a| a.at == [1000.0, 600.0] && !a.smooth()));
+ }
+
+ #[test]
+ fn the_nearest_segment_is_found() {
+ let subs = parse("M0 0 L100 0 L100 100").unwrap();
+ let (segment, t, d) = nearest(&subs, [100.0, 30.0]).unwrap();
+ assert_eq!(segment, 1);
+ assert!((t - 0.3).abs() < 0.02 && d < 0.5);
+ }
+}
diff --git a/crates/core/src/retime.rs b/crates/core/src/retime.rs
new file mode 100644
index 0000000..b749d2f
--- /dev/null
+++ b/crates/core/src/retime.rs
@@ -0,0 +1,433 @@
+use crate::doc::{Cel, Document, Kind, Layer, LayerContent, Loc, MASK};
+use crate::ops::Applied;
+use crate::timing::{OPEN, ends};
+use anyhow::{Result, bail};
+use std::collections::{BTreeMap, BTreeSet};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Retime {
+ On(u32),
+ Fit(u32),
+ Reverse,
+ Pingpong,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RetimeSpec {
+ pub from: u32,
+ pub to: u32,
+ pub action: Retime,
+ pub layers: Option<Vec<String>>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct Run {
+ start: u32,
+ end: u32,
+ cel: Option<String>,
+}
+
+fn runs_of(cels: &[Cel]) -> Vec<Run> {
+ let mut out = Vec::new();
+ let mut at = 0;
+ cels.iter().zip(ends(cels)).for_each(|(c, end)| {
+ if c.frame > at {
+ out.push(Run {
+ start: at,
+ end: c.frame,
+ cel: None,
+ });
+ }
+ out.push(Run {
+ start: c.frame,
+ end,
+ cel: Some(c.id.clone()),
+ });
+ at = end;
+ });
+ if at != OPEN {
+ out.push(Run {
+ start: at,
+ end: OPEN,
+ cel: None,
+ });
+ }
+ out
+}
+
+fn content_at(runs: &[Run], frame: u32) -> Option<&str> {
+ runs.iter()
+ .find(|r| r.start <= frame && frame < r.end)
+ .and_then(|r| r.cel.as_deref())
+}
+
+fn leaf_paths(doc: &Document, keys: Option<&[String]>) -> Result<Vec<Vec<usize>>> {
+ fn walk(layer: &Layer, path: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
+ if layer.kind() != Kind::Group {
+ out.push(path.clone());
+ }
+ if let Some(mask) = layer.mask.as_deref() {
+ path.push(MASK);
+ walk(mask, path, out);
+ path.pop();
+ }
+ layer.children().iter().enumerate().for_each(|(i, c)| {
+ path.push(i);
+ walk(c, path, out);
+ path.pop();
+ });
+ }
+ let roots: Vec<Vec<usize>> = match keys {
+ None => (0..doc.layers.len()).map(|i| vec![i]).collect(),
+ Some(keys) => keys
+ .iter()
+ .map(|k| {
+ let id = doc.find_layer(k)?.id.clone();
+ match doc.locate(&id) {
+ Some(Loc::Layer(path)) => Ok(path),
+ _ => bail!("{k} is not a layer"),
+ }
+ })
+ .collect::<Result<_>>()?,
+ };
+ let mut out = Vec::new();
+ roots.iter().for_each(|root| {
+ let mut path = root.clone();
+ walk(doc.layer_at(root), &mut path, &mut out);
+ });
+ Ok(out.into_iter().collect::<BTreeSet<_>>().into_iter().collect())
+}
+
+fn order(action: Retime, starts: &[u32], from: u32, length: u32) -> Result<Vec<(usize, u32)>> {
+ let k = starts.len();
+ let len = |i: usize| starts.get(i + 1).copied().unwrap_or(from + length) - starts[i];
+ Ok(match action {
+ Retime::On(n) => (0..k).map(|i| (i, n)).collect(),
+ Retime::Reverse => (0..k).rev().map(|i| (i, len(i))).collect(),
+ Retime::Pingpong => (0..k)
+ .chain((1..k.saturating_sub(1)).rev())
+ .map(|i| (i, len(i)))
+ .collect(),
+ Retime::Fit(n) => {
+ if (n as usize) < k {
+ bail!(
+ "frames {from} to {} show {k} different pictures; fit them into at least {k} frames",
+ from + length - 1
+ );
+ }
+ let mut placed: Vec<u32> = Vec::with_capacity(k + 1);
+ (0..k).for_each(|i| {
+ let ideal = ((starts[i] - from) as u64 * n as u64 + length as u64 / 2) / length as u64;
+ let low = placed.last().map_or(0, |p| p + 1);
+ let high = n - (k - i) as u32;
+ placed.push((ideal as u32).clamp(low, high));
+ });
+ placed.push(n);
+ (0..k).map(|i| (i, placed[i + 1] - placed[i])).collect()
+ }
+ })
+}
+
+fn rebuild(doc: &mut Document, path: &[usize], runs: Vec<Run>, out: &mut Applied) {
+ let merged = runs.into_iter().fold(Vec::<Run>::new(), |mut acc, run| {
+ match acc.last_mut() {
+ Some(last) if last.cel == run.cel && last.end == run.start => last.end = run.end,
+ _ if run.end > run.start => acc.push(run),
+ _ => {}
+ }
+ acc
+ });
+ let old: BTreeMap<String, Cel> = doc
+ .layer_at(path)
+ .cels()
+ .iter()
+ .map(|c| (c.id.clone(), c.clone()))
+ .collect();
+ let shown: Vec<&Run> = merged.iter().filter(|r| r.cel.is_some()).collect();
+ let mut seen = BTreeSet::new();
+ let mut taken = doc.ids();
+ let cels: Vec<Cel> = shown
+ .iter()
+ .enumerate()
+ .map(|(i, run)| {
+ let id = run.cel.clone().unwrap_or_default();
+ let next = shown.get(i + 1).map_or(OPEN, |r| r.start);
+ let hold = (run.end != OPEN && run.end != next).then(|| run.end - run.start);
+ let original = &old[&id];
+ if seen.insert(id.clone()) {
+ let kept = (original.hold.is_some() && run.end != OPEN).then(|| run.end - run.start);
+ return Cel {
+ frame: run.start,
+ hold: kept.or(hold),
+ ..original.clone()
+ };
+ }
+ let fresh = doc.alloc_id_in('c', &mut taken);
+ out.added.push(fresh.clone());
+ Cel {
+ link: Some(original.link.clone().unwrap_or(id)),
+ hold,
+ ..Cel::at(&fresh, run.start)
+ }
+ })
+ .collect();
+ if let LayerContent::Paint { cels: list } | LayerContent::Vector { cels: list } =
+ &mut doc.layer_at_mut(path).content
+ {
+ *list = cels;
+ }
+}
+
+fn shifted(frame: u32, delta: i64) -> u32 {
+ match frame {
+ OPEN => OPEN,
+ f => (f as i64 + delta).max(0) as u32,
+ }
+}
+
+fn warp(frame: u32, from: u32, length: u32, new_length: u32) -> u32 {
+ let end = from + length;
+ match frame {
+ f if f <= from => f,
+ f if f >= end => f - length + new_length,
+ f => from + (((f - from) as u64 * new_length as u64 + length as u64 / 2) / length as u64) as u32,
+ }
+}
+
+pub fn retime(doc: &mut Document, spec: &RetimeSpec, out: &mut Applied) -> Result<String> {
+ let (from, to) = (spec.from, spec.to);
+ let frames = doc.timeline.frames;
+ if from > to {
+ bail!("retime frames run from {from} to {to}: the first frame comes after the last");
+ }
+ if to >= frames {
+ bail!("frame {to} is past the end of the timeline ({frames} frames)");
+ }
+ match spec.action {
+ Retime::On(0) => bail!("on must be at least 1"),
+ Retime::Fit(0) => bail!("fit must be at least 1"),
+ _ => {}
+ }
+ let paths = leaf_paths(doc, spec.layers.as_deref())?;
+ let runs: Vec<Vec<Run>> = paths.iter().map(|p| runs_of(doc.layer_at(p).cels())).collect();
+ let starts: Vec<u32> = (from..=to)
+ .filter(|&f| f == from || runs.iter().any(|r| content_at(r, f) != content_at(r, f - 1)))
+ .collect();
+ let length = to + 1 - from;
+ let segments = order(spec.action, &starts, from, length)?;
+ let new_length: u32 = segments.iter().map(|(_, n)| n).sum();
+ let delta = new_length as i64 - length as i64;
+ paths.iter().zip(runs).for_each(|(path, runs)| {
+ let before = runs.iter().filter(|r| r.start < from).map(|r| Run {
+ end: r.end.min(from),
+ ..r.clone()
+ });
+ let mut at = from;
+ let middle: Vec<Run> = segments
+ .iter()
+ .map(|(i, n)| {
+ let run = Run {
+ start: at,
+ end: at + n,
+ cel: content_at(&runs, starts[*i]).map(String::from),
+ };
+ at += n;
+ run
+ })
+ .collect();
+ let after = runs.iter().filter(|r| r.end == OPEN || r.end > to + 1).map(|r| Run {
+ start: shifted(r.start.max(to + 1), delta),
+ end: shifted(r.end, delta),
+ cel: r.cel.clone(),
+ });
+ let all: Vec<Run> = before.chain(middle).chain(after).collect();
+ rebuild(doc, path, all, out);
+ });
+ match &spec.layers {
+ None => {
+ doc.timeline.clips.iter_mut().for_each(|clip| {
+ let (a, b) = (
+ warp(clip.from, from, length, new_length),
+ warp(clip.to + 1, from, length, new_length),
+ );
+ clip.from = a;
+ clip.to = b.max(a + 1) - 1;
+ });
+ doc.timeline.frames = shifted(frames, delta).max(1);
+ }
+ Some(_) if delta > 0 => {
+ let reach = paths
+ .iter()
+ .map(|p| {
+ let cels = doc.layer_at(p).cels();
+ cels.last().map_or(0, |c| match c.hold {
+ None => frames + delta as u32,
+ Some(h) => c.frame + h,
+ })
+ })
+ .max()
+ .unwrap_or(0);
+ doc.timeline.frames = frames.max(reach);
+ }
+ Some(_) => {}
+ }
+ out.changed.push("timeline".into());
+ let what = match spec.action {
+ Retime::On(n) => format!("on {n}s"),
+ Retime::Fit(n) => format!("fitted into {n} frames"),
+ Retime::Reverse => "reversed".into(),
+ Retime::Pingpong => "ping-ponged".into(),
+ };
+ let shift = match delta {
+ 0 => String::new(),
+ d => format!("; later frames moved by {d:+}"),
+ };
+ Ok(format!(
+ "frames {from} to {to} ({} picture{}) {what}: now frames {from} to {}{shift}",
+ starts.len(),
+ if starts.len() == 1 { "" } else { "s" },
+ from + new_length - 1
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::Clip;
+ use crate::ops::{Op, apply_all};
+ use crate::timing::{Cell, cells};
+ use serde_json::json;
+
+ fn cel(id: &str, frame: u32, hold: Option<u32>, link: Option<&str>) -> Cel {
+ Cel {
+ hold,
+ link: link.map(String::from),
+ ..Cel::at(id, frame)
+ }
+ }
+
+ fn doc(layers: Vec<Vec<Cel>>, frames: u32) -> Document {
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = frames;
+ doc.layers = layers
+ .into_iter()
+ .enumerate()
+ .map(|(i, cels)| {
+ let mut layer = Layer::paint(&format!("l{}", i + 1), &format!("layer {}", i + 1), "x");
+ *layer.cels_mut().unwrap() = cels;
+ layer
+ })
+ .collect();
+ doc.next_id = 100;
+ doc
+ }
+
+ fn sheet(doc: &Document, layer: &str) -> String {
+ cells(doc.layer(layer).unwrap(), doc.timeline.frames)
+ .iter()
+ .map(|c| match c {
+ Cell::Drawing { cel, start: true } => cel.trim_start_matches('c').to_string(),
+ Cell::Link {
+ source, start: true, ..
+ } => format!(">{}", source.trim_start_matches('c')),
+ Cell::Drawing { .. } | Cell::Link { .. } => "|".into(),
+ Cell::Blank => ".".into(),
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+ }
+
+ fn run(doc: &Document, op: serde_json::Value) -> Result<(Document, Applied)> {
+ apply_all(doc, &[Op::parse(op)?])
+ }
+
+ fn ones() -> Document {
+ doc(
+ vec![
+ vec![
+ cel("c1", 0, Some(1), None),
+ cel("c2", 1, Some(1), None),
+ cel("c3", 2, Some(1), None),
+ cel("c4", 3, Some(1), None),
+ cel("c9", 4, None, None),
+ ],
+ vec![cel("c5", 0, None, None)],
+ ],
+ 6,
+ )
+ }
+
+ #[test]
+ fn on_twos_and_back_keeps_every_layer_in_step() {
+ let start = ones();
+ assert_eq!(sheet(&start, "l1"), "1 2 3 4 9 |");
+ let (twos, _) = run(&start, json!({"op":"retime","from":0,"to":3,"on":2})).unwrap();
+ assert_eq!(sheet(&twos, "l1"), "1 | 2 | 3 | 4 | 9 |");
+ assert_eq!(sheet(&twos, "l2"), "5 | | | | | | | | |");
+ assert_eq!(twos.timeline.frames, 10);
+ let (back, _) = run(&twos, json!({"op":"retime","from":0,"to":7,"on":1})).unwrap();
+ assert_eq!(sheet(&back, "l1"), sheet(&start, "l1"));
+ assert_eq!(back.layer("l1").unwrap().cels(), start.layer("l1").unwrap().cels());
+ assert_eq!(back.timeline.frames, 6);
+ }
+
+ #[test]
+ fn listed_layers_retime_alone_and_leave_clips_and_other_layers() {
+ let mut start = ones();
+ start.timeline.clips = vec![Clip::new("walk", 0, 3, true)];
+ let (twos, _) = run(&start, json!({"op":"retime","from":0,"to":3,"on":2,"layers":["l1"]})).unwrap();
+ assert_eq!(sheet(&twos, "l1"), "1 | 2 | 3 | 4 | 9 |");
+ assert_eq!(sheet(&twos, "l2"), "5 | | | | | | | | |");
+ assert_eq!(twos.timeline.clips[0], Clip::new("walk", 0, 3, true));
+ let (all, _) = run(&start, json!({"op":"retime","from":0,"to":3,"on":2})).unwrap();
+ assert_eq!((all.timeline.clips[0].from, all.timeline.clips[0].to), (0, 7));
+ }
+
+ #[test]
+ fn fit_keeps_order_and_relative_timing_with_at_least_a_frame_each() {
+ let start = doc(
+ vec![vec![
+ cel("c1", 0, Some(4), None),
+ cel("c2", 4, Some(2), None),
+ cel("c3", 6, Some(2), None),
+ cel("c4", 8, None, None),
+ ]],
+ 10,
+ );
+ let (fit, _) = run(&start, json!({"op":"retime","from":0,"to":7,"fit":4})).unwrap();
+ assert_eq!(sheet(&fit, "l1"), "1 | 2 3 4 |");
+ let (tight, _) = run(&start, json!({"op":"retime","from":0,"to":7,"fit":3})).unwrap();
+ assert_eq!(sheet(&tight, "l1"), "1 2 3 4 |");
+ let err = run(&start, json!({"op":"retime","from":0,"to":7,"fit":2})).unwrap_err();
+ assert!(format!("{err:#}").contains("at least 3 frames"), "{err:#}");
+ let (long, _) = run(&start, json!({"op":"retime","from":0,"to":7,"fit":16})).unwrap();
+ assert_eq!(sheet(&long, "l1"), "1 | | | | | | | 2 | | | 3 | | | 4 |");
+ }
+
+ #[test]
+ fn reverse_and_pingpong_reuse_drawings_through_links() {
+ let start = ones();
+ let (back, _) = run(&start, json!({"op":"retime","from":0,"to":3,"reverse":true})).unwrap();
+ assert_eq!(sheet(&back, "l1"), "4 3 2 1 9 |");
+ let (pp, applied) = run(&start, json!({"op":"retime","from":0,"to":3,"pingpong":true})).unwrap();
+ assert_eq!(sheet(&pp, "l1"), "1 2 3 4 >3 >2 9 |");
+ assert_eq!(applied.added.len(), 2);
+ assert_eq!(pp.timeline.frames, 8);
+ assert_eq!(sheet(&pp, "l2"), "5 | | | | | | |");
+ }
+
+ #[test]
+ fn exposures_crossing_the_range_split_into_links_when_they_move() {
+ let start = doc(
+ vec![vec![
+ cel("c1", 0, Some(3), None),
+ cel("c2", 3, Some(1), None),
+ cel("c3", 4, Some(2), Some("c1")),
+ ]],
+ 6,
+ );
+ let (back, _) = run(&start, json!({"op":"retime","from":2,"to":5,"reverse":true})).unwrap();
+ assert_eq!(sheet(&back, "l1"), "1 | >1 | 2 >1");
+ back.validate().unwrap();
+ }
+}
diff --git a/crates/core/src/rng.rs b/crates/core/src/rng.rs
new file mode 100644
index 0000000..b033653
--- /dev/null
+++ b/crates/core/src/rng.rs
@@ -0,0 +1,70 @@
+#[derive(Clone, Debug)]
+pub struct Rng(u64);
+
+impl Rng {
+ pub fn new(seed: u64) -> Self {
+ Self(seed ^ 0x6A09_E667_F3BC_C908)
+ }
+
+ pub fn next_u64(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ mix64(self.0)
+ }
+
+ pub fn unit(&mut self) -> f32 {
+ (self.next_u64() >> 40) as f32 / (1u64 << 24) as f32
+ }
+
+ pub fn signed(&mut self) -> f32 {
+ self.unit() * 2.0 - 1.0
+ }
+
+ pub fn range(&mut self, lo: f32, hi: f32) -> f32 {
+ lo + (hi - lo) * self.unit()
+ }
+
+ pub fn below(&mut self, n: usize) -> usize {
+ (self.next_u64() % n as u64) as usize
+ }
+}
+
+pub fn mix64(v: u64) -> u64 {
+ let z = (v ^ (v >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ let z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+}
+
+pub fn hash2(x: i32, y: i32, seed: u32) -> u32 {
+ let packed = ((x as u32 as u64) << 32) | (y as u32 as u64);
+ (mix64(packed ^ ((seed as u64) << 17).wrapping_mul(0x9E37_79B9_7F4A_7C15)) >> 32) as u32
+}
+
+pub fn hash2_unit(x: i32, y: i32, seed: u32) -> f32 {
+ (hash2(x, y, seed) >> 8) as f32 / (1u32 << 24) as f32
+}
+
+pub const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
+
+pub fn fnv(hash: u64, bytes: &[u8]) -> u64 {
+ bytes
+ .iter()
+ .fold(hash, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn same_seed_same_sequence() {
+ let a: Vec<u64> = (0..8).scan(Rng::new(7), |r, _| Some(r.next_u64())).collect();
+ let b: Vec<u64> = (0..8).scan(Rng::new(7), |r, _| Some(r.next_u64())).collect();
+ assert_eq!(a, b);
+ }
+
+ #[test]
+ fn unit_stays_in_range() {
+ let mut r = Rng::new(1);
+ assert!((0..10_000).map(|_| r.unit()).all(|v| (0.0..1.0).contains(&v)));
+ }
+}
diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rs
new file mode 100644
index 0000000..b871a2e
--- /dev/null
+++ b/crates/core/src/stroke.rs
@@ -0,0 +1,613 @@
+use crate::color::{Rgba, from_u16, to_u16};
+use crate::cut::{self, Cut};
+use crate::fill::{self, Fill};
+use crate::varint::{self, Reader};
+use anyhow::{Result, bail};
+
+pub const POS_SCALE: f32 = 16.0;
+pub const PRESSURE_STEPS: f32 = 4095.0;
+pub const TILT_STEPS: f32 = 127.0;
+pub const ZSTD_LEVEL: i32 = 3;
+const MAGIC: &[u8; 4] = b"DAST";
+const VERSION: u8 = 6;
+const MARK_STROKE: u8 = 0;
+const MARK_FILL: u8 = 1;
+const HAS_TILT: u8 = 1;
+const HAS_TIME: u8 = 2;
+const HAS_TAPER: u8 = 4;
+const HAS_LOCK: u8 = 8;
+const HAS_CUTS: u8 = 16;
+const HAS_SECOND: u8 = 32;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct Sample {
+ pub x: i32,
+ pub y: i32,
+ pub pressure: u16,
+ pub tilt_x: i8,
+ pub tilt_y: i8,
+ pub dt_ms: u16,
+}
+
+impl Sample {
+ pub fn quantize(x: f32, y: f32, pressure: f32, tilt: (f32, f32), dt_ms: f32) -> Self {
+ Self {
+ x: (x * POS_SCALE).round() as i32,
+ y: (y * POS_SCALE).round() as i32,
+ pressure: (pressure.clamp(0.0, 1.0) * PRESSURE_STEPS).round() as u16,
+ tilt_x: (tilt.0.clamp(-1.0, 1.0) * TILT_STEPS).round() as i8,
+ tilt_y: (tilt.1.clamp(-1.0, 1.0) * TILT_STEPS).round() as i8,
+ dt_ms: dt_ms.round().clamp(0.0, u16::MAX as f32) as u16,
+ }
+ }
+
+ pub fn pos(&self) -> (f32, f32) {
+ (self.x as f32 / POS_SCALE, self.y as f32 / POS_SCALE)
+ }
+
+ pub fn pressure(&self) -> f32 {
+ self.pressure as f32 / PRESSURE_STEPS
+ }
+
+ pub fn tilt(&self) -> (f32, f32) {
+ (self.tilt_x as f32 / TILT_STEPS, self.tilt_y as f32 / TILT_STEPS)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Author {
+ #[default]
+ Human,
+ Agent,
+}
+
+impl Author {
+ pub fn name(self) -> &'static str {
+ match self {
+ Author::Human => "human",
+ Author::Agent => "agent",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Stroke {
+ pub id: u32,
+ pub brush: String,
+ pub color: [u16; 4],
+ pub size: f32,
+ pub opacity: f32,
+ pub flow: f32,
+ pub seed: u32,
+ pub author: Author,
+ pub taper: [f32; 2],
+ pub lock: bool,
+ pub cuts: Vec<Cut>,
+ pub second: Option<[u16; 4]>,
+ pub samples: Vec<Sample>,
+}
+
+impl Stroke {
+ pub fn new(id: u32, brush: &str, color: Rgba, size: f32, seed: u32) -> Self {
+ Self {
+ id,
+ brush: brush.to_string(),
+ color: to_u16(color),
+ size,
+ opacity: 1.0,
+ flow: 1.0,
+ seed,
+ author: Author::Human,
+ taper: [0.0, 0.0],
+ lock: false,
+ cuts: Vec::new(),
+ second: None,
+ samples: Vec::new(),
+ }
+ }
+
+ pub fn tapered(mut self, taper: [f32; 2]) -> Self {
+ self.taper = taper;
+ self
+ }
+
+ pub fn pressureless(&self) -> bool {
+ self.samples.iter().all(|s| s.pressure == 0)
+ }
+
+ pub fn by(mut self, author: Author) -> Self {
+ self.author = author;
+ self
+ }
+
+ pub fn with_points(mut self, points: &[(f32, f32, f32)], dt_ms: f32) -> Self {
+ self.samples = points
+ .iter()
+ .map(|&(x, y, p)| Sample::quantize(x, y, p, (0.0, 0.0), dt_ms))
+ .collect();
+ self
+ }
+
+ pub fn color(&self) -> Rgba {
+ from_u16(self.color)
+ }
+
+ pub fn second_color(&self) -> Option<Rgba> {
+ self.second.map(from_u16)
+ }
+
+ pub fn bounds(&self) -> Option<[f32; 4]> {
+ let first = self.samples.first()?.pos();
+ Some(
+ self.samples
+ .iter()
+ .map(Sample::pos)
+ .fold([first.0, first.1, first.0, first.1], |[x0, y0, x1, y1], (x, y)| {
+ [x0.min(x), y0.min(y), x1.max(x), y1.max(y)]
+ }),
+ )
+ }
+
+ fn channels(&self) -> u8 {
+ let tilt = self.samples.iter().any(|s| s.tilt_x != 0 || s.tilt_y != 0);
+ let time = self.samples.iter().any(|s| s.dt_ms != 0);
+ let taper = self.taper != [0.0, 0.0];
+ [
+ (tilt, HAS_TILT),
+ (time, HAS_TIME),
+ (taper, HAS_TAPER),
+ (self.lock, HAS_LOCK),
+ (!self.cuts.is_empty(), HAS_CUTS),
+ (self.second.is_some(), HAS_SECOND),
+ ]
+ .iter()
+ .filter(|(on, _)| *on)
+ .fold(0, |bits, (_, bit)| bits | bit)
+ }
+}
+
+fn put_column(out: &mut Vec<u8>, values: impl Iterator<Item = i64>) {
+ values.fold(0i64, |prev, v| {
+ varint::put_signed(out, v - prev);
+ v
+ });
+}
+
+fn read_column(reader: &mut Reader, n: usize) -> Result<Vec<i64>> {
+ let mut prev = 0i64;
+ (0..n)
+ .map(|_| {
+ prev += reader.signed()?;
+ Ok(prev)
+ })
+ .collect()
+}
+
+fn encode_stroke(out: &mut Vec<u8>, stroke: &Stroke) {
+ let channels = stroke.channels();
+ varint::put(out, stroke.id as u64);
+ varint::put(out, stroke.brush.len() as u64);
+ out.extend_from_slice(stroke.brush.as_bytes());
+ stroke
+ .color
+ .iter()
+ .for_each(|c| out.extend_from_slice(&c.to_le_bytes()));
+ [stroke.size, stroke.opacity, stroke.flow]
+ .iter()
+ .for_each(|v| out.extend_from_slice(&v.to_le_bytes()));
+ out.extend_from_slice(&stroke.seed.to_le_bytes());
+ out.push(channels);
+ out.push(match stroke.author {
+ Author::Human => 0,
+ Author::Agent => 1,
+ });
+ if channels & HAS_TAPER != 0 {
+ stroke
+ .taper
+ .iter()
+ .for_each(|v| out.extend_from_slice(&v.to_le_bytes()));
+ }
+ if channels & HAS_CUTS != 0 {
+ cut::encode(out, &stroke.cuts);
+ }
+ if let Some(second) = stroke.second {
+ second.iter().for_each(|c| out.extend_from_slice(&c.to_le_bytes()));
+ }
+ varint::put(out, stroke.samples.len() as u64);
+ let s = &stroke.samples;
+ put_column(out, s.iter().map(|v| v.x as i64));
+ put_column(out, s.iter().map(|v| v.y as i64));
+ put_column(out, s.iter().map(|v| v.pressure as i64));
+ if channels & HAS_TILT != 0 {
+ put_column(out, s.iter().map(|v| v.tilt_x as i64));
+ put_column(out, s.iter().map(|v| v.tilt_y as i64));
+ }
+ if channels & HAS_TIME != 0 {
+ put_column(out, s.iter().map(|v| v.dt_ms as i64));
+ }
+}
+
+fn decode_stroke(reader: &mut Reader, version: u8) -> Result<Stroke> {
+ let id = u32::try_from(reader.varint()?)?;
+ let name_len = reader.varint()? as usize;
+ let brush = String::from_utf8(reader.take(name_len)?.to_vec())?;
+ let color = [reader.u16()?, reader.u16()?, reader.u16()?, reader.u16()?];
+ let size = reader.f32()?;
+ let opacity = reader.f32()?;
+ let flow = reader.f32()?;
+ let seed = reader.u32()?;
+ let channels = reader.u8()?;
+ let author = if version >= 2 && reader.u8()? == 1 {
+ Author::Agent
+ } else {
+ Author::Human
+ };
+ let taper = if version >= 3 && channels & HAS_TAPER != 0 {
+ [reader.f32()?, reader.f32()?]
+ } else {
+ [0.0, 0.0]
+ };
+ let lock = version >= 5 && channels & HAS_LOCK != 0;
+ let cuts = if version >= 5 && channels & HAS_CUTS != 0 {
+ cut::decode(reader)?
+ } else {
+ Vec::new()
+ };
+ let second = if version >= 6 && channels & HAS_SECOND != 0 {
+ Some([reader.u16()?, reader.u16()?, reader.u16()?, reader.u16()?])
+ } else {
+ None
+ };
+ let n = reader.varint()? as usize;
+ let xs = read_column(reader, n)?;
+ let ys = read_column(reader, n)?;
+ let ps = read_column(reader, n)?;
+ let zeros = || vec![0i64; n];
+ let (tx, ty) = if channels & HAS_TILT != 0 {
+ (read_column(reader, n)?, read_column(reader, n)?)
+ } else {
+ (zeros(), zeros())
+ };
+ let dts = if channels & HAS_TIME != 0 {
+ read_column(reader, n)?
+ } else {
+ zeros()
+ };
+ let samples = (0..n)
+ .map(|i| {
+ Ok(Sample {
+ x: i32::try_from(xs[i])?,
+ y: i32::try_from(ys[i])?,
+ pressure: u16::try_from(ps[i])?,
+ tilt_x: i8::try_from(tx[i])?,
+ tilt_y: i8::try_from(ty[i])?,
+ dt_ms: u16::try_from(dts[i])?,
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Stroke {
+ id,
+ brush,
+ color,
+ size,
+ opacity,
+ flow,
+ seed,
+ author,
+ taper,
+ lock,
+ cuts,
+ second,
+ samples,
+ })
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Mark {
+ Stroke(Stroke),
+ Fill(Fill),
+}
+
+impl From<Stroke> for Mark {
+ fn from(stroke: Stroke) -> Self {
+ Mark::Stroke(stroke)
+ }
+}
+
+impl From<Fill> for Mark {
+ fn from(fill: Fill) -> Self {
+ Mark::Fill(fill)
+ }
+}
+
+impl Mark {
+ pub fn id(&self) -> u32 {
+ match self {
+ Mark::Stroke(s) => s.id,
+ Mark::Fill(f) => f.id,
+ }
+ }
+
+ pub fn set_id(&mut self, id: u32) {
+ match self {
+ Mark::Stroke(s) => s.id = id,
+ Mark::Fill(f) => f.id = id,
+ }
+ }
+
+ pub fn author(&self) -> Author {
+ match self {
+ Mark::Stroke(s) => s.author,
+ Mark::Fill(f) => f.author,
+ }
+ }
+
+ pub fn as_stroke(&self) -> Option<&Stroke> {
+ match self {
+ Mark::Stroke(s) => Some(s),
+ Mark::Fill(_) => None,
+ }
+ }
+
+ pub fn as_fill(&self) -> Option<&Fill> {
+ match self {
+ Mark::Fill(f) => Some(f),
+ Mark::Stroke(_) => None,
+ }
+ }
+
+ pub fn bounds(&self) -> Option<[f32; 4]> {
+ let whole = match self {
+ Mark::Stroke(s) => s.bounds().map(|[x0, y0, x1, y1]| {
+ let pad = s.size / 2.0;
+ [x0 - pad, y0 - pad, x1 + pad, y1 + pad]
+ }),
+ Mark::Fill(f) => f.bounds(),
+ }?;
+ cut::clip_bounds(self.cuts(), whole)
+ }
+
+ pub fn cuts(&self) -> &[Cut] {
+ match self {
+ Mark::Stroke(s) => &s.cuts,
+ Mark::Fill(f) => &f.cuts,
+ }
+ }
+
+ pub fn cuts_mut(&mut self) -> &mut Vec<Cut> {
+ match self {
+ Mark::Stroke(s) => &mut s.cuts,
+ Mark::Fill(f) => &mut f.cuts,
+ }
+ }
+
+ pub fn locked(&self) -> bool {
+ match self {
+ Mark::Stroke(s) => s.lock,
+ Mark::Fill(f) => f.lock,
+ }
+ }
+}
+
+pub fn strokes_of(marks: &[Mark]) -> impl Iterator<Item = &Stroke> {
+ marks.iter().filter_map(Mark::as_stroke)
+}
+
+pub fn fills_of(marks: &[Mark]) -> impl Iterator<Item = &Fill> {
+ marks.iter().filter_map(Mark::as_fill)
+}
+
+pub fn next_id(marks: &[Mark]) -> u32 {
+ marks.iter().map(Mark::id).max().map_or(1, |m| m + 1)
+}
+
+fn encode_mark(out: &mut Vec<u8>, mark: &Mark) {
+ match mark {
+ Mark::Stroke(s) => {
+ out.push(MARK_STROKE);
+ encode_stroke(out, s);
+ }
+ Mark::Fill(f) => {
+ out.push(MARK_FILL);
+ fill::encode(out, f);
+ }
+ }
+}
+
+pub fn fingerprint(mark: &Mark) -> u64 {
+ let mut out = Vec::with_capacity(512);
+ encode_mark(&mut out, mark);
+ crate::rng::fnv(crate::rng::FNV_OFFSET, &out)
+}
+
+pub fn encode_raw(marks: &[Mark]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(marks.len() * 256);
+ out.extend_from_slice(MAGIC);
+ out.push(VERSION);
+ varint::put(&mut out, marks.len() as u64);
+ marks.iter().for_each(|mark| encode_mark(&mut out, mark));
+ out
+}
+
+pub fn decode_raw(bytes: &[u8]) -> Result<Vec<Mark>> {
+ let mut reader = Reader::new(bytes);
+ if reader.take(4)? != MAGIC {
+ bail!("not a stroke file");
+ }
+ let version = reader.u8()?;
+ if version == 0 || version > VERSION {
+ bail!("stroke format version {version} is not supported");
+ }
+ let count = reader.varint()? as usize;
+ let marks = (0..count)
+ .map(|_| {
+ if version < 4 {
+ return decode_stroke(&mut reader, version).map(Mark::Stroke);
+ }
+ match reader.u8()? {
+ MARK_STROKE => decode_stroke(&mut reader, version).map(Mark::Stroke),
+ MARK_FILL => fill::decode(&mut reader, version).map(Mark::Fill),
+ other => bail!("unknown mark kind {other}"),
+ }
+ })
+ .collect::<Result<Vec<_>>>()?;
+ if !reader.done() {
+ bail!("trailing bytes after {count} marks");
+ }
+ Ok(marks)
+}
+
+pub fn encode_cel(marks: &[Mark]) -> Result<Vec<u8>> {
+ Ok(zstd::encode_all(&encode_raw(marks)[..], ZSTD_LEVEL)?)
+}
+
+pub fn decode_cel(bytes: &[u8]) -> Result<Vec<Mark>> {
+ decode_raw(&zstd::decode_all(bytes)?)
+}
+
+pub fn marks(strokes: impl IntoIterator<Item = Stroke>) -> Vec<Mark> {
+ strokes.into_iter().map(Mark::Stroke).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fill::{Coverage, FillRef, FillSource, Seed};
+ use crate::synth::Synth;
+
+ fn as_version(stroke: &Stroke, version: u8) -> Vec<u8> {
+ let mut bytes = encode_raw(&[Mark::Stroke(stroke.clone())]);
+ assert_eq!(bytes[6], MARK_STROKE);
+ bytes.remove(6);
+ bytes[4] = version;
+ bytes
+ }
+
+ #[test]
+ fn cel_round_trip_is_exact() {
+ let strokes = marks(Synth::canvas(2048.0, 2048.0).strokes(200, 3));
+ let back = decode_cel(&encode_cel(&strokes).unwrap()).unwrap();
+ assert_eq!(back, strokes);
+ }
+
+ #[test]
+ fn strokes_without_tilt_or_time_round_trip() {
+ let stroke = Stroke::new(9, "ink", [0.1, 0.2, 0.3, 1.0], 12.0, 4)
+ .with_points(&[(1.0, 2.0, 0.5), (3.5, 2.25, 0.75), (-4.0, 9.0, 1.0)], 0.0);
+ let back = decode_raw(&encode_raw(&[stroke.clone().into()])).unwrap();
+ assert_eq!(back, vec![Mark::Stroke(stroke)]);
+ }
+
+ #[test]
+ fn quantisation_is_stable_under_re_quantising() {
+ let s = Sample::quantize(10.37, -4.21, 0.333, (0.5, -0.25), 5.2);
+ let (x, y) = s.pos();
+ let again = Sample::quantize(x, y, s.pressure(), s.tilt(), s.dt_ms as f32);
+ assert_eq!(s, again);
+ }
+
+ #[test]
+ fn authors_survive_and_version_one_files_still_load() {
+ let agent = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1)
+ .with_points(&[(1.0, 1.0, 1.0), (2.0, 2.0, 1.0)], 5.0)
+ .by(Author::Agent);
+ let v2 = as_version(&agent, 2);
+ assert_eq!(decode_raw(&v2).unwrap()[0].author(), Author::Agent);
+ let author_at = 4 + 1 + 1 + 1 + 4 + 8 + 12 + 4 + 1;
+ assert_eq!(v2[author_at], 1);
+ let mut v1 = v2.clone();
+ v1[4] = 1;
+ v1.remove(author_at);
+ let legacy = decode_raw(&v1).unwrap();
+ let Mark::Stroke(legacy) = &legacy[0] else { panic!() };
+ assert_eq!(legacy.author, Author::Human);
+ assert_eq!(legacy.samples, agent.samples);
+ }
+
+ #[test]
+ fn tapers_survive_and_older_files_still_load() {
+ let points = [(1.0, 1.0, 1.0), (9.0, 2.0, 0.5)];
+ let tapered = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1)
+ .with_points(&points, 5.0)
+ .tapered([12.0, 30.0]);
+ let back = decode_raw(&as_version(&tapered, 3)).unwrap();
+ assert_eq!(back[0].as_stroke().unwrap().taper, [12.0, 30.0]);
+ let plain = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&points, 5.0);
+ assert_eq!(decode_raw(&as_version(&plain, 2)).unwrap(), vec![Mark::Stroke(plain)]);
+ }
+
+ #[test]
+ fn strokes_and_fills_keep_their_order() {
+ let strokes = Synth::canvas(256.0, 256.0).strokes(3, 9);
+ let mut mask = vec![0u8; 256 * 256];
+ (40..90).for_each(|y| (30..200).for_each(|x| mask[y * 256 + x] = 255));
+ let fill = Fill::new(
+ 7,
+ [0.9, 0.8, 0.1, 1.0],
+ FillSource::Seed {
+ seed: Seed {
+ x: 50.0,
+ y: 50.0,
+ tolerance: 0.1,
+ gap: 4.0,
+ expand: 2.0,
+ },
+ reference: FillRef::This,
+ },
+ Coverage::from_mask(256, 256, &mask),
+ );
+ let mixed = vec![
+ Mark::Stroke(strokes[0].clone()),
+ Mark::Fill(fill.clone()),
+ Mark::Stroke(strokes[1].clone()),
+ ];
+ let back = decode_cel(&encode_cel(&mixed).unwrap()).unwrap();
+ assert_eq!(back, mixed);
+ assert_eq!(strokes_of(&back).count(), 2);
+ assert_eq!(fills_of(&back).next(), Some(&fill));
+ assert_eq!(back[1].bounds(), Some([30.0, 40.0, 200.0, 90.0]));
+ assert_eq!(next_id(&back), strokes[0].id.max(strokes[1].id).max(7) + 1);
+ }
+
+ #[test]
+ fn locks_and_cuts_round_trip_and_leave_plain_records_alone() {
+ let points = [(1.0, 1.0, 1.0), (90.0, 2.0, 0.5)];
+ let plain = Stroke::new(3, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&points, 5.0);
+ let mut cut = plain.clone();
+ cut.lock = true;
+ cut.cuts = vec![Cut {
+ keep: cut::Keep::Outside,
+ polygon: vec![[40.0, -5.0], [60.0, -5.0], [60.0, 10.0]],
+ }];
+ let back = decode_raw(&encode_raw(&[cut.clone().into(), plain.clone().into()])).unwrap();
+ assert_eq!(back, vec![Mark::Stroke(cut.clone()), Mark::Stroke(plain.clone())]);
+ assert_eq!(&encode_raw(&[plain.clone().into()])[7..], &as_version(&plain, 4)[6..]);
+ let bounds = Mark::Stroke(Stroke {
+ cuts: vec![Cut {
+ keep: cut::Keep::Inside,
+ polygon: vec![[40.0, -5.0], [60.0, -5.0], [60.0, 10.0], [40.0, 10.0]],
+ }],
+ ..plain
+ })
+ .bounds()
+ .unwrap();
+ assert_eq!(bounds, [40.0, -1.0, 60.0, 4.0]);
+ }
+
+ #[test]
+ fn all_zero_pressure_is_pressureless() {
+ let flat =
+ Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&[(1.0, 1.0, 0.0), (5.0, 1.0, 0.0)], 5.0);
+ assert!(flat.pressureless());
+ let light =
+ Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&[(1.0, 1.0, 0.0), (5.0, 1.0, 0.01)], 5.0);
+ assert!(!light.pressureless());
+ }
+
+ #[test]
+ fn corrupt_data_is_an_error() {
+ let mut bytes = encode_raw(&marks(Synth::canvas(512.0, 512.0).strokes(5, 1)));
+ bytes.truncate(bytes.len() - 3);
+ assert!(decode_raw(&bytes).is_err());
+ }
+}
diff --git a/crates/core/src/synth.rs b/crates/core/src/synth.rs
new file mode 100644
index 0000000..86a1502
--- /dev/null
+++ b/crates/core/src/synth.rs
@@ -0,0 +1,142 @@
+use crate::color::Rgba;
+use crate::rng::Rng;
+use crate::stroke::{Sample, Stroke};
+use libm::{cosf, sinf};
+
+#[derive(Clone, Debug)]
+pub struct Synth {
+ pub width: f32,
+ pub height: f32,
+ pub rate_hz: f32,
+ pub min_len: f32,
+ pub max_len: f32,
+ pub sizes: Vec<f32>,
+ pub brushes: Vec<String>,
+ pub palette: Vec<Rgba>,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Gesture {
+ pub start: (f32, f32),
+ pub heading: f32,
+ pub length: f32,
+ pub speed: f32,
+ pub curl: f32,
+ pub pressure: f32,
+ pub attack: f32,
+ pub release: f32,
+ pub tilt: (f32, f32),
+}
+
+impl Synth {
+ pub fn canvas(width: f32, height: f32) -> Self {
+ Self {
+ width,
+ height,
+ rate_hz: 200.0,
+ min_len: 15.0,
+ max_len: 600.0,
+ sizes: vec![4.0, 10.0, 24.0, 60.0],
+ brushes: ["pencil", "ink", "soft", "chalk"].map(String::from).to_vec(),
+ palette: vec![
+ [0.12, 0.10, 0.14, 1.0],
+ [0.85, 0.80, 0.70, 1.0],
+ [0.30, 0.45, 0.62, 1.0],
+ [0.72, 0.35, 0.28, 1.0],
+ [0.40, 0.55, 0.32, 1.0],
+ ],
+ }
+ }
+
+ pub fn strokes(&self, count: usize, seed: u64) -> Vec<Stroke> {
+ let mut rng = Rng::new(seed);
+ (0..count).map(|i| self.stroke(i as u32, &mut rng)).collect()
+ }
+
+ pub fn stroke(&self, id: u32, rng: &mut Rng) -> Stroke {
+ let t = rng.unit();
+ let length = self.min_len + (self.max_len - self.min_len) * t * t;
+ let gesture = Gesture {
+ start: (rng.range(0.0, self.width), rng.range(0.0, self.height)),
+ heading: rng.range(0.0, std::f32::consts::TAU),
+ length,
+ speed: rng.range(300.0, 1500.0),
+ curl: rng.range(0.5, 6.0),
+ pressure: rng.range(0.3, 1.0),
+ attack: rng.range(0.05, 0.3),
+ release: rng.range(0.05, 0.4),
+ tilt: (rng.range(-0.6, 0.6), rng.range(-0.6, 0.6)),
+ };
+ let brush = &self.brushes[rng.below(self.brushes.len())];
+ let size = self.sizes[rng.below(self.sizes.len())] * rng.range(0.7, 1.4);
+ let color = self.palette[rng.below(self.palette.len())];
+ let seed = rng.next_u64() as u32;
+ let mut stroke = Stroke::new(id, brush, color, size, seed);
+ stroke.samples = gesture.samples(self.rate_hz, rng);
+ stroke
+ }
+}
+
+impl Gesture {
+ pub fn samples(&self, rate_hz: f32, rng: &mut Rng) -> Vec<Sample> {
+ let duration = self.length / self.speed;
+ let n = ((duration * rate_hz).ceil() as usize).max(2);
+ let dt = 1.0 / rate_hz;
+ let weights: Vec<f32> = (0..n)
+ .map(|i| 0.3 + 0.7 * sinf(std::f32::consts::PI * (i as f32 + 0.5) / n as f32))
+ .collect();
+ let total: f32 = weights.iter().sum();
+ let mut pos = self.start;
+ let mut heading = self.heading;
+ let mut turn = 0.0f32;
+ let mut tilt = self.tilt;
+ weights
+ .iter()
+ .enumerate()
+ .map(|(i, w)| {
+ let t = i as f32 / (n - 1) as f32;
+ let envelope = (t / self.attack).min(1.0) * ((1.0 - t) / self.release).min(1.0);
+ let pressure = self.pressure * (0.15 + 0.85 * envelope) + rng.signed() * 0.02;
+ let tremor = (rng.signed() * 0.15, rng.signed() * 0.15);
+ let sample = Sample::quantize(
+ pos.0 + tremor.0,
+ pos.1 + tremor.1,
+ pressure,
+ tilt,
+ if i == 0 { 0.0 } else { dt * 1000.0 },
+ );
+ turn = (turn + rng.signed() * self.curl * dt) * 0.97;
+ heading += turn;
+ let step = self.length * w / total;
+ pos = (pos.0 + cosf(heading) * step, pos.1 + sinf(heading) * step);
+ tilt = (
+ (tilt.0 + rng.signed() * 0.01).clamp(-1.0, 1.0),
+ (tilt.1 + rng.signed() * 0.01).clamp(-1.0, 1.0),
+ );
+ sample
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn same_seed_same_strokes() {
+ let synth = Synth::canvas(1024.0, 1024.0);
+ assert_eq!(synth.strokes(50, 11), synth.strokes(50, 11));
+ assert_ne!(synth.strokes(50, 11), synth.strokes(50, 12));
+ }
+
+ #[test]
+ fn strokes_have_tapered_pressure() {
+ let strokes = Synth::canvas(1024.0, 1024.0).strokes(20, 5);
+ assert!(strokes.iter().all(|s| s.samples.len() >= 2));
+ assert!(strokes.iter().filter(|s| s.samples.len() >= 10).all(|s| {
+ let peak = s.samples.iter().map(|v| v.pressure).max().unwrap();
+ s.samples[0].pressure < peak
+ }));
+ }
+}
diff --git a/crates/core/src/timing.rs b/crates/core/src/timing.rs
new file mode 100644
index 0000000..40b618e
--- /dev/null
+++ b/crates/core/src/timing.rs
@@ -0,0 +1,799 @@
+use crate::doc::{Cel, Document, Kind, Layer, LayerContent, Loc, Node, valid_id};
+use crate::ops::Applied;
+use anyhow::{Result, anyhow, bail};
+use std::collections::BTreeSet;
+
+pub const OPEN: u32 = u32::MAX;
+
+pub fn ends(cels: &[Cel]) -> Vec<u32> {
+ cels.iter()
+ .enumerate()
+ .map(|(i, c)| {
+ let next = cels.get(i + 1).map_or(OPEN, |n| n.frame);
+ c.hold.map_or(next, |h| c.frame.saturating_add(h).min(next))
+ })
+ .collect()
+}
+
+pub fn exposure(layer: &Layer, cel: &str) -> Option<(u32, u32)> {
+ let cels = layer.cels();
+ let at = cels.iter().position(|c| c.id == cel)?;
+ Some((cels[at].frame, ends(cels)[at]))
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Shift {
+ Insert { at: u32, count: u32 },
+ Room { at: u32, count: u32 },
+ Remove { at: u32, count: u32 },
+}
+
+impl Shift {
+ pub fn start(self, s: u32) -> u32 {
+ match self {
+ Shift::Insert { at, count } if s > at => s + count,
+ Shift::Room { at, count } if s >= at => s + count,
+ Shift::Remove { at, .. } if s < at => s,
+ Shift::Remove { at, count } if s < at + count => at,
+ Shift::Remove { count, .. } => s - count,
+ _ => s,
+ }
+ }
+
+ pub fn end(self, e: u32) -> u32 {
+ match self {
+ _ if e == OPEN => OPEN,
+ Shift::Insert { at, count } | Shift::Room { at, count } if e > at => e + count,
+ Shift::Remove { at, .. } if e <= at => e,
+ Shift::Remove { at, count } if e <= at + count => at,
+ Shift::Remove { count, .. } => e - count,
+ _ => e,
+ }
+ }
+
+ fn grows(self) -> Option<u32> {
+ match self {
+ Shift::Insert { count, .. } | Shift::Room { count, .. } => Some(count),
+ Shift::Remove { .. } => None,
+ }
+ }
+}
+
+fn remap(cels: &[Cel], shift: Shift) -> (Vec<Cel>, Vec<Cel>) {
+ let moved: Vec<(Cel, u32)> = cels
+ .iter()
+ .zip(ends(cels))
+ .map(|(c, e)| {
+ let start = shift.start(c.frame);
+ (
+ Cel {
+ frame: start,
+ ..c.clone()
+ },
+ shift.end(e),
+ )
+ })
+ .collect();
+ let (kept, gone): (Vec<_>, Vec<_>) = moved.into_iter().partition(|(c, e)| *e > c.frame);
+ let starts: Vec<u32> = kept.iter().map(|(c, _)| c.frame).collect();
+ let kept = kept
+ .into_iter()
+ .enumerate()
+ .map(|(i, (cel, end))| {
+ let next = starts.get(i + 1).copied().unwrap_or(OPEN);
+ let hold = match cel.hold {
+ None if end == next || end == OPEN => None,
+ _ => Some(end - cel.frame),
+ };
+ Cel { hold, ..cel }
+ })
+ .collect();
+ (kept, gone.into_iter().map(|(c, _)| c).collect())
+}
+
+pub fn hand_over(layer: &mut Layer, gone: Vec<Cel>, out: &mut Applied) {
+ let (id, paint) = (layer.id.clone(), layer.kind() == Kind::Paint);
+ let Some(cels) = layer.cels_mut() else {
+ return;
+ };
+ gone.into_iter().filter(|g| g.link.is_none()).for_each(|drawing| {
+ let users: Vec<usize> = cels
+ .iter()
+ .enumerate()
+ .filter(|(_, c)| c.link.as_deref() == Some(drawing.id.as_str()))
+ .map(|(i, _)| i)
+ .collect();
+ if let Some((&heir, rest)) = users.split_first() {
+ let heir_id = cels[heir].id.clone();
+ cels[heir].link = None;
+ rest.iter().for_each(|&i| cels[i].link = Some(heir_id.clone()));
+ if paint {
+ out.copy(&id, &heir_id, &id, &drawing.id);
+ } else {
+ cels[heir].nodes = drawing.nodes;
+ }
+ }
+ if paint {
+ out.dropped_cels.push((id.clone(), drawing.id));
+ }
+ });
+}
+
+fn shift_layer(layer: &mut Layer, shift: Shift, out: &mut Applied) {
+ if let Some(cels) = layer.cels_mut() {
+ let (kept, gone) = remap(cels, shift);
+ *cels = kept;
+ out.removed.extend(gone.iter().map(|c| c.id.clone()));
+ hand_over(layer, gone, out);
+ }
+ if let Some(mask) = layer.mask.as_deref_mut() {
+ shift_layer(mask, shift, out);
+ }
+ if let LayerContent::Group { children } = &mut layer.content {
+ children.iter_mut().for_each(|c| shift_layer(c, shift, out));
+ }
+}
+
+fn reach(layer: &Layer, frames: u32, count: u32) -> u32 {
+ let own = layer.cels().last().map_or(0, |c| match c.hold {
+ None => frames + count,
+ Some(h) => c.frame + h,
+ });
+ layer
+ .mask
+ .iter()
+ .map(|m| reach(m, frames, count))
+ .chain(layer.children().iter().map(|c| reach(c, frames, count)))
+ .fold(own, u32::max)
+}
+
+fn grow_for(doc: &mut Document, paths: &[Vec<usize>], count: u32) {
+ let before = doc.timeline.frames;
+ let need = paths
+ .iter()
+ .map(|p| reach(doc.layer_at(p), before, count))
+ .max()
+ .unwrap_or(0);
+ doc.timeline.frames = before.max(need);
+}
+
+fn layer_path(doc: &Document, key: &str) -> Result<Vec<usize>> {
+ let id = doc.find_layer(key)?.id.clone();
+ match doc.locate(&id) {
+ Some(Loc::Layer(path)) => Ok(path),
+ _ => bail!("{key} is not a layer"),
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct FrameSpec {
+ pub insert: bool,
+ pub at: u32,
+ pub count: u32,
+ pub layers: Option<Vec<String>>,
+}
+
+pub fn frames(doc: &mut Document, spec: &FrameSpec, out: &mut Applied) -> Result<()> {
+ if spec.count == 0 {
+ bail!("count must be at least 1");
+ }
+ let shift = if spec.insert {
+ Shift::Insert {
+ at: spec.at,
+ count: spec.count,
+ }
+ } else {
+ Shift::Remove {
+ at: spec.at,
+ count: spec.count,
+ }
+ };
+ match &spec.layers {
+ None => {
+ doc.layers.iter_mut().for_each(|l| shift_layer(l, shift, out));
+ doc.timeline.clips.retain_mut(|clip| {
+ let (from, end) = (shift.start(clip.from), shift.end(clip.to + 1));
+ clip.from = from;
+ clip.to = end.saturating_sub(1);
+ end > from
+ });
+ doc.timeline.frames = match shift.grows() {
+ Some(count) => doc.timeline.frames + count,
+ None => shift.end(doc.timeline.frames).max(1),
+ };
+ }
+ Some(keys) => {
+ let paths = keys.iter().map(|k| layer_path(doc, k)).collect::<Result<Vec<_>>>()?;
+ let outermost: Vec<Vec<usize>> = paths
+ .iter()
+ .filter(|p| !paths.iter().any(|q| q.len() < p.len() && p.starts_with(q)))
+ .cloned()
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ outermost
+ .iter()
+ .for_each(|path| shift_layer(doc.layer_at_mut(path), shift, out));
+ if let Some(count) = shift.grows() {
+ grow_for(doc, &outermost, count);
+ }
+ }
+ }
+ out.changed.push("timeline".into());
+ Ok(())
+}
+
+pub fn timeline(doc: &mut Document, fps: Option<u32>, frames: Option<u32>) -> Result<()> {
+ if let Some(n) = frames {
+ let late = doc
+ .all_layers()
+ .into_iter()
+ .flat_map(|l| l.cels().iter().map(move |c| (l, c)))
+ .filter(|(_, c)| c.frame >= n)
+ .max_by_key(|(_, c)| c.frame);
+ if let Some((layer, cel)) = late {
+ bail!(
+ "cel {} of layer {} starts at frame {}; keep at least {} frames or remove frames first",
+ cel.id,
+ layer.id,
+ cel.frame,
+ cel.frame + 1
+ );
+ }
+ if let Some(clip) = doc.timeline.clips.iter().find(|c| c.from >= n) {
+ bail!(
+ "clip {} starts at frame {}; keep at least {} frames or remove the clip first",
+ clip.name,
+ clip.from,
+ clip.from + 1
+ );
+ }
+ doc.timeline.clips.iter_mut().for_each(|c| c.to = c.to.min(n - 1));
+ doc.timeline.frames = n;
+ }
+ if let Some(fps) = fps {
+ doc.timeline.fps = fps;
+ }
+ Ok(())
+}
+
+pub fn grow(doc: &mut Document) {
+ let last = doc
+ .all_layers()
+ .iter()
+ .flat_map(|l| l.cels().iter().map(|c| c.frame + 1))
+ .max()
+ .unwrap_or(1);
+ doc.timeline.frames = doc.timeline.frames.max(last);
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CelAction {
+ New { layer: String },
+ Dup { cel: String },
+ Link { cel: String },
+ Unlink { cel: String },
+ Move { cel: String },
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CelSpec {
+ pub action: CelAction,
+ pub id: Option<String>,
+ pub frame: Option<u32>,
+ pub hold: Option<u32>,
+ pub insert: bool,
+}
+
+fn place(layer: &str, cels: &mut Vec<Cel>, mut cel: Cel, hold: Option<u32>, fallback: Option<u32>) -> Result<()> {
+ if let Some(c) = cels.iter().find(|c| c.frame == cel.frame) {
+ bail!("layer {layer} already has {} starting at frame {}", c.id, cel.frame);
+ }
+ let ends = ends(cels);
+ let covering = cels
+ .iter()
+ .zip(&ends)
+ .position(|(c, e)| c.frame < cel.frame && cel.frame < *e);
+ cel.hold = hold;
+ match covering {
+ Some(i) => {
+ if let Some(h) = cels[i].hold {
+ if hold.is_none() {
+ cel.hold = Some(cels[i].frame + h - cel.frame);
+ }
+ cels[i].hold = Some(cel.frame - cels[i].frame);
+ }
+ }
+ None if hold.is_none() => cel.hold = fallback,
+ None => {}
+ }
+ let index = cels.iter().position(|c| c.frame > cel.frame).unwrap_or(cels.len());
+ cels.insert(index, cel);
+ Ok(())
+}
+
+fn make_room(doc: &mut Document, path: &[usize], at: u32, count: u32, out: &mut Applied) -> Result<()> {
+ let layer = doc.layer_at(path);
+ let cels = layer.cels();
+ if let Some((c, _)) = cels.iter().zip(ends(cels)).find(|(c, e)| c.frame < at && at < *e) {
+ bail!(
+ "frame {at} is inside the exposure of {} (from frame {}); insert at the start or end of an exposure, or leave insert off to take over the rest of it",
+ c.id,
+ c.frame
+ );
+ }
+ shift_layer(doc.layer_at_mut(path), Shift::Room { at, count }, out);
+ grow_for(doc, &[path.to_vec()], count);
+ Ok(())
+}
+
+fn move_cel(doc: &mut Document, id: &str, to: u32, out: &mut Applied) -> Result<String> {
+ let (path, c) = cel_loc(doc, id)?;
+ let frames = doc.timeline.frames;
+ let layer_id = doc.layer_at(&path).id.clone();
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer {layer_id} has no cels"))?;
+ let me = cels[c].clone();
+ if me.frame == to {
+ return Ok(id.to_string());
+ }
+ let end = match ends(cels)[c] {
+ OPEN => frames.max(me.frame + 1),
+ e => e,
+ };
+ let length = end - me.frame;
+ if c > 0 && ends(cels)[c - 1] == me.frame && cels[c - 1].hold.is_none() {
+ cels[c - 1].hold = Some(me.frame - cels[c - 1].frame);
+ }
+ cels.remove(c);
+ let e = ends(cels);
+ if let Some(i) = cels.iter().zip(&e).position(|(x, end)| x.frame < to && to < *end) {
+ cels[i].hold = Some(to - cels[i].frame);
+ }
+ let landed = cels.iter().map(|x| x.frame).filter(|f| *f >= to).min();
+ if let Some(at) = landed.filter(|at| *at < to + length) {
+ shift_layer(
+ doc.layer_at_mut(&path),
+ Shift::Room {
+ at,
+ count: to + length - at,
+ },
+ out,
+ );
+ }
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer {layer_id} has no cels"))?;
+ let mut moved = me;
+ moved.frame = to;
+ moved.hold = Some(length);
+ let index = cels.iter().position(|x| x.frame > to).unwrap_or(cels.len());
+ cels.insert(index, moved);
+ grow(doc);
+ out.changed.push(id.to_string());
+ Ok(id.to_string())
+}
+
+pub(crate) fn renumbered(doc: &mut Document, nodes: &[Node]) -> Vec<Node> {
+ fn fresh(doc: &mut Document, taken: &mut BTreeSet<String>, node: &Node) -> Node {
+ let mut copy = node.clone();
+ copy.id = doc.alloc_id_in('n', taken);
+ if let Some(children) = copy.shape.children_mut() {
+ *children = children.iter().map(|c| fresh(doc, taken, c)).collect();
+ }
+ copy
+ }
+ let mut taken = doc.ids();
+ nodes.iter().map(|n| fresh(doc, &mut taken, n)).collect()
+}
+
+fn cel_loc(doc: &Document, id: &str) -> Result<(Vec<usize>, usize)> {
+ match doc.locate(id) {
+ Some(Loc::Cel(path, c)) => Ok((path, c)),
+ Some(_) => bail!("{id} is not a cel"),
+ None => bail!("no cel {id}"),
+ }
+}
+
+fn drawing_layer(doc: &Document, path: &[usize]) -> Result<()> {
+ let layer = doc.layer_at(path);
+ if layer.kind() == Kind::Group {
+ bail!("{} is a group; drawings live in paint and vector layers", layer.id);
+ }
+ Ok(())
+}
+
+pub fn cel(doc: &mut Document, spec: &CelSpec, out: &mut Applied) -> Result<String> {
+ let (path, source, fallback, frame) = match &spec.action {
+ CelAction::New { layer } => {
+ let path = layer_path(doc, layer)?;
+ drawing_layer(doc, &path)?;
+ let frame = spec.frame.ok_or_else(|| anyhow!("a new drawing needs a frame"))?;
+ (path, None, None, frame)
+ }
+ CelAction::Dup { cel } | CelAction::Link { cel } => {
+ let (path, c) = cel_loc(doc, cel)?;
+ let layer = doc.layer_at(&path);
+ let from = &layer.cels()[c];
+ let source = from.link.clone().unwrap_or_else(|| from.id.clone());
+ let end = ends(layer.cels())[c];
+ let after = if end == OPEN {
+ doc.timeline.frames.max(from.frame + 1)
+ } else {
+ end
+ };
+ (path, Some(source), from.hold, spec.frame.unwrap_or(after))
+ }
+ CelAction::Unlink { cel } => return unlink(doc, cel, out),
+ CelAction::Move { cel } => {
+ let to = spec
+ .frame
+ .ok_or_else(|| anyhow!("moving a drawing needs \"frame\": where it goes"))?;
+ return move_cel(doc, cel, to, out);
+ }
+ };
+ if spec.insert {
+ let count = spec.hold.or(fallback).unwrap_or(1);
+ make_room(doc, &path, frame, count, out)?;
+ }
+ let id = match &spec.id {
+ Some(id) if !valid_id(id) => bail!("id {id:?} may only use letters, digits, - and _"),
+ Some(id) if doc.locate(id).is_some() => bail!("id {id} is already used"),
+ Some(id) => id.clone(),
+ None => doc.alloc_id('c'),
+ };
+ let mut cel = Cel::at(&id, frame);
+ let layer_id = doc.layer_at(&path).id.clone();
+ let kind = doc.layer_at(&path).kind();
+ match (&spec.action, &source) {
+ (CelAction::Link { .. }, Some(source)) => cel.link = Some(source.clone()),
+ (CelAction::Dup { .. }, Some(source)) if kind == Kind::Vector => {
+ let nodes = doc
+ .layer_at(&path)
+ .cels()
+ .iter()
+ .find(|c| &c.id == source)
+ .map(|c| c.nodes.clone())
+ .unwrap_or_default();
+ cel.nodes = renumbered(doc, &nodes);
+ }
+ (CelAction::Dup { .. }, Some(source)) => {
+ out.copy(&layer_id, &id, &layer_id, source);
+ cel.parts = doc
+ .layer_at(&path)
+ .cels()
+ .iter()
+ .find(|c| &c.id == source)
+ .map(|c| c.parts.clone())
+ .unwrap_or_default();
+ }
+ _ => {}
+ }
+ let cels = doc
+ .layer_at_mut(&path)
+ .cels_mut()
+ .ok_or_else(|| anyhow!("layer {layer_id} has no cels"))?;
+ place(&layer_id, cels, cel, spec.hold, fallback)?;
+ out.added.push(id.clone());
+ Ok(id)
+}
+
+fn unlink(doc: &mut Document, id: &str, out: &mut Applied) -> Result<String> {
+ let (path, c) = cel_loc(doc, id)?;
+ let layer = doc.layer_at(&path);
+ let layer_id = layer.id.clone();
+ let Some(source) = layer.cels()[c].link.clone() else {
+ bail!("cel {id} is a drawing of its own, not a link");
+ };
+ if layer.kind() == Kind::Paint {
+ out.copy(&layer_id, id, &layer_id, &source);
+ let parts = layer
+ .cels()
+ .iter()
+ .find(|c| c.id == source)
+ .map(|c| c.parts.clone())
+ .unwrap_or_default();
+ if let Some(cels) = doc.layer_at_mut(&path).cels_mut() {
+ cels[c].parts = parts;
+ }
+ } else {
+ let nodes = layer
+ .cels()
+ .iter()
+ .find(|c| c.id == source)
+ .map(|c| c.nodes.clone())
+ .unwrap_or_default();
+ let fresh = renumbered(doc, &nodes);
+ if let Some(cels) = doc.layer_at_mut(&path).cels_mut() {
+ cels[c].nodes = fresh;
+ }
+ }
+ if let Some(cels) = doc.layer_at_mut(&path).cels_mut() {
+ cels[c].link = None;
+ }
+ out.changed.push(id.to_string());
+ Ok(id.to_string())
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Cell {
+ Drawing { cel: String, start: bool },
+ Link { cel: String, source: String, start: bool },
+ Blank,
+}
+
+pub fn cells(layer: &Layer, frames: u32) -> Vec<Cell> {
+ let cels = layer.cels();
+ let ends = ends(cels);
+ (0..frames)
+ .map(|f| {
+ let found = cels
+ .iter()
+ .zip(&ends)
+ .find(|(c, e)| c.frame <= f && f < **e)
+ .map(|(c, _)| c);
+ match found {
+ None => Cell::Blank,
+ Some(c) => match &c.link {
+ Some(source) => Cell::Link {
+ cel: c.id.clone(),
+ source: source.clone(),
+ start: c.frame == f,
+ },
+ None => Cell::Drawing {
+ cel: c.id.clone(),
+ start: c.frame == f,
+ },
+ },
+ }
+ })
+ .collect()
+}
+
+pub fn sheet_layers(doc: &Document) -> Vec<&Layer> {
+ fn walk<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) {
+ layers.iter().rev().for_each(|l| {
+ if l.kind() != Kind::Group {
+ out.push(l);
+ }
+ out.extend(l.mask.as_deref());
+ walk(l.children(), out);
+ });
+ }
+ let mut out = Vec::new();
+ walk(&doc.layers, &mut out);
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::doc::Layer;
+ use crate::doc::Shape;
+ use crate::ops::{Op, apply_all};
+ use serde_json::json;
+
+ fn cel(id: &str, frame: u32, hold: Option<u32>, link: Option<&str>) -> Cel {
+ Cel {
+ hold,
+ link: link.map(String::from),
+ ..Cel::at(id, frame)
+ }
+ }
+
+ fn doc_with(cels: Vec<Cel>, frames: u32) -> Document {
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = frames;
+ let mut layer = Layer::paint("l1", "lines", "c0");
+ *layer.cels_mut().unwrap() = cels;
+ doc.layers = vec![layer];
+ doc.next_id = 100;
+ doc
+ }
+
+ fn sheet(doc: &Document) -> String {
+ cells(doc.layer("l1").unwrap(), doc.timeline.frames)
+ .iter()
+ .map(|c| match c {
+ Cell::Drawing { cel, start: true } => cel.trim_start_matches('c').to_string(),
+ Cell::Link {
+ source, start: true, ..
+ } => format!(">{}", source.trim_start_matches('c')),
+ Cell::Drawing { .. } | Cell::Link { .. } => "|".into(),
+ Cell::Blank => ".".into(),
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+ }
+
+ fn run(doc: &Document, ops: &[serde_json::Value]) -> Result<(Document, Applied)> {
+ let ops: Vec<Op> = ops.iter().map(|v| Op::parse(v.clone())).collect::<Result<_>>()?;
+ apply_all(doc, &ops)
+ }
+
+ fn twos() -> Document {
+ doc_with(
+ vec![
+ cel("c1", 0, Some(2), None),
+ cel("c2", 2, Some(2), None),
+ cel("c3", 4, Some(2), Some("c1")),
+ cel("c4", 6, None, None),
+ ],
+ 8,
+ )
+ }
+
+ #[test]
+ fn inserting_lengthens_the_exposure_and_shifts_what_follows() {
+ let doc = twos();
+ assert_eq!(sheet(&doc), "1 | 2 | >1 | 4 |");
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":2,"count":2})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | | | >1 | 4 |");
+ assert_eq!(doc.timeline.frames, 10);
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":1})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | | 2 | | | >1 | 4 |");
+ }
+
+ #[test]
+ fn removing_shortens_exposures_and_drops_drawings_left_without_frames() {
+ let (doc, _) = run(&twos(), &[json!({"op":"frames","remove":1,"count":2})]).unwrap();
+ assert_eq!(sheet(&doc), "1 2 >1 | 4 |");
+ let (doc, applied) = run(&twos(), &[json!({"op":"frames","remove":2,"count":2})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | >1 | 4 |");
+ assert_eq!(doc.timeline.frames, 6);
+ assert_eq!(applied.removed, ["c2"]);
+ assert_eq!(applied.dropped_cels, [("l1".to_string(), "c2".to_string())]);
+ let (doc, _) = run(&twos(), &[json!({"op":"frames","remove":7})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | >1 | 4");
+ }
+
+ #[test]
+ fn a_removed_drawing_goes_to_its_first_link() {
+ let (doc, applied) = run(&twos(), &[json!({"op":"frames","remove":0,"count":2})]).unwrap();
+ assert_eq!(sheet(&doc), "2 | 3 | 4 |");
+ assert_eq!(doc.layer("l1").unwrap().cels()[1].link, None);
+ assert_eq!(applied.dropped_cels, [("l1".to_string(), "c1".to_string())]);
+ let copy = &applied.marks[0];
+ assert_eq!((copy.layer.as_str(), copy.cel.as_str()), ("l1", "c3"));
+ let (doc, _) = run(&twos(), &[json!({"op":"rm","id":"c1"})]).unwrap();
+ assert_eq!(sheet(&doc), ". . 2 | 3 | 4 |");
+ }
+
+ #[test]
+ fn a_hold_ending_where_a_removed_drawing_was_keeps_its_blank() {
+ let doc = doc_with(
+ vec![
+ cel("c1", 0, None, None),
+ cel("c2", 2, Some(1), None),
+ cel("c3", 5, None, None),
+ ],
+ 7,
+ );
+ assert_eq!(sheet(&doc), "1 | 2 . . 3 |");
+ let (doc, _) = run(&doc, &[json!({"op":"frames","remove":2})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | . . 3 |");
+ }
+
+ #[test]
+ fn new_drawings_take_over_the_rest_of_an_exposure() {
+ let (doc, applied) = run(&twos(), &[json!({"op":"cel","new":"l1","frame":3})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 101 >1 | 4 |");
+ assert_eq!(applied.added, ["c101"]);
+ let (doc, _) = run(&twos(), &[json!({"op":"cel","new":"l1","frame":7})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | >1 | 4 101");
+ let taken = run(&twos(), &[json!({"op":"cel","new":"l1","frame":2})]);
+ assert!(format!("{:#}", taken.unwrap_err()).contains("already has c2"));
+ let (doc, _) = run(&twos(), &[json!({"op":"cel","new":"l1","frame":11})]).unwrap();
+ assert_eq!(doc.timeline.frames, 12);
+ }
+
+ #[test]
+ fn dup_and_link_land_after_their_source_and_can_make_room() {
+ let (doc, applied) = run(&twos(), &[json!({"op":"cel","dup":"c2","insert":true})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | 101 | >1 | 4 |");
+ assert_eq!(doc.timeline.frames, 10);
+ let copy = &applied.marks[0];
+ assert_eq!(copy.cel, "c101");
+ let (doc, _) = run(&twos(), &[json!({"op":"cel","link":"c3","frame":7})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | >1 | 4 >1");
+ let inside = run(&twos(), &[json!({"op":"cel","dup":"c2","frame":3,"insert":true})]);
+ assert!(format!("{:#}", inside.unwrap_err()).contains("inside the exposure"));
+ }
+
+ #[test]
+ fn unlink_makes_a_copy_of_the_source() {
+ let (doc, applied) = run(&twos(), &[json!({"op":"cel","unlink":"c3"})]).unwrap();
+ assert_eq!(sheet(&doc), "1 | 2 | 3 | 4 |");
+ assert_eq!(applied.marks[0].cel, "c3");
+ let own = run(&twos(), &[json!({"op":"cel","unlink":"c2"})]);
+ assert!(format!("{:#}", own.unwrap_err()).contains("not a link"));
+ }
+
+ #[test]
+ fn vector_drawings_copy_nodes_with_new_ids() {
+ let mut doc = Document::new(64, 64);
+ doc.timeline.frames = 4;
+ let node = Node::new(
+ "n1",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 4.0,
+ h: 4.0,
+ radius: 0.0,
+ },
+ );
+ doc.layers = vec![Layer::vector("l1", "shapes", "c1", vec![node])];
+ doc.next_id = 10;
+ let (doc, _) = run(&doc, &[json!({"op":"cel","dup":"c1","frame":2})]).unwrap();
+ let cels = doc.layer("l1").unwrap().cels();
+ assert_eq!(cels[1].nodes.len(), 1);
+ assert_ne!(cels[1].nodes[0].id, "n1");
+ doc.validate().unwrap();
+ }
+
+ #[test]
+ fn listed_layers_shift_alone_and_masks_follow() {
+ let mut doc = twos();
+ doc.layers.push(Layer::paint("l2", "colour", "c9"));
+ doc.layers[1].mask = Some(Box::new(Layer::paint("l3", "mask", "c8")));
+ doc.layers[1].cels_mut().unwrap()[0].frame = 2;
+ doc.layers[1].mask.as_mut().unwrap().cels_mut().unwrap()[0].frame = 2;
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":0,"count":3,"layers":["l2"]})]).unwrap();
+ assert_eq!(doc.layer("l2").unwrap().cels()[0].frame, 5);
+ assert_eq!(doc.layer("l3").unwrap().cels()[0].frame, 5);
+ assert_eq!(sheet(&doc), "1 | 2 | >1 | 4 | | | |");
+ assert_eq!(doc.timeline.frames, 11);
+ }
+
+ #[test]
+ fn a_listed_layer_lengthens_the_timeline_only_as_far_as_it_needs() {
+ let mut doc = twos();
+ let mut blink = Layer::paint("l2", "blink", "c9");
+ blink.cels_mut().unwrap()[0].hold = Some(3);
+ doc.layers.push(blink);
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":1,"layers":["l2"]})]).unwrap();
+ assert_eq!(doc.timeline.frames, 8);
+ assert_eq!(doc.layer("l2").unwrap().cels()[0].hold, Some(4));
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":2,"count":6,"layers":["l2"]})]).unwrap();
+ assert_eq!(doc.timeline.frames, 10);
+ let (doc, _) = run(&doc, &[json!({"op":"frames","insert":0,"layers":["l1"]})]).unwrap();
+ assert_eq!(doc.timeline.frames, 11);
+ }
+
+ #[test]
+ fn clips_shift_with_all_layers_and_go_when_removed() {
+ let mut doc = twos();
+ doc.timeline.clips = vec![
+ crate::doc::Clip::new("a", 0, 1, false),
+ crate::doc::Clip::new("b", 4, 7, true),
+ ];
+ let (grown, _) = run(&doc, &[json!({"op":"frames","insert":5,"count":2})]).unwrap();
+ assert_eq!((grown.timeline.clips[1].from, grown.timeline.clips[1].to), (4, 9));
+ let (shrunk, _) = run(&doc, &[json!({"op":"frames","remove":0,"count":2})]).unwrap();
+ assert_eq!(shrunk.timeline.clips.len(), 1);
+ assert_eq!((shrunk.timeline.clips[0].from, shrunk.timeline.clips[0].to), (2, 5));
+ }
+
+ #[test]
+ fn timeline_sets_fps_and_refuses_to_cut_cels() {
+ let (doc, _) = run(&twos(), &[json!({"op":"timeline","fps":24,"frames":12})]).unwrap();
+ assert_eq!((doc.timeline.fps, doc.timeline.frames), (24, 12));
+ let cut = run(&twos(), &[json!({"op":"timeline","frames":5})]);
+ assert!(format!("{:#}", cut.unwrap_err()).contains("c4"));
+ }
+
+ #[test]
+ fn strokes_past_the_end_grow_the_timeline() {
+ let doc = doc_with(vec![cel("c1", 0, None, None)], 1);
+ let (doc, _) = run(
+ &doc,
+ &[json!({"op":"stroke","layer":"l1","frame":5,"path":"M0 0 L9 9"})],
+ )
+ .unwrap();
+ assert_eq!(doc.timeline.frames, 6);
+ }
+}
diff --git a/crates/core/src/tween.rs b/crates/core/src/tween.rs
new file mode 100644
index 0000000..743c23d
--- /dev/null
+++ b/crates/core/src/tween.rs
@@ -0,0 +1,1489 @@
+use crate::fill::{Coverage, Fill, FillSource};
+use crate::markedit::Affine;
+use crate::stroke::{Author, Mark, Sample, Stroke, fingerprint};
+use anyhow::{Result, anyhow, bail};
+use std::collections::BTreeMap;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Match {
+ #[default]
+ Id,
+ Order,
+ Near,
+}
+
+impl Match {
+ pub fn parse(text: &str) -> Result<Self> {
+ Ok(match text {
+ "" | "id" => Match::Id,
+ "order" => Match::Order,
+ "near" => Match::Near,
+ other => bail!("match takes id, order or near, not {other:?}"),
+ })
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Match::Id => "id",
+ Match::Order => "order",
+ Match::Near => "near",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub enum Unpaired {
+ #[default]
+ Leave,
+ Pop(f32),
+ Fade,
+ DrawOn,
+}
+
+impl Unpaired {
+ pub fn parse(text: &str) -> Result<Self> {
+ let mut words = text.split_whitespace();
+ let mode = match (words.next().unwrap_or(""), words.next()) {
+ ("" | "leave", None) => Unpaired::Leave,
+ ("pop", None) => Unpaired::Pop(0.5),
+ ("pop", Some(at)) => {
+ let at: f32 = at
+ .parse()
+ .map_err(|_| anyhow!("pop takes the moment it happens, 0 to 1, not {at:?}"))?;
+ if !(0.0..=1.0).contains(&at) {
+ bail!("pop happens between 0 and 1, not at {at}");
+ }
+ Unpaired::Pop(at)
+ }
+ ("fade", None) => Unpaired::Fade,
+ ("draw-on", None) => Unpaired::DrawOn,
+ _ => bail!("unpaired takes leave, pop, fade or draw-on (pop may take a moment: pop 0.3), not {text:?}"),
+ };
+ if words.next().is_some() {
+ bail!("unpaired takes one mode, not {text:?}");
+ }
+ Ok(mode)
+ }
+
+ pub fn name(&self) -> String {
+ match self {
+ Unpaired::Leave => String::new(),
+ Unpaired::Pop(at) if *at == 0.5 => "pop".into(),
+ Unpaired::Pop(at) => format!("pop {at}"),
+ Unpaired::Fade => "fade".into(),
+ Unpaired::DrawOn => "draw-on".into(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub enum Spacing {
+ #[default]
+ Even,
+ In,
+ Out,
+ InOut,
+ Values(Vec<f32>),
+}
+
+impl Spacing {
+ pub fn parse(text: &str) -> Result<Self> {
+ Ok(match text.trim() {
+ "" | "even" => Spacing::Even,
+ "in" => Spacing::In,
+ "out" => Spacing::Out,
+ "in-out" | "inout" => Spacing::InOut,
+ list => {
+ let values: Vec<f32> = list
+ .split(',')
+ .map(|v| {
+ v.trim()
+ .parse::<f32>()
+ .map_err(|_| anyhow!("spacing {v:?} is not a number"))
+ })
+ .collect::<Result<_>>()?;
+ if values.iter().any(|v| !(*v > 0.0 && *v < 1.0)) {
+ bail!("spacing values must lie between 0 and 1 (the keys), for example 0.25,0.5,0.75");
+ }
+ if values.windows(2).any(|w| w[1] <= w[0]) {
+ bail!("spacing values must grow from the first key to the second");
+ }
+ Spacing::Values(values)
+ }
+ })
+ }
+
+ pub fn count(&self) -> Option<usize> {
+ match self {
+ Spacing::Values(v) => Some(v.len()),
+ _ => None,
+ }
+ }
+
+ pub fn ts(&self, count: usize) -> Vec<f32> {
+ let s = |i: usize| (i + 1) as f64 / (count + 1) as f64;
+ (0..count)
+ .map(|i| {
+ let x = s(i);
+ (match self {
+ Spacing::Even => x,
+ Spacing::In => x * x,
+ Spacing::Out => 1.0 - (1.0 - x) * (1.0 - x),
+ Spacing::InOut => x * x * (3.0 - 2.0 * x),
+ Spacing::Values(v) => v[i] as f64,
+ }) as f32
+ })
+ .collect()
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+struct P {
+ x: f64,
+ y: f64,
+ p: f64,
+ tx: f64,
+ ty: f64,
+ time: f64,
+}
+
+fn lerp(a: f64, b: f64, t: f64) -> f64 {
+ a + (b - a) * t
+}
+
+fn mix(a: &P, b: &P, t: f64) -> P {
+ P {
+ x: lerp(a.x, b.x, t),
+ y: lerp(a.y, b.y, t),
+ p: lerp(a.p, b.p, t),
+ tx: lerp(a.tx, b.tx, t),
+ ty: lerp(a.ty, b.ty, t),
+ time: lerp(a.time, b.time, t),
+ }
+}
+
+fn points_of(stroke: &Stroke) -> Vec<P> {
+ let mut time = 0.0;
+ stroke
+ .samples
+ .iter()
+ .map(|s| {
+ time += s.dt_ms as f64;
+ let (x, y) = s.pos();
+ let (tx, ty) = s.tilt();
+ P {
+ x: x as f64,
+ y: y as f64,
+ p: s.pressure() as f64,
+ tx: tx as f64,
+ ty: ty as f64,
+ time,
+ }
+ })
+ .collect()
+}
+
+fn dist(a: (f64, f64), b: (f64, f64)) -> f64 {
+ libm::sqrt((a.0 - b.0) * (a.0 - b.0) + (a.1 - b.1) * (a.1 - b.1))
+}
+
+fn walked(points: &[P]) -> Vec<f64> {
+ let mut total = 0.0;
+ points
+ .iter()
+ .enumerate()
+ .map(|(i, p)| {
+ if i > 0 {
+ total += dist((points[i - 1].x, points[i - 1].y), (p.x, p.y));
+ }
+ total
+ })
+ .collect()
+}
+
+fn resample(points: &[P], n: usize) -> Vec<P> {
+ match (points.len(), n) {
+ (0, _) | (_, 0) => Vec::new(),
+ (1, n) => vec![points[0]; n],
+ (_, 1) => vec![points[0]],
+ _ => {
+ let along = walked(points);
+ let total = along[along.len() - 1];
+ if total < 1e-9 {
+ return (0..n)
+ .map(|i| mix(&points[0], &points[points.len() - 1], i as f64 / (n - 1) as f64))
+ .collect();
+ }
+ let mut seg = 0;
+ (0..n)
+ .map(|i| {
+ let at = total * i as f64 / (n - 1) as f64;
+ while seg + 2 < points.len() && along[seg + 1] < at {
+ seg += 1;
+ }
+ let span = along[seg + 1] - along[seg];
+ let t = if span < 1e-12 {
+ 0.0
+ } else {
+ ((at - along[seg]) / span).clamp(0.0, 1.0)
+ };
+ mix(&points[seg], &points[seg + 1], t)
+ })
+ .collect()
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Sim {
+ m: (f64, f64),
+ c: (f64, f64),
+}
+
+const SAME: Sim = Sim {
+ m: (1.0, 0.0),
+ c: (0.0, 0.0),
+};
+
+fn cmul(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
+ (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)
+}
+
+fn cdiv(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
+ let d = b.0 * b.0 + b.1 * b.1;
+ ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)
+}
+
+fn fit(a: &[(f64, f64)], b: &[(f64, f64)]) -> Sim {
+ let n = a.len().max(1) as f64;
+ let centre = |v: &[(f64, f64)]| {
+ let (sx, sy) = v.iter().fold((0.0, 0.0), |(x, y), p| (x + p.0, y + p.1));
+ (sx / n, sy / n)
+ };
+ let (ca, cb) = (centre(a), centre(b));
+ let (dot, cross, norm) = a.iter().zip(b).fold((0.0, 0.0, 0.0), |(d, c, s), (p, q)| {
+ let (ax, ay, bx, by) = (p.0 - ca.0, p.1 - ca.1, q.0 - cb.0, q.1 - cb.1);
+ (d + ax * bx + ay * by, c + ax * by - ay * bx, s + ax * ax + ay * ay)
+ });
+ let m = if norm < 1e-6 || (dot.abs() < 1e-9 && cross.abs() < 1e-9) {
+ (1.0, 0.0)
+ } else {
+ (dot / norm, cross / norm)
+ };
+ let turned = cmul(m, ca);
+ Sim {
+ m,
+ c: (cb.0 - turned.0, cb.1 - turned.1),
+ }
+}
+
+impl Sim {
+ fn apply(&self, p: (f64, f64)) -> (f64, f64) {
+ let q = cmul(self.m, p);
+ (q.0 + self.c.0, q.1 + self.c.1)
+ }
+
+ fn then(&self, inner: &Sim) -> Sim {
+ let c = cmul(self.m, inner.c);
+ Sim {
+ m: cmul(self.m, inner.m),
+ c: (c.0 + self.c.0, c.1 + self.c.1),
+ }
+ }
+
+ fn inverse(&self) -> Sim {
+ let m = cdiv((1.0, 0.0), self.m);
+ let c = cmul(m, self.c);
+ Sim { m, c: (-c.0, -c.1) }
+ }
+
+ fn arc(&self, t: f64) -> Sim {
+ let scale = libm::pow(libm::sqrt(self.m.0 * self.m.0 + self.m.1 * self.m.1), t);
+ let angle = libm::atan2(self.m.1, self.m.0) * t;
+ let m = (scale * libm::cos(angle), scale * libm::sin(angle));
+ let gap = (1.0 - self.m.0, -self.m.1);
+ let ratio = match gap.0 * gap.0 + gap.1 * gap.1 < 1e-12 {
+ true => (t, 0.0),
+ false => cdiv((1.0 - m.0, -m.1), gap),
+ };
+ Sim {
+ m,
+ c: cmul(self.c, ratio),
+ }
+ }
+
+ fn affine(&self) -> [f64; 6] {
+ [self.m.0, -self.m.1, self.m.1, self.m.0, self.c.0, self.c.1]
+ }
+}
+
+fn affine32(a: [f64; 6]) -> Affine {
+ a.map(|v| v as f32)
+}
+
+fn xy(points: &[P]) -> Vec<(f64, f64)> {
+ points.iter().map(|p| (p.x, p.y)).collect()
+}
+
+pub type Lines = Vec<Vec<(f32, f32)>>;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Anchor {
+ pub line: usize,
+ u: f64,
+ along: f64,
+ across: f64,
+}
+
+fn frame_at(line: &[(f64, f64)], u: f64) -> Option<((f64, f64), (f64, f64))> {
+ match line.len() {
+ 0 => None,
+ 1 => Some((line[0], (1.0, 0.0))),
+ _ => {
+ let pts: Vec<P> = line.iter().map(|&(x, y)| P { x, y, ..P::default() }).collect();
+ let along = walked(&pts);
+ let total = along[along.len() - 1];
+ let at = total * u.clamp(0.0, 1.0);
+ let seg = (0..line.len() - 1)
+ .find(|&i| along[i + 1] >= at)
+ .unwrap_or(line.len() - 2);
+ let span = (along[seg + 1] - along[seg]).max(1e-12);
+ let t = ((at - along[seg]) / span).clamp(0.0, 1.0);
+ let (a, b) = (line[seg], line[seg + 1]);
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let len = libm::sqrt(dx * dx + dy * dy);
+ let tangent = if len < 1e-12 { (1.0, 0.0) } else { (dx / len, dy / len) };
+ Some(((a.0 + dx * t, a.1 + dy * t), tangent))
+ }
+ }
+}
+
+fn nearest_on(line: &[(f64, f64)], at: (f64, f64), hint: Option<f64>) -> Option<(f64, f64)> {
+ match line.len() {
+ 0 => None,
+ 1 => Some((0.0, dist(line[0], at))),
+ _ => {
+ let pts: Vec<P> = line.iter().map(|&(x, y)| P { x, y, ..P::default() }).collect();
+ let along = walked(&pts);
+ let total = along[along.len() - 1].max(1e-12);
+ let found: Vec<(f64, f64)> = line
+ .windows(2)
+ .enumerate()
+ .map(|(i, w)| {
+ let (a, b) = (w[0], w[1]);
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let span = dx * dx + dy * dy;
+ let t = if span < 1e-12 {
+ 0.0
+ } else {
+ (((at.0 - a.0) * dx + (at.1 - a.1) * dy) / span).clamp(0.0, 1.0)
+ };
+ let p = (a.0 + dx * t, a.1 + dy * t);
+ ((along[i] + (along[i + 1] - along[i]) * t) / total, dist(p, at))
+ })
+ .collect();
+ let best = found.iter().map(|f| f.1).fold(f64::MAX, f64::min);
+ found
+ .into_iter()
+ .filter(|f| f.1 <= best + 1.0)
+ .min_by(|x, y| match hint {
+ Some(u) => (x.0 - u).abs().total_cmp(&(y.0 - u).abs()),
+ None => x.1.total_cmp(&y.1),
+ })
+ }
+ }
+}
+
+fn anchor_on(line: &[(f64, f64)], index: usize, at: (f64, f64)) -> Option<(Anchor, f64)> {
+ anchor_near(line, index, at, None)
+}
+
+fn anchor_near(line: &[(f64, f64)], index: usize, at: (f64, f64), hint: Option<f64>) -> Option<(Anchor, f64)> {
+ let (u, d) = nearest_on(line, at, hint)?;
+ let (p, tangent) = frame_at(line, u)?;
+ let (ox, oy) = (at.0 - p.0, at.1 - p.1);
+ Some((
+ Anchor {
+ line: index,
+ u,
+ along: ox * tangent.0 + oy * tangent.1,
+ across: -ox * tangent.1 + oy * tangent.0,
+ },
+ d,
+ ))
+}
+
+pub fn anchor(lines: &[Vec<(f32, f32)>], at: (f32, f32)) -> Option<Anchor> {
+ let at = (at.0 as f64, at.1 as f64);
+ lines
+ .iter()
+ .enumerate()
+ .filter_map(|(i, line)| {
+ let line: Vec<(f64, f64)> = line.iter().map(|&(x, y)| (x as f64, y as f64)).collect();
+ anchor_on(&line, i, at)
+ })
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(a, _)| a)
+}
+
+fn place_on(line: &[(f64, f64)], a: &Anchor) -> Option<(f64, f64)> {
+ let (p, tangent) = frame_at(line, a.u)?;
+ Some((
+ p.0 + a.along * tangent.0 - a.across * tangent.1,
+ p.1 + a.along * tangent.1 + a.across * tangent.0,
+ ))
+}
+
+pub fn place(anchor: &Anchor, lines: &[Vec<(f32, f32)>]) -> Option<(f32, f32)> {
+ let line: Vec<(f64, f64)> = lines
+ .get(anchor.line)?
+ .iter()
+ .map(|&(x, y)| (x as f64, y as f64))
+ .collect();
+ place_on(&line, anchor).map(|(x, y)| (x as f32, y as f32))
+}
+
+fn points_of_mark(mark: &Mark) -> Vec<(f32, f32)> {
+ match mark {
+ Mark::Stroke(s) => s.samples.iter().map(Sample::pos).collect(),
+ Mark::Fill(f) => match &f.source {
+ FillSource::Polygon(points) => points.iter().map(|p| (p[0], p[1])).collect(),
+ FillSource::Seed { seed, .. } => vec![(seed.x, seed.y)],
+ },
+ }
+}
+
+fn wide(line: &[(f32, f32)]) -> Vec<(f64, f64)> {
+ line.iter().map(|&(x, y)| (x as f64, y as f64)).collect()
+}
+
+pub fn carry(mark: &Mark, from: &Lines, to: &Lines, within: Option<&[usize]>) -> Mark {
+ let pts = points_of_mark(mark);
+ if pts.is_empty() {
+ return mark.clone();
+ }
+ let n = pts.len() as f64;
+ let centre = pts
+ .iter()
+ .fold((0.0, 0.0), |a, p| (a.0 + p.0 as f64 / n, a.1 + p.1 as f64 / n));
+ let nearest = from
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| within.is_none_or(|w| w.contains(i)) && to.get(*i).is_some_and(|l| !l.is_empty()))
+ .filter_map(|(i, line)| anchor_on(&wide(line), i, centre).map(|(_, d)| (i, d)))
+ .min_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)))
+ .map(|(i, _)| i);
+ let Some(line) = nearest else {
+ return mark.clone();
+ };
+ let (src, dst) = (wide(&from[line]), wide(&to[line]));
+ let mv = |(x, y): (f32, f32)| -> (f32, f32) {
+ anchor_on(&src, line, (x as f64, y as f64))
+ .and_then(|(a, _)| place_on(&dst, &a))
+ .map_or((x, y), |(x, y)| (x as f32, y as f32))
+ };
+ let mut out = mark.clone();
+ match &mut out {
+ Mark::Stroke(s) => s.samples.iter_mut().for_each(|q| {
+ let (x, y) = mv(q.pos());
+ q.x = (x * crate::stroke::POS_SCALE).round() as i32;
+ q.y = (y * crate::stroke::POS_SCALE).round() as i32;
+ }),
+ Mark::Fill(f) => match &mut f.source {
+ FillSource::Polygon(points) => points.iter_mut().for_each(|p| {
+ let (x, y) = mv((p[0], p[1]));
+ *p = [x, y];
+ }),
+ FillSource::Seed { seed, .. } => {
+ (seed.x, seed.y) = mv((seed.x, seed.y));
+ }
+ },
+ }
+ out
+}
+
+fn drawn_part(stroke: &Stroke, share: f32, from_start: bool) -> Option<Stroke> {
+ if share <= 0.0 || stroke.samples.len() < 2 {
+ return (share >= 1.0).then(|| stroke.clone());
+ }
+ if share >= 1.0 {
+ return Some(stroke.clone());
+ }
+ let pts: Vec<P> = points_of(stroke);
+ let along = walked(&pts);
+ let total = along[along.len() - 1];
+ let keep: Vec<Sample> = stroke
+ .samples
+ .iter()
+ .zip(&along)
+ .filter(|(_, d)| match from_start {
+ true => **d <= total * share as f64,
+ false => **d >= total * (1.0 - share as f64),
+ })
+ .map(|(q, _)| *q)
+ .collect();
+ (keep.len() >= 2).then(|| Stroke {
+ samples: keep,
+ ..stroke.clone()
+ })
+}
+
+fn shown(mark: &Mark, t: f32, how: Unpaired, first: bool) -> Option<Mark> {
+ let presence = if first { 1.0 - t } else { t };
+ match (how, mark) {
+ (Unpaired::Leave, _) => None,
+ (Unpaired::Pop(at), _) => (if first { t < at } else { t >= at }).then(|| mark.clone()),
+ (Unpaired::Fade, Mark::Stroke(s)) => Some(Mark::Stroke(Stroke {
+ opacity: s.opacity * presence,
+ ..s.clone()
+ })),
+ (Unpaired::Fade, Mark::Fill(f)) => Some(Mark::Fill(Fill {
+ opacity: f.opacity * presence,
+ ..f.clone()
+ })),
+ (Unpaired::DrawOn, Mark::Stroke(s)) => drawn_part(s, presence, true).map(Mark::Stroke),
+ (Unpaired::DrawOn, Mark::Fill(_)) => (presence >= 0.5).then(|| mark.clone()),
+ }
+}
+
+pub fn line_of(stroke: &Stroke) -> Vec<(f32, f32)> {
+ stroke.samples.iter().map(Sample::pos).collect()
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Pair {
+ pub a: u32,
+ pub b: u32,
+ pub reversed: bool,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Pairing {
+ pub pairs: Vec<Pair>,
+ pub alone_a: Vec<u32>,
+ pub alone_b: Vec<u32>,
+ pub clashes: Vec<(u32, u32)>,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Sort {
+ Stroke,
+ Polygon,
+ Flood,
+}
+
+fn sort_of(mark: &Mark) -> Sort {
+ match mark {
+ Mark::Stroke(_) => Sort::Stroke,
+ Mark::Fill(f) => match f.source {
+ FillSource::Polygon(_) => Sort::Polygon,
+ FillSource::Seed { .. } => Sort::Flood,
+ },
+ }
+}
+
+fn outline(mark: &Mark) -> Vec<P> {
+ match mark {
+ Mark::Stroke(s) => points_of(s),
+ Mark::Fill(f) => match &f.source {
+ FillSource::Polygon(points) => points
+ .iter()
+ .chain(points.first())
+ .map(|p| P {
+ x: p[0] as f64,
+ y: p[1] as f64,
+ ..P::default()
+ })
+ .collect(),
+ FillSource::Seed { seed, .. } => vec![P {
+ x: seed.x as f64,
+ y: seed.y as f64,
+ ..P::default()
+ }],
+ },
+ }
+}
+
+fn shape_cost(a: &Mark, b: &Mark) -> (f64, bool) {
+ let (pa, pb) = (resample(&outline(a), 16), resample(&outline(b), 16));
+ let mean = |q: &[P]| pa.iter().zip(q).map(|(x, y)| dist((x.x, x.y), (y.x, y.y))).sum::<f64>() / 16.0;
+ let forward = mean(&pb);
+ let back: Vec<P> = pb.iter().rev().copied().collect();
+ let backward = mean(&back);
+ match a.as_stroke().is_some() && backward < forward {
+ true => (backward, true),
+ false => (forward, false),
+ }
+}
+
+pub type Groups = [(Vec<u32>, Vec<u32>)];
+
+fn nearest(free_a: &[&Mark], free_b: &[&Mark], xs: &[u32], ys: &[u32]) -> Vec<(u32, u32, bool)> {
+ let mut costs: Vec<(f64, u32, u32, bool)> = free_a
+ .iter()
+ .filter(|x| xs.contains(&x.id()))
+ .flat_map(|x| {
+ free_b
+ .iter()
+ .filter(|y| ys.contains(&y.id()) && sort_of(x) == sort_of(y))
+ .map(|y| {
+ let (cost, rev) = shape_cost(x, y);
+ (cost, x.id(), y.id(), rev)
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ costs.sort_by(|p, q| p.0.total_cmp(&q.0).then(p.1.cmp(&q.1)).then(p.2.cmp(&q.2)));
+ let mut used_a = Vec::new();
+ let mut used_b = Vec::new();
+ costs
+ .into_iter()
+ .filter(|(_, x, y, _)| {
+ let fresh = !used_a.contains(x) && !used_b.contains(y);
+ if fresh {
+ used_a.push(*x);
+ used_b.push(*y);
+ }
+ fresh
+ })
+ .map(|(_, x, y, rev)| (x, y, rev))
+ .collect()
+}
+
+pub fn pair(a: &[Mark], b: &[Mark], how: Match, forced: &[[u32; 2]]) -> Pairing {
+ pair_parts(a, b, how, forced, &[])
+}
+
+pub fn pair_parts(a: &[Mark], b: &[Mark], how: Match, forced: &[[u32; 2]], parts: &Groups) -> Pairing {
+ let mut out = Pairing::default();
+ let mut free_a: Vec<&Mark> = a.iter().collect();
+ let mut free_b: Vec<&Mark> = b.iter().collect();
+ let take = |out: &mut Pairing, free_a: &mut Vec<&Mark>, free_b: &mut Vec<&Mark>, x: u32, y: u32, rev: bool| {
+ let (Some(i), Some(j)) = (
+ free_a.iter().position(|m| m.id() == x),
+ free_b.iter().position(|m| m.id() == y),
+ ) else {
+ return;
+ };
+ if sort_of(free_a[i]) != sort_of(free_b[j]) {
+ out.clashes.push((x, y));
+ } else {
+ out.pairs.push(Pair {
+ a: x,
+ b: y,
+ reversed: rev,
+ });
+ }
+ free_a.remove(i);
+ free_b.remove(j);
+ };
+ forced
+ .iter()
+ .for_each(|[x, y]| take(&mut out, &mut free_a, &mut free_b, *x, *y, false));
+ parts.iter().for_each(|(xs, ys)| {
+ [Sort::Stroke, Sort::Polygon, Sort::Flood].iter().for_each(|sort| {
+ let mine = |free: &[&Mark], ids: &[u32]| -> Vec<u32> {
+ free.iter()
+ .filter(|m| sort_of(m) == *sort && ids.contains(&m.id()))
+ .map(|m| m.id())
+ .collect()
+ };
+ let (left, right) = (mine(&free_a, xs), mine(&free_b, ys));
+ let chosen: Vec<(u32, u32, bool)> = match left.len() == right.len() {
+ true => left.iter().zip(&right).map(|(&x, &y)| (x, y, false)).collect(),
+ false => nearest(&free_a, &free_b, &left, &right),
+ };
+ chosen
+ .into_iter()
+ .for_each(|(x, y, rev)| take(&mut out, &mut free_a, &mut free_b, x, y, rev));
+ });
+ });
+ match how {
+ Match::Id => {
+ let ids: Vec<u32> = free_a.iter().map(|m| m.id()).collect();
+ ids.iter()
+ .for_each(|&id| take(&mut out, &mut free_a, &mut free_b, id, id, false));
+ }
+ Match::Order => {
+ [Sort::Stroke, Sort::Polygon, Sort::Flood].iter().for_each(|sort| {
+ let xs: Vec<u32> = free_a.iter().filter(|m| sort_of(m) == *sort).map(|m| m.id()).collect();
+ let ys: Vec<u32> = free_b.iter().filter(|m| sort_of(m) == *sort).map(|m| m.id()).collect();
+ xs.iter()
+ .zip(&ys)
+ .for_each(|(&x, &y)| take(&mut out, &mut free_a, &mut free_b, x, y, false));
+ });
+ }
+ Match::Near => {
+ let (xs, ys): (Vec<u32>, Vec<u32>) = (
+ free_a.iter().map(|m| m.id()).collect(),
+ free_b.iter().map(|m| m.id()).collect(),
+ );
+ nearest(&free_a, &free_b, &xs, &ys)
+ .into_iter()
+ .for_each(|(x, y, rev)| take(&mut out, &mut free_a, &mut free_b, x, y, rev));
+ }
+ }
+ let order: BTreeMap<u32, usize> = a.iter().enumerate().map(|(i, m)| (m.id(), i)).collect();
+ out.pairs
+ .sort_by_key(|p| order.get(&p.a).copied().unwrap_or(usize::MAX));
+ out.alone_a = free_a.iter().map(|m| m.id()).collect();
+ out.alone_b = free_b.iter().map(|m| m.id()).collect();
+ out
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Touch {
+ other: usize,
+ u: (f64, f64),
+ along: (f64, f64),
+ across: (f64, f64),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct StrokePlan {
+ a: Stroke,
+ b: Stroke,
+ pa: Vec<P>,
+ pb: Vec<P>,
+ own: Sim,
+ rel: Sim,
+ parent: Option<usize>,
+ rest: Vec<(f64, f64)>,
+ touches: [Option<Touch>; 2],
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct ShapePlan {
+ a: Fill,
+ b: Fill,
+ pa: Vec<(f64, f64)>,
+ fit: Sim,
+ rest: Vec<(f64, f64)>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+enum Item {
+ Stroke(StrokePlan),
+ Polygon(ShapePlan),
+ Flood { a: Fill, b: Fill },
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Plan {
+ items: Vec<Item>,
+ order: Vec<usize>,
+ pub pairing: Pairing,
+ alone: (Vec<Mark>, Vec<Mark>),
+}
+
+fn planned_points(pa: &[P], pb: &[P]) -> (Sim, Vec<(f64, f64)>) {
+ let (xa, xb) = (xy(pa), xy(pb));
+ let f = fit(&xa, &xb);
+ let rest = xa
+ .iter()
+ .zip(&xb)
+ .map(|(p, q)| {
+ let m = f.apply(*p);
+ (q.0 - m.0, q.1 - m.1)
+ })
+ .collect();
+ (f, rest)
+}
+
+fn reach(stroke: &Stroke) -> f64 {
+ stroke.size as f64 / 2.0 + 2.0
+}
+
+fn touch_of(
+ strokes: &[(&Stroke, Vec<(f64, f64)>)],
+ me: usize,
+ end: usize,
+ hint: Option<(usize, f64)>,
+) -> Option<(usize, f64, f64, f64)> {
+ let (own, line) = &strokes[me];
+ let at = match end {
+ 0 => *line.first()?,
+ _ => *line.last()?,
+ };
+ let slack = own.size as f64 * 0.25;
+ strokes
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| *i != me && hint.is_none_or(|(h, _)| h == *i))
+ .filter_map(|(i, (stroke, other))| {
+ let (anchor, d) = anchor_near(other, i, at, hint.map(|(_, u)| u))?;
+ (d <= reach(stroke) + slack).then_some((i, anchor, d))
+ })
+ .min_by(|x, y| x.2.total_cmp(&y.2))
+ .map(|(i, a, _)| (i, a.u, a.along, a.across))
+}
+
+pub fn plan(a: &[Mark], b: &[Mark], how: Match, forced: &[[u32; 2]]) -> Plan {
+ plan_parts(a, b, how, forced, &[])
+}
+
+pub fn plan_parts(a: &[Mark], b: &[Mark], how: Match, forced: &[[u32; 2]], parts: &Groups) -> Plan {
+ let pairing = pair_parts(a, b, how, forced, parts);
+ let find = |marks: &[Mark], id: u32| marks.iter().find(|m| m.id() == id).cloned();
+ let items: Vec<Item> = pairing
+ .pairs
+ .iter()
+ .filter_map(|p| Some((p, find(a, p.a)?, find(b, p.b)?)))
+ .map(|(p, ma, mb)| match (ma, mb) {
+ (Mark::Stroke(sa), Mark::Stroke(sb)) => {
+ let (oa, mut ob) = (points_of(&sa), points_of(&sb));
+ if p.reversed {
+ let end = ob.last().map_or(0.0, |q| q.time);
+ ob.reverse();
+ ob.iter_mut().for_each(|q| q.time = end - q.time);
+ }
+ let n = oa.len().max(ob.len()).max(1);
+ let (pa, pb) = (resample(&oa, n), resample(&ob, n));
+ let (own, rest) = planned_points(&pa, &pb);
+ Item::Stroke(StrokePlan {
+ a: sa,
+ b: sb,
+ pa,
+ pb,
+ own,
+ rel: own,
+ parent: None,
+ rest,
+ touches: [None, None],
+ })
+ }
+ (Mark::Fill(fa), Mark::Fill(fb)) => match (&fa.source, &fb.source) {
+ (FillSource::Polygon(_), FillSource::Polygon(_)) => {
+ let (oa, ob) = (outline(&Mark::Fill(fa.clone())), outline(&Mark::Fill(fb.clone())));
+ let n = oa.len().max(ob.len()).max(4);
+ let (pa, pb) = (resample(&oa, n), resample(&ob, n));
+ let (fit, rest) = planned_points(&pa, &pb);
+ Item::Polygon(ShapePlan {
+ a: fa,
+ b: fb,
+ pa: xy(&pa),
+ fit,
+ rest,
+ })
+ }
+ _ => Item::Flood { a: fa, b: fb },
+ },
+ _ => unreachable!("pairs share their kind"),
+ })
+ .collect();
+ let alone = |marks: &[Mark], ids: &[u32], clashed: &[u32]| -> Vec<Mark> {
+ marks
+ .iter()
+ .filter(|m| ids.contains(&m.id()) || clashed.contains(&m.id()))
+ .cloned()
+ .collect()
+ };
+ let (clash_a, clash_b): (Vec<u32>, Vec<u32>) = pairing.clashes.iter().copied().unzip();
+ let alone = (
+ alone(a, &pairing.alone_a, &clash_a),
+ alone(b, &pairing.alone_b, &clash_b),
+ );
+ let mut plan = Plan {
+ items,
+ order: Vec::new(),
+ pairing,
+ alone,
+ };
+ plan.find_touches();
+ plan.link_parents();
+ plan
+}
+
+impl Plan {
+ fn find_touches(&mut self) {
+ let strokes: Vec<usize> = (0..self.items.len())
+ .filter(|&i| matches!(self.items[i], Item::Stroke(_)))
+ .collect();
+ let side = |pick_b: bool| -> Vec<(&Stroke, Vec<(f64, f64)>)> {
+ strokes
+ .iter()
+ .map(|&i| match &self.items[i] {
+ Item::Stroke(s) if pick_b => (&s.b, xy(&s.pb)),
+ Item::Stroke(s) => (&s.a, xy(&s.pa)),
+ _ => unreachable!(),
+ })
+ .collect()
+ };
+ let (in_a, in_b) = (side(false), side(true));
+ let found: Vec<(usize, usize, Touch)> = (0..strokes.len())
+ .flat_map(|k| (0..2).map(move |end| (k, end)))
+ .filter_map(|(k, end)| {
+ let ta = touch_of(&in_a, k, end, None)?;
+ let tb = touch_of(&in_b, k, end, Some((ta.0, ta.1)))?;
+ ((tb.1 - ta.1).abs() <= 0.5).then(|| {
+ (
+ strokes[k],
+ end,
+ Touch {
+ other: strokes[ta.0],
+ u: (ta.1, tb.1),
+ along: (ta.2, tb.2),
+ across: (ta.3, tb.3),
+ },
+ )
+ })
+ })
+ .collect();
+ found.into_iter().for_each(|(i, end, touch)| {
+ if let Item::Stroke(s) = &mut self.items[i] {
+ s.touches[end] = Some(touch);
+ }
+ });
+ }
+
+ fn link_parents(&mut self) {
+ let strokes: Vec<usize> = (0..self.items.len())
+ .filter(|&i| matches!(self.items[i], Item::Stroke(_)))
+ .collect();
+ let stroke = |i: usize| match &self.items[i] {
+ Item::Stroke(s) => Some(s),
+ _ => None,
+ };
+ let mut next: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
+ strokes.iter().for_each(|&i| {
+ stroke(i)
+ .into_iter()
+ .flat_map(|s| s.touches.iter().flatten())
+ .for_each(|t| {
+ next.entry(i).or_default().push(t.other);
+ next.entry(t.other).or_default().push(i);
+ });
+ });
+ next.values_mut().for_each(|v| {
+ v.sort_unstable();
+ v.dedup();
+ });
+ let length = |i: usize| stroke(i).map_or(0.0, |s| walked(&s.pa).last().copied().unwrap_or(0.0));
+ let mut roots = strokes.clone();
+ roots.sort_by(|x, y| length(*y).total_cmp(&length(*x)).then(x.cmp(y)));
+ let mut parent: Vec<Option<usize>> = vec![None; self.items.len()];
+ let mut seen = vec![false; self.items.len()];
+ let mut order = Vec::new();
+ roots.into_iter().for_each(|root| {
+ if seen[root] {
+ return;
+ }
+ seen[root] = true;
+ let mut queue = std::collections::VecDeque::from([root]);
+ while let Some(i) = queue.pop_front() {
+ order.push(i);
+ next.get(&i).into_iter().flatten().for_each(|&n| {
+ if !seen[n] {
+ seen[n] = true;
+ parent[n] = Some(i);
+ queue.push_back(n);
+ }
+ });
+ }
+ });
+ let owns: Vec<Sim> = self
+ .items
+ .iter()
+ .map(|item| match item {
+ Item::Stroke(s) => s.own,
+ _ => SAME,
+ })
+ .collect();
+ self.items.iter_mut().enumerate().for_each(|(i, item)| {
+ if let Item::Stroke(s) = item {
+ s.parent = parent[i];
+ s.rel = match parent[i] {
+ Some(p) => owns[p].inverse().then(&s.own),
+ None => s.own,
+ };
+ }
+ });
+ self.order = order;
+ }
+
+ pub fn touching_ends(&self) -> usize {
+ self.items
+ .iter()
+ .map(|item| match item {
+ Item::Stroke(s) => s.touches.iter().flatten().count(),
+ _ => 0,
+ })
+ .sum()
+ }
+
+ pub fn floods(&self) -> Vec<(&Fill, &Fill)> {
+ self.items
+ .iter()
+ .filter_map(|item| match item {
+ Item::Flood { a, b } => Some((a, b)),
+ _ => None,
+ })
+ .collect()
+ }
+
+ pub fn unpaired_at(&self, t: f32, how: Unpaired, now: &Lines) -> Vec<Mark> {
+ let (la, lb) = self.key_lines();
+ let side = |marks: &[Mark], lines: &Lines, first: bool| -> Vec<Mark> {
+ marks
+ .iter()
+ .filter(|m| !matches!(m, Mark::Fill(f) if matches!(f.source, FillSource::Seed { .. })))
+ .filter_map(|m| shown(&carry(m, lines, now, None), t, how, first))
+ .collect()
+ };
+ side(&self.alone.0, &la, true)
+ .into_iter()
+ .chain(side(&self.alone.1, &lb, false))
+ .collect()
+ }
+
+ pub fn unpaired_floods(&self) -> usize {
+ self.alone
+ .0
+ .iter()
+ .chain(&self.alone.1)
+ .filter(|m| matches!(m, Mark::Fill(f) if matches!(f.source, FillSource::Seed { .. })))
+ .count()
+ }
+
+ pub fn key_lines(&self) -> (Lines, Lines) {
+ let strokes: Vec<&StrokePlan> = self
+ .items
+ .iter()
+ .filter_map(|item| match item {
+ Item::Stroke(s) => Some(s),
+ _ => None,
+ })
+ .collect();
+ let line = |pts: &[P]| pts.iter().map(|p| (p.x as f32, p.y as f32)).collect::<Vec<_>>();
+ (
+ strokes.iter().map(|s| line(&s.pa)).collect(),
+ strokes.iter().map(|s| line(&s.pb)).collect(),
+ )
+ }
+
+ pub fn at(&self, t: f32) -> Vec<Mark> {
+ let t64 = t as f64;
+ let mut moved: Vec<Option<Sim>> = vec![None; self.items.len()];
+ self.order.iter().for_each(|&i| {
+ if let Item::Stroke(s) = &self.items[i] {
+ let own = s.rel.arc(t64);
+ moved[i] = Some(match s.parent.and_then(|p| moved[p]) {
+ Some(up) => up.then(&own),
+ None => own,
+ });
+ }
+ });
+ let mut lines: Vec<Option<Vec<P>>> = self
+ .items
+ .iter()
+ .enumerate()
+ .map(|(i, item)| match item {
+ Item::Stroke(s) => {
+ let a = moved[i].unwrap_or(SAME);
+ Some(
+ s.pa.iter()
+ .zip(&s.pb)
+ .zip(&s.rest)
+ .map(|((p, q), r)| {
+ let (x, y) = a.apply((p.x, p.y));
+ P {
+ x: x + r.0 * t64,
+ y: y + r.1 * t64,
+ ..mix(p, q, t64)
+ }
+ })
+ .collect(),
+ )
+ }
+ _ => None,
+ })
+ .collect();
+ (0..self.items.len()).for_each(|i| {
+ let Item::Stroke(s) = &self.items[i] else {
+ return;
+ };
+ (0..2).for_each(|end| {
+ let Some(touch) = s.touches[end] else {
+ return;
+ };
+ let Some(other) = lines[touch.other].as_ref().map(|l| xy(l)) else {
+ return;
+ };
+ let anchor = Anchor {
+ line: 0,
+ u: lerp(touch.u.0, touch.u.1, t64),
+ along: lerp(touch.along.0, touch.along.1, t64),
+ across: lerp(touch.across.0, touch.across.1, t64),
+ };
+ let Some(target) = place_on(&other, &anchor) else {
+ return;
+ };
+ if let Some(line) = lines[i].as_mut() {
+ snap(line, end, target);
+ }
+ });
+ });
+ self.items
+ .iter()
+ .zip(lines)
+ .zip(moved)
+ .map(|((item, line), sim)| match (item, line) {
+ (Item::Stroke(s), Some(line)) => Mark::Stroke(stroke_at(s, &line, sim.unwrap_or(SAME), t)),
+ (Item::Polygon(f), _) => Mark::Fill(polygon_at(f, t)),
+ (Item::Flood { a, b }, _) => Mark::Fill(flood_at(a, b, t)),
+ _ => unreachable!(),
+ })
+ .collect()
+ }
+}
+
+fn snap(line: &mut [P], end: usize, target: (f64, f64)) {
+ if line.is_empty() {
+ return;
+ }
+ let order: Vec<usize> = match end {
+ 0 => (0..line.len()).collect(),
+ _ => (0..line.len()).rev().collect(),
+ };
+ let at = line[order[0]];
+ let (dx, dy) = (target.0 - at.x, target.1 - at.y);
+ if dx * dx + dy * dy < 1e-6 {
+ return;
+ }
+ let ordered: Vec<P> = order.iter().map(|&i| line[i]).collect();
+ let along = walked(&ordered);
+ let total = along[along.len() - 1];
+ let span = (total * 0.35).clamp(1e-3, 48.0);
+ order.iter().zip(along).for_each(|(&i, s)| {
+ if s < span {
+ let x = 1.0 - s / span;
+ let w = x * x * (3.0 - 2.0 * x);
+ line[i].x += dx * w;
+ line[i].y += dy * w;
+ }
+ });
+}
+
+fn lerp32(a: f32, b: f32, t: f32) -> f32 {
+ a + (b - a) * t
+}
+
+fn colour(a: [u16; 4], b: [u16; 4], t: f32) -> [u16; 4] {
+ std::array::from_fn(|i| lerp32(a[i] as f32, b[i] as f32, t).round().clamp(0.0, 65535.0) as u16)
+}
+
+fn stroke_at(s: &StrokePlan, line: &[P], sim: Sim, t: f32) -> Stroke {
+ let mut last = 0.0;
+ let samples = line
+ .iter()
+ .enumerate()
+ .map(|(i, p)| {
+ let dt = if i == 0 { 0.0 } else { (p.time - last).max(0.0) };
+ last = p.time;
+ Sample::quantize(
+ p.x as f32,
+ p.y as f32,
+ p.p as f32,
+ (p.tx as f32, p.ty as f32),
+ dt as f32,
+ )
+ })
+ .collect();
+ let mut cuts = s.a.cuts.clone();
+ let a = affine32(sim.affine());
+ cuts.iter_mut().for_each(|c| {
+ c.map(|p| {
+ let (x, y) = crate::markedit::apply_affine(a, (p[0], p[1]));
+ [x, y]
+ })
+ });
+ Stroke {
+ id: s.a.id,
+ brush: if t < 0.5 { s.a.brush.clone() } else { s.b.brush.clone() },
+ color: colour(s.a.color, s.b.color, t),
+ size: lerp32(s.a.size, s.b.size, t).max(0.05),
+ opacity: lerp32(s.a.opacity, s.b.opacity, t).clamp(0.0, 1.0),
+ flow: lerp32(s.a.flow, s.b.flow, t).max(1e-3),
+ seed: s.a.seed,
+ author: Author::Agent,
+ taper: [
+ lerp32(s.a.taper[0], s.b.taper[0], t),
+ lerp32(s.a.taper[1], s.b.taper[1], t),
+ ],
+ lock: s.a.lock,
+ cuts,
+ second: match (s.a.second, s.b.second) {
+ (Some(a), Some(b)) => Some(colour(a, b, t)),
+ (a, b) => a.or(b),
+ },
+ samples,
+ }
+}
+
+fn polygon_at(f: &ShapePlan, t: f32) -> Fill {
+ let a = f.fit.arc(t as f64);
+ let points: Vec<[f32; 2]> =
+ f.pa.iter()
+ .zip(&f.rest)
+ .take(f.pa.len().saturating_sub(1).max(3))
+ .map(|(p, r)| {
+ let (x, y) = a.apply(*p);
+ [(x + r.0 * t as f64) as f32, (y + r.1 * t as f64) as f32]
+ })
+ .collect();
+ let mut cuts = f.a.cuts.clone();
+ let a32 = affine32(a.affine());
+ cuts.iter_mut().for_each(|c| {
+ c.map(|p| {
+ let (x, y) = crate::markedit::apply_affine(a32, (p[0], p[1]));
+ [x, y]
+ })
+ });
+ Fill {
+ id: f.a.id,
+ color: colour(f.a.color, f.b.color, t),
+ opacity: lerp32(f.a.opacity, f.b.opacity, t).clamp(0.0, 1.0),
+ author: Author::Agent,
+ source: FillSource::Polygon(points),
+ coverage: Coverage::default(),
+ lock: f.a.lock,
+ cuts,
+ }
+}
+
+fn flood_at(a: &Fill, b: &Fill, t: f32) -> Fill {
+ let source = match (&a.source, &b.source) {
+ (FillSource::Seed { seed: sa, reference }, FillSource::Seed { seed: sb, .. }) => FillSource::Seed {
+ seed: crate::fill::Seed {
+ x: lerp32(sa.x, sb.x, t),
+ y: lerp32(sa.y, sb.y, t),
+ ..*sa
+ },
+ reference: reference.clone(),
+ },
+ (source, _) => source.clone(),
+ };
+ Fill {
+ id: a.id,
+ color: colour(a.color, b.color, t),
+ opacity: lerp32(a.opacity, b.opacity, t).clamp(0.0, 1.0),
+ author: Author::Agent,
+ source,
+ coverage: Coverage::default(),
+ lock: a.lock,
+ cuts: a.cuts.clone(),
+ }
+}
+
+pub fn made_hash(marks: &[Mark]) -> String {
+ let hash = marks.iter().fold(crate::rng::FNV_OFFSET, |h, m| {
+ crate::rng::fnv(h, &fingerprint(m).to_le_bytes())
+ });
+ format!("{hash:016x}")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fill::{FillRef, Seed};
+
+ fn stroke(id: u32, points: &[(f32, f32)], size: f32) -> Mark {
+ let pts: Vec<(f32, f32, f32)> = points.iter().map(|&(x, y)| (x, y, 1.0)).collect();
+ Stroke::new(id, "ink", [0.0, 0.0, 0.0, 1.0], size, 7)
+ .with_points(&pts, 8.0)
+ .into()
+ }
+
+ fn arm(angle: f32) -> Vec<(f32, f32)> {
+ let (s, c) = (libm::sinf(angle.to_radians()), libm::cosf(angle.to_radians()));
+ (0..=20)
+ .map(|i| {
+ let r = i as f32 * 10.0;
+ (100.0 + r * c, 100.0 + r * s)
+ })
+ .collect()
+ }
+
+ fn ends(mark: &Mark) -> ((f32, f32), (f32, f32)) {
+ let s = mark.as_stroke().unwrap();
+ (s.samples[0].pos(), s.samples[s.samples.len() - 1].pos())
+ }
+
+ fn length(mark: &Mark) -> f32 {
+ let s = mark.as_stroke().unwrap();
+ s.samples
+ .windows(2)
+ .map(|w| {
+ let (a, b) = (w[0].pos(), w[1].pos());
+ libm::sqrtf((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2))
+ })
+ .sum()
+ }
+
+ #[test]
+ fn spacing_bunches_in_betweens_where_asked() {
+ assert_eq!(Spacing::Even.ts(3), [0.25, 0.5, 0.75]);
+ assert_eq!(Spacing::In.ts(1), [0.25]);
+ assert_eq!(Spacing::Out.ts(1), [0.75]);
+ assert_eq!(Spacing::InOut.ts(1), [0.5]);
+ let list = Spacing::parse("0.1,0.4").unwrap();
+ assert_eq!((list.count(), list.ts(2)), (Some(2), vec![0.1, 0.4]));
+ assert!(Spacing::parse("0.5,0.2").is_err() && Spacing::parse("0,1").is_err());
+ }
+
+ #[test]
+ fn a_swinging_arm_turns_about_its_shoulder_and_keeps_its_length() {
+ let a = [stroke(1, &arm(0.0), 6.0)];
+ let b = [stroke(1, &arm(90.0), 6.0)];
+ let plan = plan(&a, &b, Match::Id, &[]);
+ let mid = plan.at(0.5);
+ let (start, end) = ends(&mid[0]);
+ assert!(
+ (start.0 - 100.0).abs() < 0.2 && (start.1 - 100.0).abs() < 0.2,
+ "{start:?}"
+ );
+ let diagonal = 200.0 / std::f32::consts::SQRT_2;
+ assert!(
+ (end.0 - 100.0 - diagonal).abs() < 0.5 && (end.1 - 100.0 - diagonal).abs() < 0.5,
+ "{end:?}"
+ );
+ assert!((length(&mid[0]) - 200.0).abs() < 1.0, "{}", length(&mid[0]));
+ let straight = {
+ let (p, q) = (ends(&a[0]).1, ends(&b[0]).1);
+ ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0)
+ };
+ assert!(libm::sqrtf((end.0 - straight.0).powi(2) + (end.1 - straight.1).powi(2)) > 40.0);
+ assert_eq!(mid[0].as_stroke().unwrap().author, Author::Agent);
+ }
+
+ #[test]
+ fn a_hand_bending_at_the_wrist_rides_on_the_turning_forearm() {
+ let forearm = |angle: f32| {
+ let (s, c) = (libm::sinf(angle.to_radians()), libm::cosf(angle.to_radians()));
+ (0..=20)
+ .map(|i| (100.0 + i as f32 * 10.0 * c, 100.0 + i as f32 * 10.0 * s))
+ .collect::<Vec<_>>()
+ };
+ let hand = |wrist: (f32, f32), angle: f32| {
+ let (s, c) = (libm::sinf(angle.to_radians()), libm::cosf(angle.to_radians()));
+ (0..=6)
+ .map(|i| (wrist.0 + i as f32 * 10.0 * c, wrist.1 + i as f32 * 10.0 * s))
+ .collect::<Vec<_>>()
+ };
+ let a = [
+ stroke(1, &forearm(0.0), 6.0),
+ stroke(2, &hand((300.0, 100.0), 0.0), 4.0),
+ ];
+ let b = [
+ stroke(1, &forearm(90.0), 6.0),
+ stroke(2, &hand((100.0, 300.0), 130.0), 4.0),
+ ];
+ let plan = plan(&a, &b, Match::Id, &[]);
+ let mid = plan.at(0.5);
+ let wrist = ends(&mid[0]).1;
+ let (start, end) = ends(&mid[1]);
+ let d = |p: (f32, f32), q: (f32, f32)| libm::sqrtf((p.0 - q.0).powi(2) + (p.1 - q.1).powi(2));
+ assert!(d(start, wrist) < 1.0, "{start:?} {wrist:?}");
+ let want = (
+ wrist.0 + 60.0 * libm::cosf(65f32.to_radians()),
+ wrist.1 + 60.0 * libm::sinf(65f32.to_radians()),
+ );
+ assert!(d(end, want) < 1.5, "{end:?} {want:?}");
+ assert!((length(&mid[1]) - 60.0).abs() < 1.0);
+ }
+
+ #[test]
+ fn pairs_by_id_by_order_and_by_nearest_shape() {
+ let a = vec![
+ stroke(1, &[(0.0, 0.0), (10.0, 0.0)], 4.0),
+ stroke(2, &[(0.0, 50.0), (10.0, 50.0)], 4.0),
+ ];
+ let b = vec![
+ stroke(5, &[(10.0, 51.0), (0.0, 51.0)], 4.0),
+ stroke(1, &[(1.0, 1.0), (11.0, 1.0)], 4.0),
+ ];
+ let by_id = pair(&a, &b, Match::Id, &[]);
+ assert_eq!(by_id.pairs.len(), 1);
+ assert_eq!((by_id.alone_a.clone(), by_id.alone_b.clone()), (vec![2], vec![5]));
+ let by_order = pair(&a, &b, Match::Order, &[]);
+ assert_eq!(
+ by_order.pairs.iter().map(|p| (p.a, p.b)).collect::<Vec<_>>(),
+ [(1, 5), (2, 1)]
+ );
+ let near = pair(&a, &b, Match::Near, &[]);
+ assert_eq!(
+ near.pairs.iter().map(|p| (p.a, p.b, p.reversed)).collect::<Vec<_>>(),
+ [(1, 1, false), (2, 5, true)]
+ );
+ let forced = pair(&a, &b, Match::Id, &[[2, 1]]);
+ assert_eq!(forced.pairs.iter().map(|p| (p.a, p.b)).collect::<Vec<_>>(), [(2, 1)]);
+ assert_eq!(forced.alone_a, [1]);
+ }
+
+ #[test]
+ fn line_ends_that_touch_in_both_keys_touch_in_between() {
+ let bar = |dy: f32| stroke(1, &[(0.0, 100.0 + dy), (200.0, 100.0 + dy)], 6.0);
+ let post_a = stroke(2, &[(60.0, 0.0), (60.0, 98.0)], 4.0);
+ let post_b = stroke(2, &[(140.0, 20.0), (140.0, 158.0)], 4.0);
+ let a = [bar(0.0), post_a];
+ let b = [bar(60.0), post_b];
+ let plan = plan(&a, &b, Match::Id, &[]);
+ assert_eq!(plan.touching_ends(), 1);
+ let mid = plan.at(0.5);
+ let (_, end) = ends(&mid[1]);
+ let bar_y = mid[0].as_stroke().unwrap().samples[0].pos().1;
+ assert!((end.1 - (bar_y - 2.0)).abs() < 1.0, "{end:?} against {bar_y}");
+ let open = [bar(0.0), stroke(2, &[(60.0, 0.0), (60.0, 60.0)], 4.0)];
+ assert_eq!(super::plan(&open, &b, Match::Id, &[]).touching_ends(), 0);
+ }
+
+ #[test]
+ fn polygon_fills_interpolate_and_floods_carry_their_settings() {
+ let square = |x: f32| {
+ Mark::Fill(Fill::new(
+ 3,
+ [1.0, 0.0, 0.0, 1.0],
+ FillSource::Polygon(vec![[x, 0.0], [x + 10.0, 0.0], [x + 10.0, 10.0], [x, 10.0]]),
+ Coverage::default(),
+ ))
+ };
+ let flood = |x: f32| {
+ Mark::Fill(Fill::new(
+ 4,
+ [0.0, 0.0, 1.0, 1.0],
+ FillSource::Seed {
+ seed: Seed {
+ x,
+ y: 5.0,
+ tolerance: 0.2,
+ gap: 3.0,
+ expand: 2.0,
+ },
+ reference: FillRef::Layer("l1".into()),
+ },
+ Coverage::default(),
+ ))
+ };
+ let plan = plan(&[square(0.0), flood(0.0)], &[square(40.0), flood(40.0)], Match::Id, &[]);
+ let mid = plan.at(0.5);
+ let FillSource::Polygon(points) = &mid[0].as_fill().unwrap().source else {
+ panic!()
+ };
+ assert_eq!(points.len(), 4);
+ assert!((points[0][0] - 20.0).abs() < 0.01, "{points:?}");
+ let FillSource::Seed { seed, reference } = &mid[1].as_fill().unwrap().source else {
+ panic!()
+ };
+ assert_eq!((seed.x, seed.gap, reference.name()), (20.0, 3.0, "l1"));
+ assert_eq!(plan.floods().len(), 1);
+ }
+
+ #[test]
+ fn anchors_carry_a_point_with_the_line_it_sits_by() {
+ let line = vec![(0.0, 0.0), (100.0, 0.0)];
+ let at = anchor(std::slice::from_ref(&line), (25.0, 10.0)).unwrap();
+ let turned = vec![(0.0, 0.0), (0.0, 100.0)];
+ let (x, y) = place(&at, &[turned]).unwrap();
+ assert!((x + 10.0).abs() < 1e-3 && (y - 25.0).abs() < 1e-3, "{x},{y}");
+ }
+}
diff --git a/crates/core/src/varint.rs b/crates/core/src/varint.rs
new file mode 100644
index 0000000..77bbbdd
--- /dev/null
+++ b/crates/core/src/varint.rs
@@ -0,0 +1,96 @@
+use anyhow::{Result, bail};
+
+pub fn zigzag(v: i64) -> u64 {
+ ((v << 1) ^ (v >> 63)) as u64
+}
+
+pub fn unzigzag(v: u64) -> i64 {
+ ((v >> 1) as i64) ^ -((v & 1) as i64)
+}
+
+pub fn put(out: &mut Vec<u8>, mut v: u64) {
+ while v >= 0x80 {
+ out.push((v as u8) | 0x80);
+ v >>= 7;
+ }
+ out.push(v as u8);
+}
+
+pub fn put_signed(out: &mut Vec<u8>, v: i64) {
+ put(out, zigzag(v));
+}
+
+pub struct Reader<'a> {
+ bytes: &'a [u8],
+ pos: usize,
+}
+
+impl<'a> Reader<'a> {
+ pub fn new(bytes: &'a [u8]) -> Self {
+ Self { bytes, pos: 0 }
+ }
+
+ pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
+ let Some(slice) = self.bytes.get(self.pos..self.pos + n) else {
+ bail!("stroke data ends early at byte {}", self.pos);
+ };
+ self.pos += n;
+ Ok(slice)
+ }
+
+ pub fn u8(&mut self) -> Result<u8> {
+ Ok(self.take(1)?[0])
+ }
+
+ pub fn u16(&mut self) -> Result<u16> {
+ Ok(u16::from_le_bytes(self.take(2)?.try_into()?))
+ }
+
+ pub fn u32(&mut self) -> Result<u32> {
+ Ok(u32::from_le_bytes(self.take(4)?.try_into()?))
+ }
+
+ pub fn f32(&mut self) -> Result<f32> {
+ Ok(f32::from_le_bytes(self.take(4)?.try_into()?))
+ }
+
+ pub fn varint(&mut self) -> Result<u64> {
+ let mut value = 0u64;
+ let mut shift = 0;
+ loop {
+ let byte = self.u8()?;
+ value |= ((byte & 0x7F) as u64) << shift;
+ if byte & 0x80 == 0 {
+ return Ok(value);
+ }
+ shift += 7;
+ if shift > 63 {
+ bail!("varint too long at byte {}", self.pos);
+ }
+ }
+ }
+
+ pub fn signed(&mut self) -> Result<i64> {
+ Ok(unzigzag(self.varint()?))
+ }
+
+ pub fn done(&self) -> bool {
+ self.pos == self.bytes.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn signed_round_trip() {
+ let values = [0i64, 1, -1, 63, -64, 64, 1 << 40, -(1 << 40), i64::MAX, i64::MIN];
+ let mut out = Vec::new();
+ values.iter().for_each(|&v| put_signed(&mut out, v));
+ let mut reader = Reader::new(&out);
+ let back: Vec<i64> = values.iter().map(|_| reader.signed().unwrap()).collect();
+ assert_eq!(back, values);
+ assert!(reader.done());
+ }
+}
diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml
new file mode 100644
index 0000000..5cfd68b
--- /dev/null
+++ b/crates/render/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "klad-render"
+version.workspace = true
+edition.workspace = true
+license-file.workspace = true
+publish.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+bytemuck = "1.25.2"
+klad-brush = { version = "0.1.0", path = "../brush" }
+klad-core = { version = "0.1.0", path = "../core" }
+half = { version = "2.7.1", features = ["bytemuck"] }
+libm = "0.2.16"
+rayon = "1.12.0"
+serde_json = "1.0.154"
+skia-safe = "0.157.0"
+skrifa = "0.44.0"
+zune-jpeg = "0.5.15"
+png = "0.18.1"
diff --git a/crates/render/build.rs b/crates/render/build.rs
new file mode 100644
index 0000000..2e51795
--- /dev/null
+++ b/crates/render/build.rs
@@ -0,0 +1,30 @@
+use std::path::{Path, PathBuf};
+
+const SYSTEM_LIBS: [(&str, &str); 2] = [("freetype", "6"), ("fontconfig", "1")];
+
+fn main() {
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") {
+ return;
+ }
+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
+ let system = PathBuf::from(format!("/usr/lib/{arch}-linux-gnu"));
+ let out = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR"));
+ let linked: Vec<bool> = SYSTEM_LIBS
+ .iter()
+ .map(|(name, major)| link_runtime_only(&system, &out, name, major))
+ .collect();
+ if linked.iter().any(|&l| l) {
+ println!("cargo:rustc-link-search=native={}", out.display());
+ }
+}
+
+fn link_runtime_only(system: &Path, out: &Path, name: &str, major: &str) -> bool {
+ let dev = system.join(format!("lib{name}.so"));
+ let runtime = system.join(format!("lib{name}.so.{major}"));
+ if dev.exists() || !runtime.exists() {
+ return false;
+ }
+ let link = out.join(format!("lib{name}.so"));
+ let _ = std::fs::remove_file(&link);
+ std::os::unix::fs::symlink(&runtime, &link).is_ok()
+}
diff --git a/crates/render/src/assets.rs b/crates/render/src/assets.rs
new file mode 100644
index 0000000..8e45790
--- /dev/null
+++ b/crates/render/src/assets.rs
@@ -0,0 +1,192 @@
+use anyhow::{Context, Result, anyhow, bail};
+use klad_core::bundle::write_atomic;
+use klad_core::rng::{FNV_OFFSET, fnv};
+use skia_safe::{AlphaType, ColorSpace, ColorType, Data, Image, ImageInfo, images};
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+
+pub const IMAGES: &str = "images";
+pub const FONTS: &str = "fonts";
+
+static ROOTS: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
+static PICTURES: Mutex<BTreeMap<String, Image>> = Mutex::new(BTreeMap::new());
+static TYPEFACES: Mutex<BTreeMap<String, Arc<Vec<u8>>>> = Mutex::new(BTreeMap::new());
+
+pub fn add_root(root: &Path) {
+ let mut roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner());
+ if !roots.iter().any(|r| r == root) {
+ roots.push(root.to_path_buf());
+ }
+}
+
+fn find(folder: &str, name: &str) -> Option<PathBuf> {
+ let added = ROOTS.lock().unwrap_or_else(|e| e.into_inner()).clone();
+ added
+ .into_iter()
+ .chain(klad_core::bundle::opened())
+ .map(|root| root.join(folder).join(name))
+ .find(|p| p.exists())
+}
+
+pub struct Rgba {
+ pub width: u32,
+ pub height: u32,
+ pub pixels: Vec<u8>,
+}
+
+pub fn decode(bytes: &[u8]) -> Result<Rgba> {
+ match bytes {
+ [0x89, b'P', b'N', b'G', ..] => decode_png(bytes),
+ [0xFF, 0xD8, ..] => decode_jpeg(bytes),
+ _ => bail!("only PNG and JPEG pictures can be imported"),
+ }
+}
+
+fn decode_png(bytes: &[u8]) -> Result<Rgba> {
+ let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
+ decoder.set_transformations(png::Transformations::normalize_to_color8() | png::Transformations::ALPHA);
+ let mut reader = decoder.read_info()?;
+ let size = reader
+ .output_buffer_size()
+ .ok_or_else(|| anyhow!("the picture is too big"))?;
+ let mut buf = vec![0u8; size];
+ let info = reader.next_frame(&mut buf)?;
+ let (w, h) = (info.width, info.height);
+ let channels = info.color_type.samples();
+ let pixels = buf[..(w * h) as usize * channels]
+ .chunks_exact(channels)
+ .flat_map(|px| match channels {
+ 2 => [px[0], px[0], px[0], px[1]],
+ 4 => [px[0], px[1], px[2], px[3]],
+ 3 => [px[0], px[1], px[2], 255],
+ _ => [px[0], px[0], px[0], 255],
+ })
+ .collect();
+ Ok(Rgba {
+ width: w,
+ height: h,
+ pixels,
+ })
+}
+
+fn decode_jpeg(bytes: &[u8]) -> Result<Rgba> {
+ use zune_jpeg::zune_core::colorspace::ColorSpace as Space;
+ use zune_jpeg::zune_core::options::DecoderOptions;
+ let options = DecoderOptions::default().jpeg_set_out_colorspace(Space::RGBA);
+ let mut decoder = zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(bytes), options);
+ let pixels = decoder.decode().map_err(|e| anyhow!("reading the JPEG: {e:?}"))?;
+ let info = decoder.info().ok_or_else(|| anyhow!("the JPEG has no size"))?;
+ Ok(Rgba {
+ width: info.width as u32,
+ height: info.height as u32,
+ pixels,
+ })
+}
+
+pub fn encode_png(rgba: &Rgba) -> Result<Vec<u8>> {
+ let mut out = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut out, rgba.width, rgba.height);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.set_compression(png::Compression::Balanced);
+ let mut writer = encoder.write_header()?;
+ writer.write_image_data(&rgba.pixels)?;
+ }
+ Ok(out)
+}
+
+pub fn import_image(root: &Path, bytes: &[u8]) -> Result<(String, u32, u32)> {
+ let rgba = decode(bytes)?;
+ if rgba.width == 0 || rgba.height == 0 {
+ bail!("the picture is empty");
+ }
+ let png = encode_png(&rgba)?;
+ let name = format!("{:016x}.png", fnv(FNV_OFFSET, &png));
+ let path = root.join(IMAGES).join(&name);
+ if !path.exists() {
+ write_atomic(&path, &png)?;
+ }
+ Ok((name, rgba.width, rgba.height))
+}
+
+pub fn import_font(root: &Path, file: &Path) -> Result<String> {
+ let bytes = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?;
+ crate::text::parse(&bytes).map_err(|e| anyhow!("{} is not a font this can read: {e}", file.display()))?;
+ let name = file
+ .file_name()
+ .and_then(|n| n.to_str())
+ .ok_or_else(|| anyhow!("{} has no file name", file.display()))?
+ .to_string();
+ let path = root.join(FONTS).join(&name);
+ if path.exists() && std::fs::read(&path)? != bytes {
+ bail!("the bundle already has another font called {name}; rename the file");
+ }
+ write_atomic(&path, &bytes)?;
+ Ok(name)
+}
+
+pub fn image(src: &str) -> Result<Image> {
+ if let Some(found) = PICTURES.lock().unwrap_or_else(|e| e.into_inner()).get(src) {
+ return Ok(found.clone());
+ }
+ let path = find(IMAGES, src).ok_or_else(|| anyhow!("the picture {src} is not in the bundle's images folder"))?;
+ let rgba = decode(&std::fs::read(&path)?).with_context(|| format!("picture {src}"))?;
+ let info = ImageInfo::new(
+ (rgba.width as i32, rgba.height as i32),
+ ColorType::RGBA8888,
+ AlphaType::Unpremul,
+ ColorSpace::new_srgb(),
+ );
+ let made = images::raster_from_data(&info, Data::new_copy(&rgba.pixels), rgba.width as usize * 4)
+ .and_then(|i| i.with_default_mipmaps())
+ .ok_or_else(|| anyhow!("cannot hold the picture {src}"))?;
+ PICTURES
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .insert(src.to_string(), made.clone());
+ Ok(made)
+}
+
+pub fn font(name: &str) -> Result<Arc<Vec<u8>>> {
+ if let Some(found) = TYPEFACES.lock().unwrap_or_else(|e| e.into_inner()).get(name) {
+ return Ok(found.clone());
+ }
+ let path = find(FONTS, name)
+ .ok_or_else(|| anyhow!("the font {name} is not in the bundle's fonts folder; add it with klad font"))?;
+ let bytes = Arc::new(std::fs::read(&path)?);
+ crate::text::parse(&bytes).map_err(|e| anyhow!("the font {name} cannot be read: {e}"))?;
+ TYPEFACES
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .insert(name.to_string(), bytes.clone());
+ Ok(bytes)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_picture_is_stored_once_by_its_content_and_reads_back() {
+ let root = std::env::temp_dir().join(format!("draw-assets-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let rgba = Rgba {
+ width: 3,
+ height: 2,
+ pixels: (0..24).map(|i| (i * 10) as u8).collect(),
+ };
+ let png = encode_png(&rgba).unwrap();
+ let (a, w, h) = import_image(&root, &png).unwrap();
+ let (b, _, _) = import_image(&root, &png).unwrap();
+ assert_eq!((a.clone(), w, h), (b, 3, 2));
+ assert_eq!(std::fs::read_dir(root.join(IMAGES)).unwrap().count(), 1);
+ add_root(&root);
+ let image = image(&a).unwrap();
+ assert_eq!((image.width(), image.height()), (3, 2));
+ assert!(decode(b"GIF89a").is_err());
+ assert!(font("nope.ttf").unwrap_err().to_string().contains("nope.ttf"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rs
new file mode 100644
index 0000000..395c721
--- /dev/null
+++ b/crates/render/src/effects.rs
@@ -0,0 +1,648 @@
+use anyhow::Result;
+use klad_core::color::parse_hex;
+use klad_core::doc::Blend;
+use klad_core::look::{self, Displace, Effect, Glow, Haze, Noise, Outline, Shadow};
+use klad_core::rng::hash2_unit;
+use rayon::prelude::*;
+
+pub type Px = [f32; 4];
+
+const SHARP: f32 = 2.0;
+const MAX_FACTOR: i32 = 32;
+const FAR: f64 = 1e20;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Img {
+ pub x: i32,
+ pub y: i32,
+ pub w: usize,
+ pub h: usize,
+ pub px: Vec<Px>,
+}
+
+impl Img {
+ pub fn empty(x: i32, y: i32, w: usize, h: usize) -> Self {
+ Self {
+ x,
+ y,
+ w,
+ h,
+ px: vec![[0.0; 4]; w * h],
+ }
+ }
+
+ pub fn at(&self, gx: i32, gy: i32) -> Px {
+ let (lx, ly) = (gx - self.x, gy - self.y);
+ if lx < 0 || ly < 0 || lx as usize >= self.w || ly as usize >= self.h {
+ return [0.0; 4];
+ }
+ self.px[ly as usize * self.w + lx as usize]
+ }
+
+ fn each(&self, f: impl Fn(i32, i32, Px) -> Px + Sync) -> Img {
+ let px = self
+ .px
+ .par_chunks(self.w.max(1))
+ .enumerate()
+ .flat_map_iter(|(row, line)| {
+ let gy = self.y + row as i32;
+ line.iter()
+ .enumerate()
+ .map(move |(col, p)| (self.x + col as i32, gy, *p))
+ .map(|(gx, gy, p)| f(gx, gy, p))
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ Img {
+ px,
+ ..self.clone_shape()
+ }
+ }
+
+ pub fn crop(&self, x: i32, y: i32, w: usize, h: usize) -> Img {
+ let px = (0..h)
+ .flat_map(|row| (0..w).map(move |col| (x + col as i32, y + row as i32)))
+ .map(|(gx, gy)| self.at(gx, gy))
+ .collect();
+ Img { x, y, w, h, px }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Space {
+ pub scale: f32,
+ pub tx: f32,
+ pub ty: f32,
+}
+
+impl Space {
+ fn canvas(&self, gx: i32, gy: i32) -> (f32, f32) {
+ (
+ (gx as f32 + 0.5 - self.tx) / self.scale,
+ (gy as f32 + 0.5 - self.ty) / self.scale,
+ )
+ }
+}
+
+pub struct Pass {
+ pub img: Img,
+ pub blend: Blend,
+}
+
+fn factor(sigma: f32) -> i32 {
+ let mut f = 1;
+ while sigma / (2 * f) as f32 >= SHARP && f < MAX_FACTOR {
+ f *= 2;
+ }
+ f
+}
+
+pub fn margin(effects: &[Effect], scale: f32) -> i32 {
+ let slack: i32 = effects
+ .iter()
+ .map(|e| match e {
+ Effect::Blur(b) => factor(b.radius * scale) * 2 + 2,
+ Effect::Glow(g) => factor(g.radius * scale) * 2 + 2,
+ Effect::Shadow(s) => factor(s.radius * scale) * 2 + 2,
+ Effect::Displace(_) => 2,
+ _ => 1,
+ })
+ .sum();
+ (look::reach(effects) * scale).ceil() as i32 + slack
+}
+
+pub fn run(
+ effects: &[Effect],
+ img: Img,
+ space: Space,
+ by: &dyn Fn(&str) -> Result<Option<Img>>,
+) -> Result<(Vec<Pass>, Img)> {
+ let s = space.scale;
+ effects.iter().try_fold((Vec::new(), img), |(mut passes, img), effect| {
+ let img = match effect {
+ Effect::Blur(b) => blur(&img, b.radius * s),
+ Effect::Glow(g) => {
+ let glow = glow(&img, g, s)?;
+ match g.blend {
+ Blend::Normal => over(&img, &glow),
+ blend => {
+ passes.push(Pass { img: glow, blend });
+ img
+ }
+ }
+ }
+ Effect::Outline(o) => outline(&img, o, s)?,
+ Effect::Shadow(sh) => over(&img, &shadow(&img, sh, s)?),
+ Effect::Noise(n) => noise(&img, n, space),
+ Effect::Haze(h) => haze(&img, h, space)?,
+ Effect::Displace(d) => {
+ let map = match &d.by {
+ Some(id) => by(id)?,
+ None => None,
+ };
+ displace(&img, d, space, map.as_ref())
+ }
+ };
+ Ok((passes, img))
+ })
+}
+
+pub fn over(top: &Img, under: &Img) -> Img {
+ top.each(|gx, gy, t| {
+ let u = under.at(gx, gy);
+ let k = 1.0 - t[3];
+ [t[0] + u[0] * k, t[1] + u[1] * k, t[2] + u[2] * k, t[3] + u[3] * k]
+ })
+}
+
+pub fn blur(img: &Img, sigma: f32) -> Img {
+ if sigma < 0.25 || img.w == 0 || img.h == 0 {
+ return img.clone();
+ }
+ let f = factor(sigma);
+ if f == 1 {
+ return gaussian(img, sigma);
+ }
+ let small = downsample(img, f);
+ let small_sigma = (sigma * sigma - (f * f) as f32 / 4.0).max(1.0).sqrt() / f as f32;
+ upsample(&gaussian(&small, small_sigma), f, img)
+}
+
+fn downsample(img: &Img, f: i32) -> Img {
+ let (cx0, cy0) = (img.x.div_euclid(f), img.y.div_euclid(f));
+ let cx1 = (img.x + img.w as i32 - 1).div_euclid(f);
+ let cy1 = (img.y + img.h as i32 - 1).div_euclid(f);
+ let (w, h) = ((cx1 - cx0 + 1) as usize, (cy1 - cy0 + 1) as usize);
+ let area = (f * f) as f32;
+ let px = (0..h)
+ .into_par_iter()
+ .flat_map_iter(|row| {
+ let cy = cy0 + row as i32;
+ (0..w)
+ .map(move |col| {
+ let cx = cx0 + col as i32;
+ let sum = (0..f).fold([0.0f32; 4], |acc, dy| {
+ (0..f).fold(acc, |acc, dx| {
+ let p = img.at(cx * f + dx, cy * f + dy);
+ [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2], acc[3] + p[3]]
+ })
+ });
+ sum.map(|v| v / area)
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ Img {
+ x: cx0,
+ y: cy0,
+ w,
+ h,
+ px,
+ }
+}
+
+fn upsample(small: &Img, f: i32, like: &Img) -> Img {
+ let k = f as f32;
+ like.each(|gx, gy, _| {
+ let u = (gx as f32 + 0.5) / k - 0.5;
+ let v = (gy as f32 + 0.5) / k - 0.5;
+ let (i, j) = (u.floor() as i32, v.floor() as i32);
+ let (fu, fv) = (u - i as f32, v - j as f32);
+ let (a, b, c, d) = (
+ small.at(i, j),
+ small.at(i + 1, j),
+ small.at(i, j + 1),
+ small.at(i + 1, j + 1),
+ );
+ [0, 1, 2, 3].map(|ch| {
+ let top = a[ch] + (b[ch] - a[ch]) * fu;
+ let bottom = c[ch] + (d[ch] - c[ch]) * fu;
+ top + (bottom - top) * fv
+ })
+ })
+}
+
+fn kernel(sigma: f32) -> Vec<f32> {
+ let radius = (sigma * 3.0).ceil() as i32;
+ let weights: Vec<f32> = (-radius..=radius)
+ .map(|i| libm::expf(-((i * i) as f32) / (2.0 * sigma * sigma)))
+ .collect();
+ let total: f32 = weights.iter().sum();
+ weights.iter().map(|w| w / total).collect()
+}
+
+fn gaussian(img: &Img, sigma: f32) -> Img {
+ let taps = kernel(sigma);
+ let reach = (taps.len() / 2) as i32;
+ let (w, h) = (img.w as i32, img.h as i32);
+ let pass = |src: &[Px], horizontal: bool| -> Vec<Px> {
+ (0..h)
+ .into_par_iter()
+ .flat_map_iter(|y| {
+ let taps = &taps;
+ (0..w)
+ .map(move |x| {
+ taps.iter().enumerate().fold([0.0f32; 4], |acc, (k, wt)| {
+ let o = k as i32 - reach;
+ let (sx, sy) = match horizontal {
+ true => (x + o, y),
+ false => (x, y + o),
+ };
+ if sx < 0 || sy < 0 || sx >= w || sy >= h {
+ return acc;
+ }
+ let p = src[(sy * w + sx) as usize];
+ [
+ acc[0] + p[0] * wt,
+ acc[1] + p[1] * wt,
+ acc[2] + p[2] * wt,
+ acc[3] + p[3] * wt,
+ ]
+ })
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect()
+ };
+ let across = pass(&img.px, true);
+ Img {
+ px: pass(&across, false),
+ ..img.clone_shape()
+ }
+}
+
+impl Img {
+ fn clone_shape(&self) -> Img {
+ Img {
+ x: self.x,
+ y: self.y,
+ w: self.w,
+ h: self.h,
+ px: Vec::new(),
+ }
+ }
+}
+
+fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
+ let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+fn glow(img: &Img, g: &Glow, scale: f32) -> Result<Img> {
+ let tint = g.color.as_deref().map(parse_hex).transpose()?;
+ let lit = img.each(|_, _, p| {
+ let a = p[3];
+ if a <= 0.0 {
+ return [0.0; 4];
+ }
+ let weight = match g.threshold > 0.0 {
+ true => smoothstep(
+ g.threshold,
+ g.threshold + 0.1,
+ look::luma([p[0] / a, p[1] / a, p[2] / a]),
+ ),
+ false => 1.0,
+ };
+ match tint {
+ Some(c) => {
+ let k = a * weight * c[3];
+ [c[0] * k, c[1] * k, c[2] * k, k]
+ }
+ None => p.map(|v| v * weight),
+ }
+ });
+ let soft = blur(&lit, g.radius * scale);
+ Ok(soft.each(|_, _, p| {
+ let a = (p[3] * g.strength).clamp(0.0, 1.0);
+ let c = |v: f32| (v * g.strength).clamp(0.0, a);
+ [c(p[0]), c(p[1]), c(p[2]), a]
+ }))
+}
+
+fn dt1d(f: &[f64]) -> Vec<f64> {
+ let n = f.len();
+ if n == 0 {
+ return Vec::new();
+ }
+ let mut v = vec![0usize; n];
+ let mut z = vec![0.0f64; n + 1];
+ let mut k = 0usize;
+ z[0] = f64::NEG_INFINITY;
+ z[1] = f64::INFINITY;
+ let cross =
+ |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64);
+ (1..n).for_each(|q| {
+ let mut s = cross(q, v[k]);
+ while s <= z[k] {
+ k -= 1;
+ s = cross(q, v[k]);
+ }
+ k += 1;
+ v[k] = q;
+ z[k] = s;
+ z[k + 1] = f64::INFINITY;
+ });
+ let mut k = 0usize;
+ (0..n)
+ .map(|q| {
+ while z[k + 1] < q as f64 {
+ k += 1;
+ }
+ let p = v[k];
+ let d = q as f64 - p as f64;
+ d * d + f[p]
+ })
+ .collect()
+}
+
+fn distances(img: &Img, seed: impl Fn(Px) -> bool + Sync) -> Vec<f32> {
+ let (w, h) = (img.w, img.h);
+ let start: Vec<f64> = img.px.iter().map(|p| if seed(*p) { 0.0 } else { FAR }).collect();
+ let columns: Vec<Vec<f64>> = (0..w)
+ .into_par_iter()
+ .map(|x| dt1d(&(0..h).map(|y| start[y * w + x]).collect::<Vec<_>>()))
+ .collect();
+ (0..h)
+ .into_par_iter()
+ .flat_map_iter(|y| {
+ dt1d(&(0..w).map(|x| columns[x][y]).collect::<Vec<_>>())
+ .into_iter()
+ .map(|d| d.sqrt() as f32)
+ })
+ .collect()
+}
+
+fn outline(img: &Img, o: &Outline, scale: f32) -> Result<Img> {
+ let c = parse_hex(&o.color)?;
+ let width = o.width * scale;
+ let paint = |cov: f32| {
+ let a = cov * c[3];
+ [c[0] * a, c[1] * a, c[2] * a, a]
+ };
+ match o.inside {
+ false => {
+ let d = distances(img, |p| p[3] >= 0.5);
+ let ring = Img {
+ px: d.iter().map(|d| paint((width + 0.5 - d).clamp(0.0, 1.0))).collect(),
+ ..img.clone_shape()
+ };
+ Ok(over(img, &ring))
+ }
+ true => {
+ let d = distances(img, |p| p[3] < 0.5);
+ let edge = Img {
+ px: d
+ .iter()
+ .zip(&img.px)
+ .map(|(d, p)| paint((width + 0.5 - d).clamp(0.0, 1.0) * p[3]))
+ .collect(),
+ ..img.clone_shape()
+ };
+ Ok(over(&edge, img))
+ }
+ }
+}
+
+fn shadow(img: &Img, sh: &Shadow, scale: f32) -> Result<Img> {
+ let c = parse_hex(&sh.color)?;
+ let (dx, dy) = ((sh.x * scale).round() as i32, (sh.y * scale).round() as i32);
+ let moved = img.each(|gx, gy, _| [0.0, 0.0, 0.0, img.at(gx - dx, gy - dy)[3]]);
+ Ok(blur(&moved, sh.radius * scale).each(|_, _, p| {
+ let a = p[3] * c[3];
+ [c[0] * a, c[1] * a, c[2] * a, a]
+ }))
+}
+
+fn noise(img: &Img, n: &Noise, space: Space) -> Img {
+ img.each(|gx, gy, p| {
+ if p[3] <= 0.0 {
+ return p;
+ }
+ let (cx, cy) = space.canvas(gx, gy);
+ let (ix, iy) = ((cx / n.size).floor() as i32, (cy / n.size).floor() as i32);
+ let value = |k: u32| hash2_unit(ix, iy, n.seed.wrapping_mul(3).wrapping_add(k)) * 2.0 - 1.0;
+ let d = match n.mono {
+ true => [value(0); 3],
+ false => [value(0), value(1), value(2)],
+ };
+ let a = p[3];
+ [
+ (p[0] + d[0] * n.amount * a).clamp(0.0, a),
+ (p[1] + d[1] * n.amount * a).clamp(0.0, a),
+ (p[2] + d[2] * n.amount * a).clamp(0.0, a),
+ a,
+ ]
+ })
+}
+
+fn haze(img: &Img, h: &Haze, space: Space) -> Result<Img> {
+ let bottom = parse_hex(&h.color)?;
+ let top = h.top.as_deref().map(parse_hex).transpose()?;
+ Ok(img.each(|gx, gy, p| {
+ let a = p[3];
+ if a <= 0.0 {
+ return p;
+ }
+ let fog = match top.filter(|_| h.span > 0.0) {
+ Some(t) => {
+ let k = (space.canvas(gx, gy).1 / h.span).clamp(0.0, 1.0);
+ [0, 1, 2, 3].map(|c| t[c] + (bottom[c] - t[c]) * k)
+ }
+ None => bottom,
+ };
+ let un = [p[0] / a, p[1] / a, p[2] / a];
+ let l = look::luma(un);
+ let k = h.amount.clamp(0.0, 1.0) * fog[3];
+ let out = [0, 1, 2].map(|c| {
+ let grey = un[c] + (l - un[c]) * h.desaturate.clamp(0.0, 1.0);
+ (grey + (fog[c] - grey) * k) * a
+ });
+ [out[0], out[1], out[2], a]
+ }))
+}
+
+fn smooth_noise(x: f32, y: f32, seed: u32) -> f32 {
+ let (ix, iy) = (x.floor(), y.floor());
+ let (fx, fy) = (x - ix, y - iy);
+ let (i, j) = (ix as i32, iy as i32);
+ let h = |a: i32, b: i32| hash2_unit(a, b, seed);
+ let (sx, sy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));
+ let top = h(i, j) + (h(i + 1, j) - h(i, j)) * sx;
+ let bottom = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * sx;
+ top + (bottom - top) * sy
+}
+
+fn sample(img: &Img, gx: i32, gy: i32, dx: f32, dy: f32) -> Px {
+ let (fx, fy) = (dx.floor(), dy.floor());
+ let (i, j) = (gx + fx as i32, gy + fy as i32);
+ let (fu, fv) = (dx - fx, dy - fy);
+ let (a, b, c, d) = (img.at(i, j), img.at(i + 1, j), img.at(i, j + 1), img.at(i + 1, j + 1));
+ [0, 1, 2, 3].map(|ch| {
+ let top = a[ch] + (b[ch] - a[ch]) * fu;
+ let bottom = c[ch] + (d[ch] - c[ch]) * fu;
+ top + (bottom - top) * fv
+ })
+}
+
+fn displace(img: &Img, d: &Displace, space: Space, map: Option<&Img>) -> Img {
+ let reach = d.amount * space.scale;
+ img.each(|gx, gy, _| {
+ let (ox, oy) = match map {
+ Some(m) => {
+ let p = m.at(gx, gy);
+ match p[3] > 0.0 {
+ true => ((p[0] / p[3] - 0.5) * 2.0, (p[1] / p[3] - 0.5) * 2.0),
+ false => (0.0, 0.0),
+ }
+ }
+ None => {
+ let (cx, cy) = space.canvas(gx, gy);
+ let (u, v) = (cx / d.size, cy / d.size);
+ (
+ smooth_noise(u, v, d.seed) * 2.0 - 1.0,
+ smooth_noise(u, v, d.seed ^ 0x9E37_79B9) * 2.0 - 1.0,
+ )
+ }
+ };
+ sample(img, gx, gy, ox * reach, oy * reach)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn disc(x: i32, y: i32, w: usize, h: usize, centre: (f32, f32), radius: f32) -> Img {
+ let mut img = Img::empty(x, y, w, h);
+ img.px = (0..h)
+ .flat_map(|r| (0..w).map(move |c| (c, r)))
+ .map(|(c, r)| {
+ let (gx, gy) = (x as f32 + c as f32 + 0.5, y as f32 + r as f32 + 0.5);
+ let d = ((gx - centre.0).powi(2) + (gy - centre.1).powi(2)).sqrt();
+ let a = (radius - d + 0.5).clamp(0.0, 1.0);
+ [a, 0.5 * a, 0.0, a]
+ })
+ .collect();
+ img
+ }
+
+ #[test]
+ fn a_window_with_its_margin_gives_the_full_image_pixels() {
+ let full = disc(-40, -40, 400, 300, (150.0, 140.0), 60.0);
+ let list: Vec<Effect> = serde_json::from_str(
+ r##"[{"glow":{"radius":10,"color":"#ffd080","blend":"normal"}},{"outline":{"width":4}},{"shadow":{"x":5,"y":-7,"radius":3}},{"noise":{"amount":0.2,"size":3}},{"displace":{"amount":6,"size":20}},{"blur":{"radius":2}},{"outline":{"width":3,"inside":true,"color":"#2040ff"}}]"##,
+ )
+ .unwrap();
+ let space = Space {
+ scale: 1.0,
+ tx: 0.0,
+ ty: 0.0,
+ };
+ let none = |_: &str| Ok(None);
+ let (_, reference) = run(&list, full.clone(), space, &none).unwrap();
+ let m = margin(&list, 1.0);
+ let (tx, ty, tw, th) = (128, 64, 64, 64);
+ let window = full.crop(tx - m, ty - m, tw + 2 * m as usize, th + 2 * m as usize);
+ let (_, local) = run(&list, window, space, &none).unwrap();
+ let (a, b) = (reference.crop(tx, ty, tw, th), local.crop(tx, ty, tw, th));
+ let worst =
+ a.px.iter()
+ .zip(&b.px)
+ .flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs()))
+ .fold(0.0f32, f32::max);
+ assert!(worst < 1e-5, "tile and full image differ by {worst}");
+ assert!(a.px.iter().any(|p| p[3] > 0.0) && a.px.iter().any(|p| p[3] < 1.0));
+ }
+
+ #[test]
+ fn the_outline_rings_the_shape_at_its_width() {
+ let shape = disc(0, 0, 100, 100, (50.0, 50.0), 20.0);
+ let o = Outline {
+ width: 5.0,
+ color: "#000000".into(),
+ inside: false,
+ };
+ let out = outline(&shape, &o, 1.0).unwrap();
+ assert!(out.at(50 + 23, 50)[3] > 0.99 && out.at(50 + 23, 50)[0] < 0.01);
+ assert!(out.at(50 + 27, 50)[3] < 0.01);
+ assert_eq!(out.at(50, 50), shape.at(50, 50));
+ }
+
+ #[test]
+ fn blur_keeps_what_there_is_and_spreads_it() {
+ let shape = disc(0, 0, 200, 200, (100.0, 100.0), 30.0);
+ let total = |i: &Img| i.px.iter().map(|p| p[3]).sum::<f32>();
+ [1.5f32, 6.0, 24.0].iter().for_each(|s| {
+ let soft = blur(&shape, *s);
+ assert!((total(&soft) - total(&shape)).abs() / total(&shape) < 0.01, "sigma {s}");
+ assert!(soft.at(100 + 30 + (*s as i32), 100)[3] > 0.01, "sigma {s}");
+ });
+ }
+
+ #[test]
+ fn noise_and_displacement_repeat_with_their_seed() {
+ let shape = disc(0, 0, 64, 64, (32.0, 32.0), 20.0);
+ let space = Space {
+ scale: 1.0,
+ tx: 0.0,
+ ty: 0.0,
+ };
+ let n = Noise {
+ amount: 0.3,
+ size: 2.0,
+ seed: 4,
+ mono: false,
+ };
+ assert_eq!(noise(&shape, &n, space), noise(&shape, &n, space));
+ assert_ne!(
+ noise(&shape, &n, space),
+ noise(&shape, &Noise { seed: 5, ..n.clone() }, space)
+ );
+ let d = Displace::default();
+ assert_eq!(displace(&shape, &d, space, None), displace(&shape, &d, space, None));
+ assert_ne!(displace(&shape, &d, space, None), shape);
+ }
+}
+
+#[cfg(test)]
+mod timing {
+ use super::*;
+
+ #[test]
+ #[ignore = "timing: cargo test --release -p klad-render glow_steps -- --ignored --nocapture"]
+ fn glow_steps() {
+ use std::time::Instant;
+ let mut img = Img::empty(-38, -38, 332, 332);
+ img.px.iter_mut().enumerate().for_each(|(i, p)| {
+ if (i / 332 + i % 332) % 7 < 3 {
+ *p = [0.8, 0.6, 0.2, 1.0];
+ }
+ });
+ let g = Glow {
+ radius: 32.0 / 3.0,
+ ..Glow::default()
+ };
+ let best = |f: &dyn Fn()| {
+ (0..20)
+ .map(|_| {
+ let t = Instant::now();
+ f();
+ t.elapsed().as_secs_f64() * 1000.0
+ })
+ .fold(f64::MAX, f64::min)
+ };
+ let each = best(&|| {
+ img.each(|_, _, p| p);
+ });
+ let blurred = best(&|| {
+ blur(&img, g.radius);
+ });
+ let glowed = best(&|| {
+ glow(&img, &g, 1.0).unwrap();
+ });
+ let crop = best(&|| {
+ img.crop(0, 0, 256, 256);
+ });
+ println!("332 px window: each {each:.2} ms, blur {blurred:.2} ms, glow {glowed:.2} ms, crop {crop:.2} ms");
+ }
+}
diff --git a/crates/render/src/export.rs b/crates/render/src/export.rs
new file mode 100644
index 0000000..d6e4b03
--- /dev/null
+++ b/crates/render/src/export.rs
@@ -0,0 +1,316 @@
+use crate::{Ctx, Rasters, background, draw_layer, draw_layers, f16_info, rgba8_info};
+use anyhow::{Result, anyhow, bail};
+use klad_core::doc::{Blend, Document, Layer};
+use rayon::prelude::*;
+use skia_safe::{
+ AlphaType, ColorSpace, ColorType, CubicResampler, FilterMode, Image, ImageInfo, MipmapMode, Pixmap,
+ SamplingOptions, image::CachingHint, png_encoder, surfaces,
+};
+
+pub const SNAP: f32 = 0.13;
+pub const MAX_SCALE: f32 = 8.0;
+
+const BAYER: [u8; 64] = [
+ 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30,
+ 54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23,
+ 61, 29, 53, 21,
+];
+
+pub enum Target<'a> {
+ Frame,
+ Layer(&'a Layer),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Options {
+ pub scale: f32,
+ pub background: bool,
+ pub references: bool,
+}
+
+pub fn render(doc: &Document, frame: u32, rasters: &Rasters, target: &Target, options: Options) -> Result<Image> {
+ let scale = options.scale;
+ if !(1.0 / 16.0..=MAX_SCALE).contains(&scale) {
+ bail!("export scale {scale} is outside 1/16..{MAX_SCALE}");
+ }
+ let (w, h) = (
+ ((doc.canvas.width as f32 * scale).round() as u32).max(1),
+ ((doc.canvas.height as f32 * scale).round() as u32).max(1),
+ );
+ let mut surface =
+ surfaces::raster(&f16_info(w, h), None, None).ok_or_else(|| anyhow!("cannot allocate {w}x{h}"))?;
+ let canvas = surface.canvas();
+ let fill = match (options.background, target) {
+ (true, Target::Frame) => background(doc.canvas.background.as_deref())?,
+ _ => background(None)?,
+ };
+ canvas.clear(fill);
+ canvas.scale((scale, scale));
+ let sampling = if scale > 1.0 {
+ Some(SamplingOptions::from(CubicResampler::mitchell()))
+ } else if scale < 1.0 {
+ Some(SamplingOptions::new(FilterMode::Linear, MipmapMode::Linear))
+ } else {
+ None
+ };
+ let ctx = Ctx {
+ sampling,
+ doc: Some(doc),
+ references: options.references,
+ ..Ctx::full(frame, rasters)
+ };
+ match target {
+ Target::Frame => draw_layers(canvas, &doc.layers, ctx)?,
+ Target::Layer(layer) => {
+ let mut alone = (*layer).clone();
+ alone.visible = true;
+ alone.blend = Blend::Normal;
+ draw_layer(canvas, &alone, ctx)?;
+ }
+ }
+ Ok(surface.image_snapshot())
+}
+
+pub(crate) fn f16_pixels(image: &Image, alpha: AlphaType) -> Result<Vec<half::f16>> {
+ let (w, h) = (image.width() as usize, image.height() as usize);
+ let info = ImageInfo::new((w as i32, h as i32), ColorType::RGBAF16, alpha, ColorSpace::new_srgb());
+ let mut pixels = vec![half::f16::ZERO; w * h * 4];
+ if !image.read_pixels(
+ &info,
+ bytemuck::cast_slice_mut::<half::f16, u8>(&mut pixels),
+ w * 8,
+ (0, 0),
+ CachingHint::Allow,
+ ) {
+ return Err(anyhow!("cannot read pixels"));
+ }
+ Ok(pixels)
+}
+
+pub fn quantize(value: f32, threshold: f32) -> u8 {
+ let x = value.clamp(0.0, 1.0) * 255.0;
+ let near = x.round();
+ if (x - near).abs() <= SNAP {
+ return near as u8;
+ }
+ (x + threshold).floor().clamp(0.0, 255.0) as u8
+}
+
+pub fn dither8(image: &Image) -> Result<Vec<u8>> {
+ let w = image.width() as usize;
+ let pixels = f16_pixels(image, AlphaType::Premul)?;
+ let mut out = vec![0u8; pixels.len()];
+ out.par_chunks_mut(w * 4)
+ .zip(pixels.par_chunks(w * 4))
+ .enumerate()
+ .for_each(|(y, (row, source))| {
+ row.as_chunks_mut::<4>()
+ .0
+ .iter_mut()
+ .zip(source.as_chunks::<4>().0)
+ .enumerate()
+ .for_each(|(x, (px, from))| {
+ let t = (BAYER[(y % 8) * 8 + x % 8] as f32 + 0.5) / 64.0;
+ let a = from[3].to_f32();
+ if a <= 0.0 {
+ return;
+ }
+ let alpha = quantize(a, t);
+ if alpha > 0 {
+ let [r, g, b] = [0, 1, 2].map(|c| quantize(from[c].to_f32() / a, t));
+ *px = [r, g, b, alpha];
+ }
+ });
+ });
+ Ok(out)
+}
+
+pub fn png8(image: &Image) -> Result<Vec<u8>> {
+ let (w, h) = (image.width() as u32, image.height() as u32);
+ let mut rgba = dither8(image)?;
+ let pixmap = Pixmap::new(&rgba8_info(w, h), &mut rgba, w as usize * 4).ok_or_else(|| anyhow!("bad pixmap"))?;
+ encode(&pixmap)
+}
+
+pub fn png16(image: &Image) -> Result<Vec<u8>> {
+ let (w, h) = (image.width(), image.height());
+ let mut pixels = f16_pixels(image, AlphaType::Unpremul)?;
+ let info = ImageInfo::new((w, h), ColorType::RGBAF16, AlphaType::Unpremul, ColorSpace::new_srgb());
+ let pixmap = Pixmap::new(
+ &info,
+ bytemuck::cast_slice_mut::<half::f16, u8>(&mut pixels),
+ w as usize * 8,
+ )
+ .ok_or_else(|| anyhow!("bad pixmap"))?;
+ encode(&pixmap)
+}
+
+pub(crate) fn encode(pixmap: &Pixmap) -> Result<Vec<u8>> {
+ let mut out = Vec::new();
+ if !png_encoder::encode(pixmap, &mut out, &png_encoder::Options::default()) {
+ bail!("PNG encoding failed");
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Linear, Node, Paint, Shape, Stop};
+
+ fn ramp(width: u32, from: &str, to: &str) -> Document {
+ let mut doc = Document::new(width, 64);
+ let mut bar = Node::new(
+ "n1",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: width as f32,
+ h: 64.0,
+ radius: 0.0,
+ },
+ );
+ bar.fill = Some(Paint::Linear {
+ linear: Linear {
+ from: [0.0, 0.0],
+ to: [width as f32, 0.0],
+ stops: vec![Stop(0.0, from.into()), Stop(1.0, to.into())],
+ },
+ });
+ doc.layers.push(Layer::vector("v", "v", "c1", vec![bar]));
+ doc
+ }
+
+ fn block_means(rgba: &[u8], w: usize, h: usize) -> Vec<f32> {
+ (0..w / 8)
+ .map(|b| {
+ let sum: f32 = (0..h)
+ .flat_map(|y| (b * 8..b * 8 + 8).map(move |x| rgba[(y * w + x) * 4] as f32))
+ .sum();
+ sum / (8 * h) as f32
+ })
+ .collect()
+ }
+
+ #[test]
+ fn dithering_turns_bands_into_a_smooth_ramp() {
+ let doc = ramp(1024, "#202020", "#282828");
+ let options = Options {
+ scale: 1.0,
+ background: false,
+ references: false,
+ };
+ let image = render(&doc, 0, &Rasters::new(), &Target::Frame, options).unwrap();
+ let dithered = dither8(&image).unwrap();
+ let ideal = |b: usize| 32.0 + 8.0 * (b as f32 * 8.0 + 4.0) / 1024.0;
+ let drift = |means: &[f32]| {
+ means
+ .iter()
+ .enumerate()
+ .map(|(b, m)| (m - ideal(b)).abs())
+ .fold(0.0f32, f32::max)
+ };
+ let worst = drift(&block_means(&dithered, 1024, 64));
+ assert!(worst < 0.2, "dithered blocks drift {worst} levels from the ramp");
+ let plain = crate::read_rgba8(&image).unwrap();
+ let banded = block_means(&plain.rgba, 1024, 64);
+ assert!(drift(&banded) > 0.4, "{}", drift(&banded));
+ let png = png8(&image).unwrap();
+ assert_eq!(&png[1..4], b"PNG");
+ assert_eq!(png[24], 8);
+ }
+
+ #[test]
+ fn flat_colours_stay_flat_and_transparency_stays_clean() {
+ let mut doc = Document::new(64, 64);
+ let square = Node::new(
+ "n1",
+ Shape::Rect {
+ x: 8.0,
+ y: 8.0,
+ w: 32.0,
+ h: 32.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#f4efe6");
+ doc.layers.push(Layer::vector("v", "v", "c1", vec![square]));
+ doc.canvas.background = Some("#336699".into());
+ let options = Options {
+ scale: 1.0,
+ background: false,
+ references: false,
+ };
+ let image = render(&doc, 0, &Rasters::new(), &Target::Frame, options).unwrap();
+ let rgba = dither8(&image).unwrap();
+ let px = |x: usize, y: usize| [0, 1, 2, 3].map(|c| rgba[(y * 64 + x) * 4 + c]);
+ assert!((8..40).all(|y| (8..40).all(|x| px(x, y) == [0xf4, 0xef, 0xe6, 255])));
+ assert_eq!(px(50, 50), [0, 0, 0, 0]);
+ let with_bg = render(
+ &doc,
+ 0,
+ &Rasters::new(),
+ &Target::Frame,
+ Options {
+ background: true,
+ ..options
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ &dither8(&with_bg).unwrap()[(50 * 64 + 50) * 4..(50 * 64 + 50) * 4 + 4],
+ [0x33, 0x66, 0x99, 255]
+ );
+ }
+
+ #[test]
+ fn scaled_exports_keep_vectors_sharp_and_sixteen_bit_pngs_are_sixteen_bit() {
+ let mut doc = Document::new(100, 50);
+ let mut dot = Node::new(
+ "n1",
+ Shape::Ellipse {
+ cx: 50.0,
+ cy: 25.0,
+ rx: 20.0,
+ ry: 20.0,
+ },
+ )
+ .filled("#000000");
+ dot.opacity = 0.5;
+ doc.layers.push(Layer::vector("v", "v", "c1", vec![dot]));
+ let image = render(
+ &doc,
+ 0,
+ &Rasters::new(),
+ &Target::Layer(&doc.layers[0]),
+ Options {
+ scale: 2.0,
+ background: false,
+ references: false,
+ },
+ )
+ .unwrap();
+ assert_eq!((image.width(), image.height()), (200, 100));
+ let rgba = dither8(&image).unwrap();
+ let alpha = |x: usize, y: usize| rgba[(y * 200 + x) * 4 + 3];
+ assert!((127..=128).contains(&alpha(100, 50)));
+ let edge: Vec<u8> = (136..146).map(|x| alpha(x, 50)).collect();
+ assert!(edge.iter().filter(|a| (5..120).contains(*a)).count() <= 2, "{edge:?}");
+ let png = png16(&image).unwrap();
+ assert_eq!(png[24], 16, "bit depth");
+ assert!(
+ render(
+ &doc,
+ 0,
+ &Rasters::new(),
+ &Target::Frame,
+ Options {
+ scale: 20.0,
+ background: false,
+ references: false,
+ }
+ )
+ .is_err()
+ );
+ }
+}
diff --git a/crates/render/src/form.rs b/crates/render/src/form.rs
new file mode 100644
index 0000000..d93d8ad
--- /dev/null
+++ b/crates/render/src/form.rs
@@ -0,0 +1,709 @@
+use crate::shapes::{P, Run, area};
+use klad_core::cut::inside_polygon;
+use klad_core::rng::Rng;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Form {
+ Round,
+ Flat { facing: [f32; 3] },
+ Cylinder { axis: f32 },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Lighting {
+ Direction { toward: [f32; 3] },
+ Lamp { at: [f32; 3] },
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct FormRules {
+ pub form: Form,
+ pub light: Lighting,
+ pub colour: [f32; 3],
+ pub key: [f32; 3],
+ pub fill: [f32; 3],
+ pub bounce: [f32; 3],
+ pub core: f32,
+ pub weight: f32,
+ pub angle: f32,
+ pub decisive: f32,
+ pub vary: f32,
+ pub seed: u32,
+ pub spill: bool,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct FormStroke {
+ pub run: Run,
+ pub rgb: [f32; 3],
+ pub size: f32,
+ pub bold: bool,
+ pub opacity: f32,
+ pub hand: f32,
+}
+
+const STEP: f32 = 2.0;
+const CUT: f32 = 0.14;
+
+fn sub(a: P, b: P) -> P {
+ [a[0] - b[0], a[1] - b[1]]
+}
+
+fn len(a: P) -> f32 {
+ libm::sqrtf(a[0] * a[0] + a[1] * a[1])
+}
+
+fn unit3(v: [f32; 3]) -> [f32; 3] {
+ let d = libm::sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).max(1e-6);
+ [v[0] / d, v[1] / d, v[2] / d]
+}
+
+fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+
+fn nearest(poly: &[P], p: P) -> (f32, P) {
+ (0..poly.len())
+ .map(|i| {
+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
+ let ab = sub(b, a);
+ let t = (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / (ab[0] * ab[0] + ab[1] * ab[1]).max(1e-9))
+ .clamp(0.0, 1.0);
+ let q = [a[0] + ab[0] * t, a[1] + ab[1] * t];
+ (len(sub(p, q)), q)
+ })
+ .fold((f32::MAX, [0.0, 0.0]), |best, c| if c.0 < best.0 { c } else { best })
+}
+
+fn inside(poly: &[P], p: P) -> bool {
+ inside_polygon(poly, (p[0], p[1]))
+}
+
+fn across(poly: &[P], p: P, dir: P) -> (f32, f32) {
+ let hits: Vec<f32> = (0..poly.len())
+ .filter_map(|i| {
+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
+ let e = sub(b, a);
+ let den = dir[0] * e[1] - dir[1] * e[0];
+ if den.abs() < 1e-9 {
+ return None;
+ }
+ let w = sub(a, p);
+ let s = (w[0] * e[1] - w[1] * e[0]) / den;
+ let u = (w[0] * dir[1] - w[1] * dir[0]) / den;
+ (0.0..=1.0).contains(&u).then_some(s)
+ })
+ .collect();
+ let lo = hits.iter().copied().filter(|s| *s <= 0.0).fold(f32::MIN, f32::max);
+ let hi = hits.iter().copied().filter(|s| *s >= 0.0).fold(f32::MAX, f32::min);
+ (
+ if lo == f32::MIN { 0.0 } else { lo },
+ if hi == f32::MAX { 0.0 } else { hi },
+ )
+}
+
+struct Field {
+ origin: P,
+ cell: f32,
+ nx: usize,
+ ny: usize,
+ signed: Vec<f32>,
+}
+
+impl Field {
+ fn new(poly: &[P], lo: P, hi: P) -> Self {
+ let cell = ((hi[0] - lo[0]).max(hi[1] - lo[1]) / 200.0).max(1.0);
+ let pad = cell * 4.0;
+ let origin = [lo[0] - pad, lo[1] - pad];
+ let nx = ((hi[0] - lo[0] + 2.0 * pad) / cell) as usize + 2;
+ let ny = ((hi[1] - lo[1] + 2.0 * pad) / cell) as usize + 2;
+ let signed = (0..ny)
+ .flat_map(|j| (0..nx).map(move |i| (i, j)))
+ .map(|(i, j)| {
+ let p = [origin[0] + cell * i as f32, origin[1] + cell * j as f32];
+ let d = nearest(poly, p).0;
+ if inside(poly, p) { d } else { -d }
+ })
+ .collect();
+ Field {
+ origin,
+ cell,
+ nx,
+ ny,
+ signed,
+ }
+ }
+
+ fn at(&self, p: P) -> f32 {
+ let x = ((p[0] - self.origin[0]) / self.cell).clamp(0.0, (self.nx - 1) as f32 - 1e-3);
+ let y = ((p[1] - self.origin[1]) / self.cell).clamp(0.0, (self.ny - 1) as f32 - 1e-3);
+ let (i, j) = (x as usize, y as usize);
+ let (fx, fy) = (x - i as f32, y - j as f32);
+ let v = |i: usize, j: usize| self.signed[j * self.nx + i];
+ let top = v(i, j) * (1.0 - fx) + v(i + 1, j) * fx;
+ let bottom = v(i, j + 1) * (1.0 - fx) + v(i + 1, j + 1) * fx;
+ top * (1.0 - fy) + bottom * fy
+ }
+
+ fn inward(&self, p: P) -> P {
+ let e = self.cell;
+ let gx = self.at([p[0] + e, p[1]]) - self.at([p[0] - e, p[1]]);
+ let gy = self.at([p[0], p[1] + e]) - self.at([p[0], p[1] - e]);
+ let d = libm::sqrtf(gx * gx + gy * gy);
+ match d > 1e-6 {
+ true => [gx / d, gy / d],
+ false => [0.0, 0.0],
+ }
+ }
+}
+
+struct Shape<'a> {
+ poly: &'a [P],
+ field: Field,
+ reach: f32,
+ reference: f32,
+ lo: P,
+ hi: P,
+}
+
+impl<'a> Shape<'a> {
+ fn new(poly: &'a [P], rules: &FormRules) -> Self {
+ let (lo, hi) = poly.iter().fold(([f32::MAX; 2], [f32::MIN; 2]), |(lo, hi), q| {
+ ([lo[0].min(q[0]), lo[1].min(q[1])], [hi[0].max(q[0]), hi[1].max(q[1])])
+ });
+ let field = Field::new(poly, lo, hi);
+ let (best, reach) = field
+ .signed
+ .iter()
+ .enumerate()
+ .fold((0, 1.0f32), |best, (k, d)| if *d > best.1 { (k, *d) } else { best });
+ let centre = [
+ field.origin[0] + field.cell * (best % field.nx) as f32,
+ field.origin[1] + field.cell * (best / field.nx) as f32,
+ ];
+ let mut shape = Shape {
+ poly,
+ field,
+ reach,
+ reference: 1.0,
+ lo,
+ hi,
+ };
+ if let Lighting::Lamp { at } = rules.light {
+ let h = shape.height(&rules.form, centre);
+ shape.reference =
+ libm::sqrtf((at[0] - centre[0]).powi(2) + (at[1] - centre[1]).powi(2) + (at[2] - h).powi(2)).max(1.0);
+ }
+ shape
+ }
+
+ fn dome(&self, q: P) -> f32 {
+ let v = (self.field.at(q) / self.reach).clamp(0.0, 1.0);
+ self.reach * libm::sqrtf((1.0 - (1.0 - v) * (1.0 - v)).max(0.0))
+ }
+
+ fn round(&self, p: P) -> (f32, [f32; 3]) {
+ let u = (self.field.at(p) / self.reach).clamp(0.0, 1.0);
+ let g = self.field.inward(p);
+ let rise = libm::sqrtf((1.0 - (1.0 - u) * (1.0 - u)).max(1e-4));
+ let slope = (1.0 - u) / rise;
+ let sharp = unit3([-g[0] * slope, -g[1] * slope, 1.0]);
+ let blend = ((u - 0.2) / 0.25).clamp(0.0, 1.0);
+ if blend == 0.0 {
+ return (self.reach * rise, sharp);
+ }
+ let e = (self.reach * 0.14).max(1.5);
+ let hx = (self.dome([p[0] + e, p[1]]) - self.dome([p[0] - e, p[1]])) / (2.0 * e);
+ let hy = (self.dome([p[0], p[1] + e]) - self.dome([p[0], p[1] - e])) / (2.0 * e);
+ let soft = unit3([-hx, -hy, 1.0]);
+ let mixed = [0, 1, 2].map(|c| sharp[c] * (1.0 - blend) + soft[c] * blend);
+ (self.reach * rise, unit3(mixed))
+ }
+
+ fn cylinder(&self, p: P, axis: f32) -> (f32, [f32; 3]) {
+ let a = axis.to_radians();
+ let perp = [-libm::sinf(a), libm::cosf(a)];
+ let (s1, s2) = across(self.poly, p, perp);
+ let half = ((s2 - s1) / 2.0).max(1e-3);
+ let t = (-(s1 + s2) / 2.0 / half).clamp(-1.0, 1.0);
+ let z = libm::sqrtf((1.0 - t * t).max(0.0));
+ (half * z, unit3([perp[0] * t, perp[1] * t, z]))
+ }
+
+ fn height(&self, form: &Form, p: P) -> f32 {
+ match form {
+ Form::Round => self.round(p).0,
+ Form::Cylinder { axis } => self.cylinder(p, *axis).0,
+ Form::Flat { .. } => 0.0,
+ }
+ }
+
+ fn surface(&self, form: &Form, p: P) -> (f32, [f32; 3]) {
+ match form {
+ Form::Round => self.round(p),
+ Form::Cylinder { axis } => self.cylinder(p, *axis),
+ Form::Flat { facing } => (0.0, unit3(*facing)),
+ }
+ }
+
+ fn light(&self, rules: &FormRules, p: P) -> (f32, f32, [f32; 3]) {
+ let (h, n) = self.surface(&rules.form, p);
+ let (l, falloff) = match rules.light {
+ Lighting::Direction { toward } => (unit3(toward), 1.0),
+ Lighting::Lamp { at } => {
+ let v = [at[0] - p[0], at[1] - p[1], at[2] - h];
+ let d = libm::sqrtf(dot3(v, v)).max(1.0);
+ (unit3(v), ((self.reference / d) * (self.reference / d)).clamp(0.05, 3.0))
+ }
+ };
+ (dot3(n, l), falloff, n)
+ }
+
+ fn colour(&self, rules: &FormRules, p: P) -> ([f32; 3], f32) {
+ let (facing, falloff, n) = self.light(rules, p);
+ let key = facing.max(0.0) * falloff;
+ let sky = 0.5 * (1.0 - n[1]);
+ let ground = 0.5 * (1.0 + n[1]);
+ let core = match facing < 0.08 {
+ true => 1.0 - rules.core * libm::expf(-((facing + 0.12) / 0.1).powi(2)),
+ false => 1.0,
+ };
+ let rgb = [0, 1, 2]
+ .map(|c| rules.colour[c] * (rules.key[c] * key + (rules.fill[c] * sky + rules.bounce[c] * ground) * core));
+ (rgb, facing * falloff)
+ }
+
+ fn band(&self, rules: &FormRules, p: P) -> f32 {
+ let (facing, falloff, _) = self.light(rules, p);
+ facing * falloff
+ }
+
+ fn direction(&self, rules: &FormRules, p: P) -> P {
+ let toward = |a: f32| [libm::cosf(a.to_radians()), libm::sinf(a.to_radians())];
+ match rules.form {
+ Form::Flat { .. } => toward(rules.angle),
+ Form::Cylinder { axis } => toward(axis),
+ Form::Round => {
+ let e = 1.5;
+ let gx = self.band(rules, [p[0] + e, p[1]]) - self.band(rules, [p[0] - e, p[1]]);
+ let gy = self.band(rules, [p[0], p[1] + e]) - self.band(rules, [p[0], p[1] - e]);
+ match libm::sqrtf(gx * gx + gy * gy) > 1e-4 {
+ true => {
+ let d = libm::sqrtf(gx * gx + gy * gy);
+ [-gy / d, gx / d]
+ }
+ false => {
+ let g = self.field.inward(p);
+ [-g[1], g[0]]
+ }
+ }
+ }
+ }
+ }
+
+ fn trace(&self, rules: &FormRules, start: P, length: f32, limit: f32) -> Vec<P> {
+ let level = self.band(rules, start);
+ let walk = |sign: f32| {
+ let mut out = Vec::new();
+ let (mut p, mut prev) = (start, [0.0f32, 0.0f32]);
+ let mut travelled = 0.0;
+ while travelled < length / 2.0 {
+ let mut d = self.direction(rules, p);
+ if prev != [0.0, 0.0] && d[0] * prev[0] + d[1] * prev[1] < 0.0 {
+ d = [-d[0], -d[1]];
+ }
+ if prev == [0.0, 0.0] {
+ d = [d[0] * sign, d[1] * sign];
+ }
+ let next = [p[0] + d[0] * STEP, p[1] + d[1] * STEP];
+ if self.field.at(next) < limit || (self.band(rules, next) - level).abs() > CUT {
+ break;
+ }
+ out.push(next);
+ (p, prev) = (next, d);
+ travelled += STEP;
+ }
+ out
+ };
+ let back = walk(-1.0);
+ let ahead = walk(1.0);
+ back.into_iter()
+ .rev()
+ .chain(std::iter::once(start))
+ .chain(ahead)
+ .collect()
+ }
+}
+
+fn varied(rgb: [f32; 3], rng: &mut Rng, vary: f32) -> [f32; 3] {
+ let k = 1.0 + rng.signed() * vary;
+ let warm = rng.signed() * vary * 0.5;
+ [rgb[0] * k * (1.0 + warm), rgb[1] * k, rgb[2] * k * (1.0 - warm)]
+}
+
+struct Pass {
+ size: f32,
+ spacing: f32,
+ length: (f32, f32),
+ bold: bool,
+ opacity: f32,
+ vary: f32,
+ keep: fn(f32) -> bool,
+ scatter: f32,
+ hand: f32,
+}
+
+fn everywhere(_: f32) -> bool {
+ true
+}
+
+fn turning(band: f32) -> bool {
+ band.abs() < 0.25 || band > 0.85
+}
+
+fn lit(band: f32) -> bool {
+ band > 0.35
+}
+
+fn shadowed(band: f32) -> bool {
+ band < 0.02
+}
+
+pub fn paint_form(areas: &[Vec<P>], rules: &FormRules) -> Vec<FormStroke> {
+ let w = rules.weight.max(1.0);
+ let passes = [
+ Pass {
+ size: w * 2.0,
+ spacing: 0.55,
+ length: (2.5, 5.0),
+ bold: false,
+ opacity: 1.0,
+ vary: 1.0,
+ keep: everywhere,
+ scatter: 0.0,
+ hand: 0.35,
+ },
+ Pass {
+ size: w,
+ spacing: 0.85,
+ length: (2.5, 5.0),
+ bold: false,
+ opacity: 0.95,
+ vary: 1.0,
+ keep: everywhere,
+ scatter: 0.0,
+ hand: 1.0,
+ },
+ Pass {
+ size: w * 0.55,
+ spacing: 0.85,
+ length: (2.5, 5.0),
+ bold: false,
+ opacity: 0.9,
+ vary: 0.8,
+ keep: turning,
+ scatter: 0.0,
+ hand: 1.0,
+ },
+ Pass {
+ size: w * 1.1,
+ spacing: 0.0,
+ length: (1.8, 3.5),
+ bold: true,
+ opacity: 0.9,
+ vary: 1.4,
+ keep: lit,
+ scatter: 0.25,
+ hand: 1.0,
+ },
+ Pass {
+ size: w * 1.7,
+ spacing: 0.0,
+ length: (2.0, 4.0),
+ bold: false,
+ opacity: 0.6,
+ vary: 0.6,
+ keep: shadowed,
+ scatter: 0.08,
+ hand: 1.0,
+ },
+ ];
+ let mut rng = Rng::new(rules.seed as u64 * 48_271 + 29);
+ let (body, finish) = passes.split_at(3);
+ let shapes = shapes_of(areas, rules);
+ shapes
+ .iter()
+ .flat_map(|shape| {
+ let area = area(shape.poly).abs();
+ let mut out: Vec<FormStroke> = body
+ .iter()
+ .flat_map(|pass| pass_strokes(shape, rules, pass, area, w, &mut rng))
+ .collect();
+ if rules.spill {
+ out.extend(edge_strokes(shape, rules, w, &mut rng));
+ }
+ out.extend(
+ finish
+ .iter()
+ .flat_map(|pass| pass_strokes(shape, rules, pass, area, w, &mut rng)),
+ );
+ out
+ })
+ .collect()
+}
+
+fn pass_strokes(shape: &Shape, rules: &FormRules, pass: &Pass, area: f32, w: f32, rng: &mut Rng) -> Vec<FormStroke> {
+ let seeds: Vec<P> = match pass.scatter > 0.0 {
+ true => {
+ let count = (area / (w * w) * pass.scatter * rules.decisive).round() as usize;
+ (0..count)
+ .map(|_| [rng.range(shape.lo[0], shape.hi[0]), rng.range(shape.lo[1], shape.hi[1])])
+ .collect()
+ }
+ false => {
+ let step = (pass.size * pass.spacing).max(1.5);
+ let (nx, ny) = (
+ ((shape.hi[0] - shape.lo[0]) / step) as usize + 1,
+ ((shape.hi[1] - shape.lo[1]) / step) as usize + 1,
+ );
+ (0..ny)
+ .flat_map(|j| (0..nx).map(move |i| (i, j)))
+ .map(|(i, j)| {
+ [
+ shape.lo[0] + step * (i as f32 + 0.5) + rng.signed() * step * 0.4,
+ shape.lo[1] + step * (j as f32 + 0.5) + rng.signed() * step * 0.4,
+ ]
+ })
+ .collect()
+ }
+ };
+ seeds
+ .into_iter()
+ .filter_map(|seed| {
+ let length = rng.range(pass.length.0, pass.length.1) * pass.size;
+ let size = pass.size * rng.range(0.85, 1.15);
+ let margin = (size * 0.2).min(shape.reach * 0.5);
+ let (start, limit) = match rules.spill {
+ true => (0.0, -size * 0.5),
+ false => (margin, margin),
+ };
+ if shape.field.at(seed) < start || !(pass.keep)(shape.band(rules, seed)) {
+ return None;
+ }
+ let line = shape.trace(rules, seed, length, limit);
+ if line.len() < 3 {
+ return None;
+ }
+ let (rgb, _) = shape.colour(rules, line[line.len() / 2]);
+ Some(FormStroke {
+ run: line.iter().map(|p| [p[0], p[1], 1.0]).collect(),
+ rgb: varied(rgb, rng, rules.vary * pass.vary),
+ size,
+ bold: pass.bold,
+ opacity: pass.opacity,
+ hand: pass.hand,
+ })
+ })
+ .collect::<Vec<_>>()
+}
+
+fn edge_strokes(shape: &Shape, rules: &FormRules, w: f32, rng: &mut Rng) -> Vec<FormStroke> {
+ let poly = shape.poly;
+ let points: Vec<P> = (0..poly.len())
+ .flat_map(|i| {
+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
+ let n = (len(sub(b, a)) / STEP).ceil().max(1.0) as usize;
+ (0..n).map(move |k| {
+ let t = k as f32 / n as f32;
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
+ })
+ })
+ .collect();
+ let size = w * 0.9;
+ let per = ((size * 3.0) / STEP).max(3.0) as usize;
+ (0..points.len())
+ .step_by((per / 3).max(1))
+ .filter_map(|start| {
+ let level = shape.band(rules, points[start]);
+ let line: Vec<P> = (0..per)
+ .map(|k| points[(start + k) % points.len()])
+ .take_while(|p| (shape.band(rules, *p) - level).abs() <= CUT)
+ .collect();
+ if line.len() < 3 {
+ return None;
+ }
+ let (rgb, _) = shape.colour(rules, line[line.len() / 2]);
+ Some(FormStroke {
+ run: line.iter().map(|p| [p[0], p[1], 1.0]).collect(),
+ rgb: varied(rgb, rng, rules.vary),
+ size: size * rng.range(0.85, 1.15),
+ bold: false,
+ opacity: 0.95,
+ hand: 0.6,
+ })
+ })
+ .collect()
+}
+
+fn shapes_of<'a>(areas: &'a [Vec<P>], rules: &FormRules) -> Vec<Shape<'a>> {
+ let mut shapes: Vec<Shape> = areas
+ .iter()
+ .filter(|a| a.len() >= 3)
+ .map(|a| Shape::new(a, rules))
+ .collect();
+ let nearest = shapes.iter().map(|s| s.reference).fold(f32::MAX, f32::min);
+ shapes.iter_mut().for_each(|s| s.reference = nearest);
+ shapes
+}
+
+pub fn shade_at(areas: &[Vec<P>], rules: &FormRules, p: P) -> Option<([f32; 3], f32)> {
+ shapes_of(areas, rules)
+ .iter()
+ .find(|s| inside(s.poly, p))
+ .map(|s| s.colour(rules, p))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn disc(cx: f32, cy: f32, r: f32) -> Vec<P> {
+ (0..96)
+ .map(|i| {
+ let a = core::f32::consts::TAU * i as f32 / 96.0;
+ [cx + r * libm::cosf(a), cy + r * libm::sinf(a)]
+ })
+ .collect()
+ }
+
+ fn rules(light: Lighting) -> FormRules {
+ FormRules {
+ form: Form::Round,
+ light,
+ colour: [0.6, 0.6, 0.6],
+ key: [1.0, 0.95, 0.9],
+ fill: [0.09, 0.1, 0.13],
+ bounce: [0.08, 0.06, 0.05],
+ core: 0.35,
+ weight: 10.0,
+ angle: 30.0,
+ decisive: 1.0,
+ vary: 0.03,
+ seed: 4,
+ spill: false,
+ }
+ }
+
+ fn luma(rgb: [f32; 3]) -> f32 {
+ 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
+ }
+
+ #[test]
+ fn a_round_form_is_lit_on_the_light_side_and_its_strokes_stay_inside_and_on_one_band() {
+ let shape = disc(100.0, 100.0, 60.0);
+ let r = rules(Lighting::Direction {
+ toward: [-1.0, 0.0, 0.5],
+ });
+ let strokes = paint_form(std::slice::from_ref(&shape), &r);
+ assert!(strokes.len() > 40);
+ assert!(
+ strokes
+ .iter()
+ .all(|s| s.run.iter().all(|q| inside(&shape, [q[0], q[1]])))
+ );
+ let side = |left: bool| {
+ let picked: Vec<f32> = strokes
+ .iter()
+ .filter(|s| {
+ !s.bold && (s.run[s.run.len() / 2][0] < 70.0) == left && (s.run[s.run.len() / 2][0] > 130.0) != left
+ })
+ .map(|s| luma(s.rgb))
+ .collect();
+ picked.iter().sum::<f32>() / picked.len().max(1) as f32
+ };
+ assert!(side(true) > side(false) * 2.0);
+ let form = Shape::new(&shape, &r);
+ assert!(strokes.iter().all(|s| {
+ let bands: Vec<f32> = s.run.iter().map(|q| form.band(&r, [q[0], q[1]])).collect();
+ bands.iter().cloned().fold(f32::MIN, f32::max) - bands.iter().cloned().fold(f32::MAX, f32::min)
+ <= 2.0 * CUT + 0.02
+ }));
+ assert!(strokes.iter().any(|s| s.bold) && strokes.iter().any(|s| !s.bold));
+ assert_eq!(strokes, paint_form(&[shape], &r));
+ }
+
+ #[test]
+ fn on_a_locked_or_clipped_layer_strokes_run_past_the_edge_and_the_edge_is_cut_in() {
+ let shape = disc(100.0, 100.0, 60.0);
+ let r = FormRules {
+ spill: true,
+ ..rules(Lighting::Direction {
+ toward: [-1.0, 0.0, 0.5],
+ })
+ };
+ let strokes = paint_form(std::slice::from_ref(&shape), &r);
+ let off = |q: &[f32; 3]| libm::sqrtf((q[0] - 100.0).powi(2) + (q[1] - 100.0).powi(2)) - 60.0;
+ assert!(strokes.iter().any(|s| s.run.iter().any(|q| off(q) > 1.0)));
+ assert!(strokes.iter().all(|s| s.run.iter().all(|q| off(q) < s.size)));
+ assert!(
+ strokes
+ .iter()
+ .filter(|s| s.run.iter().all(|q| off(q).abs() < 1.0))
+ .count()
+ > 20
+ );
+ }
+
+ #[test]
+ fn a_lamp_lights_the_near_form_more_and_a_flat_form_is_even() {
+ let (near, far) = (disc(100.0, 100.0, 30.0), disc(400.0, 100.0, 30.0));
+ let r = rules(Lighting::Lamp {
+ at: [20.0, 100.0, 60.0],
+ });
+ let both = paint_form(&[near, far], &r);
+ let mean = |left: bool| {
+ let picked: Vec<f32> = both
+ .iter()
+ .filter(|s| (s.run[0][0] < 250.0) == left)
+ .map(|s| luma(s.rgb))
+ .collect();
+ picked.iter().sum::<f32>() / picked.len().max(1) as f32
+ };
+ assert!(mean(true) > mean(false) * 1.5);
+ let flat = FormRules {
+ form: Form::Flat {
+ facing: [0.0, -1.0, 1.0],
+ },
+ ..rules(Lighting::Direction {
+ toward: [0.0, -1.0, 1.0],
+ })
+ };
+ let square = vec![[0.0, 0.0], [80.0, 0.0], [80.0, 80.0], [0.0, 80.0]];
+ let tones: Vec<f32> = paint_form(&[square], &flat)
+ .iter()
+ .filter(|s| !s.bold && s.opacity > 0.9)
+ .map(|s| luma(s.rgb))
+ .collect();
+ let (lo, hi) = (
+ tones.iter().cloned().fold(f32::MAX, f32::min),
+ tones.iter().cloned().fold(f32::MIN, f32::max),
+ );
+ assert!(hi / lo < 1.25);
+ }
+
+ #[test]
+ fn a_cylinder_is_painted_along_its_axis() {
+ let tube = vec![[0.0, 0.0], [40.0, 0.0], [40.0, 160.0], [0.0, 160.0]];
+ let r = FormRules {
+ form: Form::Cylinder { axis: 90.0 },
+ ..rules(Lighting::Direction {
+ toward: [-1.0, -0.2, 0.6],
+ })
+ };
+ let strokes = paint_form(&[tube], &r);
+ assert!(strokes.iter().filter(|s| s.run.len() > 6).all(|s| {
+ let (a, b) = (s.run[0], s.run[s.run.len() - 1]);
+ (b[1] - a[1]).abs() > (b[0] - a[0]).abs() * 3.0
+ }));
+ }
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
new file mode 100644
index 0000000..d46fb7a
--- /dev/null
+++ b/crates/render/src/lib.rs
@@ -0,0 +1,1424 @@
+pub mod assets;
+pub mod effects;
+pub mod export;
+pub mod form;
+pub mod onion;
+pub mod overlay;
+pub mod shapes;
+pub mod sheet;
+pub mod sprites;
+pub mod text;
+pub mod vector;
+
+use anyhow::{Context, Result, anyhow, bail};
+use effects::{Img, Space};
+use klad_brush::{Raster, TILE};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Blend, Document, Kind, Layer, LayerContent};
+use klad_core::fill::FillRef;
+use klad_core::look::{self, Adjustment, Effect};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use onion::Onions;
+use rayon::prelude::*;
+use skia_safe::{
+ AlphaType, BlendMode, Canvas, Color4f, ColorSpace, ColorType, Data, FilterMode, IRect, Image, ImageInfo,
+ MipmapMode, Paint, Pixmap, Rect, SamplingOptions, canvas::SaveLayerRec, image::CachingHint, images, png_encoder,
+ surfaces,
+};
+use std::collections::BTreeMap;
+
+pub type Rasters = BTreeMap<String, Raster>;
+
+pub struct Frame {
+ pub width: u32,
+ pub height: u32,
+ pub rgba: Vec<u8>,
+}
+
+impl Frame {
+ pub fn hash(&self) -> u64 {
+ fnv(FNV_OFFSET, &self.rgba)
+ }
+
+ pub fn png(&mut self) -> Result<Vec<u8>> {
+ let info = rgba8_info(self.width, self.height);
+ let pixmap =
+ Pixmap::new(&info, &mut self.rgba, self.width as usize * 4).ok_or_else(|| anyhow!("bad pixmap"))?;
+ let mut options = png_encoder::Options::default();
+ options.z_lib_level = 2;
+ options.filter_flags = png_encoder::FilterFlag::SUB;
+ let mut out = Vec::new();
+ if !png_encoder::encode(&pixmap, &mut out, &options) {
+ return Err(anyhow!("PNG encoding failed"));
+ }
+ Ok(out)
+ }
+
+ pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
+ let at = ((y * self.width + x) * 4) as usize;
+ [self.rgba[at], self.rgba[at + 1], self.rgba[at + 2], self.rgba[at + 3]]
+ }
+}
+
+pub(crate) fn f16_info(width: u32, height: u32) -> ImageInfo {
+ ImageInfo::new(
+ (width as i32, height as i32),
+ ColorType::RGBAF16,
+ AlphaType::Premul,
+ ColorSpace::new_srgb(),
+ )
+}
+
+pub(crate) fn rgba8_info(width: u32, height: u32) -> ImageInfo {
+ ImageInfo::new(
+ (width as i32, height as i32),
+ ColorType::RGBA8888,
+ AlphaType::Unpremul,
+ ColorSpace::new_srgb(),
+ )
+}
+
+fn blend_mode(blend: Blend) -> BlendMode {
+ match blend {
+ Blend::Normal => BlendMode::SrcOver,
+ Blend::Multiply => BlendMode::Multiply,
+ Blend::Screen => BlendMode::Screen,
+ Blend::Overlay => BlendMode::Overlay,
+ Blend::Add => BlendMode::Plus,
+ Blend::ColorDodge => BlendMode::ColorDodge,
+ Blend::SoftLight => BlendMode::SoftLight,
+ Blend::HardLight => BlendMode::HardLight,
+ Blend::Lighten => BlendMode::Lighten,
+ Blend::Darken => BlendMode::Darken,
+ Blend::Color => BlendMode::Color,
+ Blend::Luminosity => BlendMode::Luminosity,
+ }
+}
+
+pub(crate) fn background(hex: Option<&str>) -> Result<Color4f> {
+ match hex {
+ Some(hex) if hex != "none" => {
+ let [r, g, b, a] = parse_hex(hex)?;
+ Ok(Color4f::new(r, g, b, a))
+ }
+ _ => Ok(Color4f::new(0.0, 0.0, 0.0, 0.0)),
+ }
+}
+
+fn tile_image(tile: &[half::f16]) -> Result<Image> {
+ let bytes: &[u8] = bytemuck::cast_slice(tile);
+ images::raster_from_data(&f16_info(TILE as u32, TILE as u32), Data::new_copy(bytes), TILE * 8)
+ .ok_or_else(|| anyhow!("cannot wrap tile"))
+}
+
+fn draw_data(canvas: &Canvas, tile: &[half::f16], index: usize, cols: usize) -> Result<()> {
+ let (tx, ty) = (index % cols, index / cols);
+ canvas.draw_image(tile_image(tile)?, ((tx * TILE) as f32, (ty * TILE) as f32), None);
+ Ok(())
+}
+
+fn draw_tile(canvas: &Canvas, raster: &Raster, index: usize) -> Result<()> {
+ raster
+ .at(index)
+ .map_or(Ok(()), |tile| draw_data(canvas, tile, index, raster.cols))
+}
+
+fn tiles_in(cols: usize, rows: usize, area: IRect) -> Vec<usize> {
+ let t = TILE as i32;
+ if area.is_empty() || cols == 0 || rows == 0 {
+ return Vec::new();
+ }
+ let (x0, y0) = (area.left.div_euclid(t).max(0), area.top.div_euclid(t).max(0));
+ let x1 = (area.right - 1).div_euclid(t).min(cols as i32 - 1);
+ let y1 = (area.bottom - 1).div_euclid(t).min(rows as i32 - 1);
+ (y0..=y1)
+ .flat_map(|ty| (x0..=x1).map(move |tx| ty as usize * cols + tx as usize))
+ .collect()
+}
+
+pub fn raster_image(raster: &Raster) -> Result<Image> {
+ let (w, h) = (raster.width as usize, raster.height as usize);
+ let mut pixels = vec![half::f16::ZERO; w * h * 4];
+ raster.occupied().for_each(|(index, tile)| {
+ let (x0, y0) = ((index % raster.cols) * TILE, (index / raster.cols) * TILE);
+ let cols = TILE.min(w - x0);
+ (0..TILE.min(h - y0)).for_each(|row| {
+ let to = ((y0 + row) * w + x0) * 4;
+ pixels[to..to + cols * 4].copy_from_slice(&tile[row * TILE * 4..row * TILE * 4 + cols * 4]);
+ });
+ });
+ images::raster_from_data(
+ &f16_info(raster.width, raster.height),
+ Data::new_copy(bytemuck::cast_slice(&pixels)),
+ w * 8,
+ )
+ .ok_or_else(|| anyhow!("cannot wrap a {w}x{h} raster"))
+}
+
+fn draw_raster(canvas: &Canvas, raster: &Raster, ctx: Ctx) -> Result<()> {
+ match (ctx.area, ctx.sampling) {
+ (Some(area), _) => tiles_in(raster.cols, raster.rows, area)
+ .into_iter()
+ .try_for_each(|i| draw_tile(canvas, raster, i)),
+ (None, Some(sampling)) => {
+ if raster.count() > 0 {
+ let image = raster_image(raster)?;
+ let image = match sampling.use_cubic || sampling.mipmap == MipmapMode::None {
+ true => image,
+ false => image
+ .with_default_mipmaps()
+ .ok_or_else(|| anyhow!("cannot build mipmaps"))?,
+ };
+ canvas.draw_image_with_sampling_options(image, (0, 0), sampling, None);
+ }
+ Ok(())
+ }
+ (None, None) => raster
+ .occupied()
+ .try_for_each(|(index, _)| draw_tile(canvas, raster, index)),
+ }
+}
+
+pub type SwapTiles = BTreeMap<usize, Option<Vec<half::f16>>>;
+
+#[derive(Clone, Copy)]
+pub struct Swap<'a> {
+ pub cel: &'a str,
+ pub cols: usize,
+ pub rows: usize,
+ pub tiles: &'a SwapTiles,
+}
+
+#[derive(Clone, Copy)]
+pub struct Ctx<'a> {
+ pub frame: u32,
+ pub rasters: &'a Rasters,
+ pub area: Option<IRect>,
+ pub swap: Option<Swap<'a>>,
+ pub sampling: Option<SamplingOptions>,
+ pub onions: Option<&'a Onions>,
+ pub flat: bool,
+ pub doc: Option<&'a Document>,
+ pub references: bool,
+}
+
+impl<'a> Ctx<'a> {
+ pub fn full(frame: u32, rasters: &'a Rasters) -> Self {
+ Self {
+ frame,
+ rasters,
+ area: None,
+ swap: None,
+ sampling: None,
+ onions: None,
+ flat: true,
+ doc: None,
+ references: false,
+ }
+ }
+
+ fn nested(self) -> Self {
+ Self { flat: false, ..self }
+ }
+
+ fn effects(self, layer: &Layer) -> std::borrow::Cow<'_, [Effect]> {
+ match self.doc {
+ Some(doc) => doc.effects_of(layer),
+ None => std::borrow::Cow::Borrowed(&layer.effects),
+ }
+ }
+
+ fn shows(self, layer: &Layer) -> bool {
+ layer.visible && (self.references || !layer.reference)
+ }
+}
+
+fn layer_paint(opacity: f32, blend: Blend) -> Paint {
+ let mut paint = Paint::default();
+ paint.set_alpha_f(opacity);
+ paint.set_blend_mode(blend_mode(blend));
+ paint
+}
+
+fn layer_paint_isolated(canvas: &Canvas, opacity: f32, blend: Blend) {
+ canvas.save_layer(&SaveLayerRec::default().paint(&layer_paint(opacity, blend)));
+}
+
+fn mode_layer(canvas: &Canvas, mode: BlendMode) {
+ let mut paint = Paint::default();
+ paint.set_blend_mode(mode);
+ canvas.save_layer(&SaveLayerRec::default().paint(&paint));
+}
+
+fn clip_groups<'a>(layers: impl IntoIterator<Item = &'a Layer>) -> Vec<(&'a Layer, Vec<&'a Layer>)> {
+ layers.into_iter().fold(Vec::new(), |mut out, layer| {
+ match out.last_mut() {
+ Some((_, clipped)) if layer.clip => clipped.push(layer),
+ _ => out.push((layer, Vec::new())),
+ }
+ out
+ })
+}
+
+pub fn draw_layers(canvas: &Canvas, layers: &[Layer], ctx: Ctx) -> Result<()> {
+ let groups = clip_groups(layers);
+ let reads = groups.iter().any(|(base, _)| ctx.shows(base) && base.reads_under());
+ let draw = |c: &Canvas, x: Ctx| {
+ groups
+ .iter()
+ .try_for_each(|(base, clipped)| draw_clipped(c, base, clipped, x))
+ };
+ match reads && !ctx.flat {
+ true => effected(canvas, ctx, &[], 1.0, Blend::Normal, &draw),
+ false => draw(canvas, ctx),
+ }
+}
+
+fn draw_onions<'a>(canvas: &Canvas, layers: impl Iterator<Item = &'a Layer>, ctx: Ctx) -> Result<()> {
+ let Some(onions) = ctx.onions else {
+ return Ok(());
+ };
+ layers
+ .filter_map(|l| onions.get(&l.id))
+ .try_for_each(|r| draw_raster(canvas, r, ctx))
+}
+
+fn draw_clipped(canvas: &Canvas, base: &Layer, clipped: &[&Layer], ctx: Ctx) -> Result<()> {
+ if !ctx.shows(base) {
+ return Ok(());
+ }
+ if base.reads_under() {
+ return match ctx.flat {
+ true => adjust_under(canvas, base, ctx),
+ false => Ok(()),
+ };
+ }
+ let shown: Vec<&Layer> = clipped.iter().copied().filter(|l| ctx.shows(l)).collect();
+ draw_onions(canvas, std::iter::once(base).chain(shown.iter().copied()), ctx)?;
+ let effects = ctx.effects(base);
+ if !effects.is_empty() || shown.iter().any(|l| l.reads_under()) {
+ return effected(canvas, ctx, &effects, base.opacity, base.blend, &|c, x| {
+ draw_unit(c, base, &shown, x)
+ })
+ .with_context(|| format!("layer {}", base.id));
+ }
+ if shown.is_empty() {
+ return draw_layer(canvas, base, ctx);
+ }
+ let inner = ctx.nested();
+ layer_paint_isolated(canvas, base.opacity, base.blend);
+ let drawn = draw_content(canvas, base, inner)
+ .and_then(|_| shown.iter().try_for_each(|layer| draw_clip(canvas, base, layer, inner)));
+ canvas.restore();
+ drawn
+}
+
+fn draw_clip(canvas: &Canvas, base: &Layer, layer: &Layer, ctx: Ctx) -> Result<()> {
+ layer_paint_isolated(canvas, layer.opacity, layer.blend);
+ let drawn = draw_styled(canvas, layer, ctx).and_then(|_| {
+ mode_layer(canvas, BlendMode::DstIn);
+ let base_drawn = draw_content(canvas, base, ctx);
+ canvas.restore();
+ base_drawn
+ });
+ canvas.restore();
+ drawn.with_context(|| format!("layer {} clipped to {}", layer.id, base.id))
+}
+
+fn draw_unit(canvas: &Canvas, base: &Layer, shown: &[&Layer], ctx: Ctx) -> Result<()> {
+ draw_content(canvas, base, ctx.nested())?;
+ shown.iter().try_for_each(|layer| match layer.reads_under() {
+ true => adjust_under(canvas, layer, ctx),
+ false => draw_clip(canvas, base, layer, ctx.nested()),
+ })
+}
+
+fn draw_styled(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {
+ let effects = ctx.effects(layer);
+ match effects.is_empty() {
+ true => draw_content(canvas, layer, ctx),
+ false => effected(canvas, ctx, &effects, 1.0, Blend::Normal, &|c, x| {
+ draw_content(c, layer, x)
+ }),
+ }
+}
+
+pub(crate) fn draw_layer(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {
+ if layer.reference && !ctx.references {
+ return Ok(());
+ }
+ if layer.reads_under() {
+ return match ctx.flat {
+ true => adjust_under(canvas, layer, ctx),
+ false => Ok(()),
+ };
+ }
+ let effects = ctx.effects(layer);
+ if !effects.is_empty() {
+ return effected(canvas, ctx, &effects, layer.opacity, layer.blend, &|c, x| {
+ draw_content(c, layer, x)
+ })
+ .with_context(|| format!("layer {}", layer.id));
+ }
+ let isolate = layer.opacity < 1.0 || layer.blend != Blend::Normal || layer.mask_at(ctx.frame).is_some();
+ if isolate {
+ layer_paint_isolated(canvas, layer.opacity, layer.blend);
+ }
+ let drawn = draw_content(canvas, layer, ctx);
+ if isolate {
+ canvas.restore();
+ }
+ drawn.with_context(|| format!("layer {}", layer.id))
+}
+
+fn device_space(canvas: &Canvas) -> Space {
+ let matrix = canvas.local_to_device_as_3x3();
+ Space {
+ scale: matrix.scale_x().abs().max(1e-6),
+ tx: matrix.translate_x(),
+ ty: matrix.translate_y(),
+ }
+}
+
+fn canvas_rect(window: IRect, space: Space) -> IRect {
+ let to = |v: i32, t: f32| (v as f32 - t) / space.scale;
+ IRect::from_ltrb(
+ to(window.left, space.tx).floor() as i32,
+ to(window.top, space.ty).floor() as i32,
+ to(window.right, space.tx).ceil() as i32,
+ to(window.bottom, space.ty).ceil() as i32,
+ )
+}
+
+fn f32_info(width: u32, height: u32) -> ImageInfo {
+ ImageInfo::new(
+ (width as i32, height as i32),
+ ColorType::RGBAF32,
+ AlphaType::Premul,
+ ColorSpace::new_srgb(),
+ )
+}
+
+fn read_img(surface: &mut skia_safe::Surface, window: IRect) -> Result<Img> {
+ let (w, h) = (window.width() as usize, window.height() as usize);
+ let mut px = vec![[0.0f32; 4]; w * h];
+ if !surface.read_pixels(
+ &f32_info(w as u32, h as u32),
+ bytemuck::cast_slice_mut(&mut px),
+ w * 16,
+ (0, 0),
+ ) {
+ bail!("cannot read {w}x{h} pixels for effects");
+ }
+ Ok(Img {
+ x: window.left,
+ y: window.top,
+ w,
+ h,
+ px,
+ })
+}
+
+fn img_image(img: &Img) -> Result<Image> {
+ images::raster_from_data(
+ &f32_info(img.w as u32, img.h as u32),
+ Data::new_copy(bytemuck::cast_slice(&img.px)),
+ img.w * 16,
+ )
+ .ok_or_else(|| anyhow!("cannot wrap {}x{} pixels", img.w, img.h))
+}
+
+fn offscreen(window: IRect, canvas: &Canvas, ctx: Ctx, draw: &dyn Fn(&Canvas, Ctx) -> Result<()>) -> Result<Img> {
+ let (w, h) = (window.width().max(1) as u32, window.height().max(1) as u32);
+ let mut surface =
+ surfaces::raster(&f16_info(w, h), None, None).ok_or_else(|| anyhow!("cannot allocate {w}x{h} pixels"))?;
+ let inner = surface.canvas();
+ inner.translate((-window.left as f32, -window.top as f32));
+ inner.concat(&canvas.local_to_device_as_3x3());
+ let area = ctx.area.map(|_| canvas_rect(window, device_space(canvas)));
+ draw(
+ inner,
+ Ctx {
+ area,
+ flat: true,
+ ..ctx
+ },
+ )?;
+ read_img(&mut surface, window)
+}
+
+fn find<'a>(layers: &'a [Layer], id: &str) -> Option<&'a Layer> {
+ layers
+ .iter()
+ .find_map(|l| (l.id == id).then_some(l).or_else(|| find(l.children(), id)))
+}
+
+fn effected(
+ canvas: &Canvas,
+ ctx: Ctx,
+ list: &[Effect],
+ opacity: f32,
+ blend: Blend,
+ draw: &dyn Fn(&Canvas, Ctx) -> Result<()>,
+) -> Result<()> {
+ let Some(device) = canvas.device_clip_bounds().filter(|d| !d.is_empty()) else {
+ return Ok(());
+ };
+ let space = device_space(canvas);
+ let m = effects::margin(list, space.scale);
+ let window = device.with_outset((m, m));
+ let img = offscreen(window, canvas, ctx, draw)?;
+ let by = |id: &str| -> Result<Option<Img>> {
+ let Some(layer) = find(ctx.doc.map_or(&[][..], |d| &d.layers[..]), id) else {
+ bail!("the displacement layer {id} is gone");
+ };
+ offscreen(window, canvas, ctx, &|c, x| draw_content(c, layer, x.nested())).map(Some)
+ };
+ let (passes, image) = match list.is_empty() {
+ true => (Vec::new(), img),
+ false => effects::run(list, img, space, &by)?,
+ };
+ canvas.save();
+ canvas.reset_matrix();
+ let drawn = passes
+ .iter()
+ .map(|p| (&p.img, p.blend))
+ .chain(std::iter::once((&image, blend)))
+ .try_for_each(|(img, mode)| {
+ let part = match m {
+ 0 => img_image(img)?,
+ _ => img_image(&img.crop(
+ device.left,
+ device.top,
+ device.width() as usize,
+ device.height() as usize,
+ ))?,
+ };
+ canvas.draw_image(
+ part,
+ (device.left as f32, device.top as f32),
+ Some(&layer_paint(opacity, mode)),
+ );
+ Ok(())
+ });
+ canvas.restore();
+ drawn
+}
+
+fn adjust_under(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {
+ let Some(adjust) = layer.adjustment() else {
+ return Ok(());
+ };
+ let prepared = adjust.prepare().with_context(|| format!("layer {}", layer.id))?;
+ let size = canvas.base_layer_size();
+ let (w, h) = (size.width.max(0) as usize, size.height.max(0) as usize);
+ if w == 0 || h == 0 {
+ return Ok(());
+ }
+ let info = f32_info(w as u32, h as u32);
+ let mut pixels = vec![[0.0f32; 4]; w * h];
+ if !canvas.read_pixels(&info, bytemuck::cast_slice_mut(&mut pixels), w * 16, (0, 0)) {
+ bail!("cannot read the pixels under adjustment layer {}", layer.id);
+ }
+ let mask = match layer.mask_at(ctx.frame) {
+ Some((mask, cel)) => {
+ let window = IRect::from_wh(w as i32, h as i32);
+ let cel = layer_cel(mask, cel);
+ let img = offscreen(window, canvas, ctx, &|c, x| draw_paint_cel(c, &cel, x))?;
+ Some(img.px.iter().map(|p| p[3]).collect::<Vec<f32>>())
+ }
+ None => None,
+ };
+ let (opacity, blend) = (layer.opacity, layer.blend);
+ pixels.par_iter_mut().enumerate().for_each(|(i, px)| {
+ let a = px[3];
+ let k = opacity * (1.0 - mask.as_ref().map_or(0.0, |m| m[i]));
+ if a <= 0.0 || k <= 0.0 {
+ return;
+ }
+ let un = [px[0] / a, px[1] / a, px[2] / a];
+ let mixed = look::blend_rgb(blend, un, prepared.apply(un));
+ (0..3).for_each(|c| px[c] = (un[c] + (mixed[c] - un[c]) * k) * a);
+ });
+ if !canvas.write_pixels(&info, bytemuck::cast_slice(&pixels), w * 16, (0, 0)) {
+ bail!("cannot write the pixels under adjustment layer {}", layer.id);
+ }
+ Ok(())
+}
+
+fn draw_paint_cel(canvas: &Canvas, cel: &str, ctx: Ctx) -> Result<()> {
+ match ctx.swap {
+ Some(swap) if swap.cel == cel => {
+ let raster = ctx.rasters.get(cel);
+ let indices = match ctx.area {
+ Some(area) => tiles_in(swap.cols, swap.rows, area),
+ None => (0..swap.cols * swap.rows).collect(),
+ };
+ indices.into_iter().try_for_each(|i| match swap.tiles.get(&i) {
+ Some(Some(tile)) => draw_data(canvas, tile, i, swap.cols),
+ Some(None) => Ok(()),
+ None => raster.map_or(Ok(()), |r| draw_tile(canvas, r, i)),
+ })
+ }
+ _ => ctx.rasters.get(cel).map_or(Ok(()), |r| draw_raster(canvas, r, ctx)),
+ }
+}
+
+fn draw_content(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {
+ match &layer.content {
+ LayerContent::Paint { .. } => layer
+ .content_at(ctx.frame)
+ .map_or(Ok(()), |cel| draw_paint_cel(canvas, &cel.id, ctx)),
+ LayerContent::Vector { .. } => {
+ layer
+ .content_at(ctx.frame)
+ .map_or(Ok(()), |cel| match ctx.rasters.get(&cel.id) {
+ Some(r) => draw_raster(canvas, r, ctx),
+ None => vector::draw_nodes(canvas, &cel.nodes),
+ })
+ }
+ LayerContent::Group { children } => draw_layers(canvas, children, ctx.nested()),
+ LayerContent::Adjust {
+ adjust: Adjustment::Fill(fill),
+ } => {
+ if let Some(paint) = vector::shader_paint(&fill.paint)? {
+ canvas.draw_paint(&paint);
+ }
+ Ok(())
+ }
+ LayerContent::Adjust { .. } => Ok(()),
+ }?;
+ if let Some((mask, cel)) = layer.mask_at(ctx.frame) {
+ mode_layer(canvas, BlendMode::DstOut);
+ let drawn = draw_paint_cel(canvas, &layer_cel(mask, cel), ctx);
+ canvas.restore();
+ drawn.with_context(|| format!("mask {}", mask.id))?;
+ }
+ Ok(())
+}
+
+fn layer_cel(layer: &Layer, cel: &klad_core::doc::Cel) -> String {
+ layer.content_of(cel).id.clone()
+}
+
+pub struct Lifted {
+ pub rect: [f32; 4],
+ pub width: u32,
+ pub height: u32,
+ pub pixels: Vec<half::f16>,
+}
+
+pub fn rasterize_region(nodes: &[klad_core::doc::Node], rect: [f32; 4], max_side: u32, scale: f32) -> Result<Lifted> {
+ let [x, y, w, h] = rect;
+ let scale = (max_side as f32 / w.max(h)).min(scale.clamp(0.05, 1.0));
+ let (width, height) = (((w * scale).ceil() as u32).max(1), ((h * scale).ceil() as u32).max(1));
+ let info = f16_info(width, height);
+ let mut surface = surfaces::raster(&info, None, None).ok_or_else(|| anyhow!("cannot allocate {width}x{height}"))?;
+ let canvas = surface.canvas();
+ canvas.scale((scale, scale));
+ canvas.translate((-x, -y));
+ vector::draw_nodes(canvas, nodes)?;
+ let mut pixels = vec![half::f16::ZERO; width as usize * height as usize * 4];
+ if !surface.read_pixels(&info, bytemuck::cast_slice_mut(&mut pixels), width as usize * 8, (0, 0)) {
+ return Err(anyhow!("cannot read pixels"));
+ }
+ Ok(Lifted {
+ rect: [x, y, width as f32 / scale, height as f32 / scale],
+ width,
+ height,
+ pixels,
+ })
+}
+
+pub fn rasterize_nodes(nodes: &[klad_core::doc::Node], width: u32, height: u32) -> Result<Raster> {
+ let info = f16_info(width, height);
+ let mut surface = surfaces::raster(&info, None, None).ok_or_else(|| anyhow!("cannot allocate {width}x{height}"))?;
+ vector::draw_nodes(surface.canvas(), nodes)?;
+ let (w, h) = (width as usize, height as usize);
+ let mut pixels = vec![half::f16::ZERO; w * h * 4];
+ if !surface.read_pixels(&info, bytemuck::cast_slice_mut(&mut pixels), w * 8, (0, 0)) {
+ return Err(anyhow!("cannot read pixels"));
+ }
+ let mut raster = Raster::new(width, height);
+ (0..raster.rows).for_each(|ty| {
+ (0..raster.cols).for_each(|tx| {
+ let mut tile = vec![half::f16::ZERO; TILE * TILE * 4];
+ let (x0, y0) = (tx * TILE, ty * TILE);
+ let cols = TILE.min(w - x0);
+ (0..TILE.min(h - y0)).for_each(|row| {
+ let from = ((y0 + row) * w + x0) * 4;
+ tile[row * TILE * 4..row * TILE * 4 + cols * 4].copy_from_slice(&pixels[from..from + cols * 4]);
+ });
+ if tile.as_chunks::<4>().0.iter().any(|px| px[3].to_f32() > 0.0) {
+ let index = raster.index(tx, ty);
+ raster.put(index, tile.into_boxed_slice());
+ }
+ })
+ });
+ Ok(raster)
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct View {
+ pub scale: f32,
+ pub region: Option<[i32; 4]>,
+ pub references: bool,
+}
+
+impl View {
+ pub fn scaled(scale: f32) -> Self {
+ Self {
+ scale,
+ region: None,
+ references: false,
+ }
+ }
+}
+
+pub fn compose(doc: &Document, frame: u32, rasters: &Rasters, view: View) -> Result<Frame> {
+ compose_view(doc, frame, rasters, view, None, None)
+}
+
+pub fn compose_view(
+ doc: &Document,
+ frame: u32,
+ rasters: &Rasters,
+ view: View,
+ overlay: Option<&overlay::Overlay>,
+ onions: Option<&Onions>,
+) -> Result<Frame> {
+ let (width, height) = (doc.canvas.width, doc.canvas.height);
+ let mut surface = surfaces::raster(&f16_info(width, height), None, None)
+ .ok_or_else(|| anyhow!("cannot allocate {width}x{height}"))?;
+ let canvas = surface.canvas();
+ canvas.clear(background(doc.canvas.background.as_deref())?);
+ let ctx = Ctx {
+ onions,
+ doc: Some(doc),
+ references: view.references,
+ ..Ctx::full(frame, rasters)
+ };
+ draw_layers(canvas, &doc.layers, ctx)?;
+ let image = match view.region {
+ Some([x, y, w, h]) => surface
+ .image_snapshot_with_bounds(IRect::from_xywh(x, y, w, h))
+ .ok_or_else(|| anyhow!("region {x},{y} {w}x{h} is outside the canvas"))?,
+ None => surface.image_snapshot(),
+ };
+ let out = if (view.scale - 1.0).abs() < f32::EPSILON {
+ image
+ } else {
+ resample(&image, view.scale)?
+ };
+ match overlay {
+ Some(overlay) => overlay::apply(&out, overlay, &view),
+ None => read_rgba8(&out),
+ }
+}
+
+pub fn compose_image(doc: &Document, frame: u32, rasters: &Rasters) -> Result<Image> {
+ let (width, height) = (doc.canvas.width, doc.canvas.height);
+ let mut surface = surfaces::raster(&f16_info(width, height), None, None)
+ .ok_or_else(|| anyhow!("cannot allocate {width}x{height}"))?;
+ let canvas = surface.canvas();
+ canvas.clear(background(doc.canvas.background.as_deref())?);
+ let ctx = Ctx {
+ doc: Some(doc),
+ ..Ctx::full(frame, rasters)
+ };
+ draw_layers(canvas, &doc.layers, ctx)?;
+ Ok(surface.image_snapshot())
+}
+
+fn resample(image: &Image, scale: f32) -> Result<Image> {
+ let (w, h) = (
+ ((image.width() as f32 * scale).round() as u32).max(1),
+ ((image.height() as f32 * scale).round() as u32).max(1),
+ );
+ let source = if scale < 1.0 {
+ image
+ .with_default_mipmaps()
+ .ok_or_else(|| anyhow!("cannot build mipmaps"))?
+ } else {
+ image.clone()
+ };
+ let mut surface =
+ surfaces::raster(&f16_info(w, h), None, None).ok_or_else(|| anyhow!("cannot allocate {w}x{h}"))?;
+ let sampling = if scale < 1.0 {
+ SamplingOptions::new(FilterMode::Linear, MipmapMode::Linear)
+ } else {
+ SamplingOptions::new(FilterMode::Nearest, MipmapMode::None)
+ };
+ surface.canvas().draw_image_rect_with_sampling_options(
+ &source,
+ None,
+ Rect::from_wh(w as f32, h as f32),
+ sampling,
+ &Paint::default(),
+ );
+ Ok(surface.image_snapshot())
+}
+
+pub fn read_rgba8(image: &Image) -> Result<Frame> {
+ let (width, height) = (image.width() as u32, image.height() as u32);
+ let mut rgba = vec![0u8; width as usize * height as usize * 4];
+ if !image.read_pixels(
+ &rgba8_info(width, height),
+ &mut rgba,
+ width as usize * 4,
+ (0, 0),
+ CachingHint::Allow,
+ ) {
+ return Err(anyhow!("cannot read pixels"));
+ }
+ Ok(Frame { width, height, rgba })
+}
+
+pub enum TileItem<'a> {
+ Pixels {
+ tile: &'a [half::f16],
+ opacity: f32,
+ blend: Blend,
+ },
+ Layer(&'a Layer),
+}
+
+enum Unit<'a> {
+ Pixels {
+ tile: &'a [half::f16],
+ opacity: f32,
+ blend: Blend,
+ },
+ Layers(&'a Layer, Vec<&'a Layer>),
+}
+
+fn units<'a>(items: &[TileItem<'a>]) -> Vec<Unit<'a>> {
+ items.iter().fold(Vec::new(), |mut out, item| {
+ match (item, out.last_mut()) {
+ (TileItem::Layer(layer), Some(Unit::Layers(_, clipped))) if layer.clip => clipped.push(layer),
+ (TileItem::Layer(layer), _) => out.push(Unit::Layers(layer, Vec::new())),
+ (TileItem::Pixels { tile, opacity, blend }, _) => out.push(Unit::Pixels {
+ tile,
+ opacity: *opacity,
+ blend: *blend,
+ }),
+ }
+ out
+ })
+}
+
+pub struct TileJob<'a> {
+ pub frame: u32,
+ pub rasters: &'a Rasters,
+ pub background: Option<&'a str>,
+ pub tx: usize,
+ pub ty: usize,
+ pub swap: Option<Swap<'a>>,
+ pub onions: Option<&'a Onions>,
+ pub doc: &'a Document,
+ pub references: bool,
+}
+
+pub fn flatten(
+ doc: &Document,
+ frame: u32,
+ rasters: &Rasters,
+ layers: &[&Layer],
+ background: Option<&str>,
+) -> Result<Raster> {
+ flatten_with(doc, frame, rasters, layers, background, None, false)
+}
+
+pub fn flatten_with(
+ doc: &Document,
+ frame: u32,
+ rasters: &Rasters,
+ layers: &[&Layer],
+ background: Option<&str>,
+ onions: Option<&Onions>,
+ references: bool,
+) -> Result<Raster> {
+ let mut out = Raster::new(doc.canvas.width, doc.canvas.height);
+ let items: Vec<TileItem> = layers.iter().map(|l| TileItem::Layer(l)).collect();
+ let tiles = (0..out.cols * out.rows)
+ .into_par_iter()
+ .map(|index| {
+ let job = TileJob {
+ frame,
+ rasters,
+ background,
+ tx: index % out.cols,
+ ty: index / out.cols,
+ swap: None,
+ onions,
+ doc,
+ references,
+ };
+ let tile = compose_tile(&items, &job)?;
+ let used = tile.as_chunks::<4>().0.iter().any(|px| px[3].to_f32() > 0.0);
+ Ok(used.then_some((index, tile)))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ tiles
+ .into_iter()
+ .flatten()
+ .for_each(|(index, tile)| out.put(index, tile.into_boxed_slice()));
+ Ok(out)
+}
+
+pub fn fill_reference(doc: &Document, frame: u32, rasters: &Rasters, cel: &str, reference: &FillRef) -> Result<Raster> {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ match reference {
+ FillRef::This => Ok(rasters.get(cel).cloned().unwrap_or_else(|| Raster::new(w, h))),
+ FillRef::All => {
+ let layers: Vec<&Layer> = doc.layers.iter().collect();
+ flatten(doc, frame, rasters, &layers, doc.canvas.background.as_deref())
+ }
+ FillRef::Layer(id) => {
+ let layer = doc
+ .layer(id)
+ .ok_or_else(|| anyhow!("the fill reference layer {id} is gone"))?;
+ if layer.kind() == Kind::Paint {
+ return Ok(layer
+ .content_at(frame)
+ .and_then(|c| rasters.get(&c.id))
+ .cloned()
+ .unwrap_or_else(|| Raster::new(w, h)));
+ }
+ let mut alone = layer.clone();
+ alone.visible = true;
+ alone.opacity = 1.0;
+ alone.blend = Blend::Normal;
+ alone.reference = false;
+ flatten(doc, frame, rasters, &[&alone], None)
+ }
+ }
+}
+
+pub fn compose_tile(items: &[TileItem], job: &TileJob) -> Result<Vec<half::f16>> {
+ let info = f16_info(TILE as u32, TILE as u32);
+ let mut surface = surfaces::raster(&info, None, None).ok_or_else(|| anyhow!("cannot allocate a tile"))?;
+ let canvas = surface.canvas();
+ canvas.clear(background(job.background)?);
+ let (ox, oy) = ((job.tx * TILE) as f32, (job.ty * TILE) as f32);
+ canvas.translate((-ox, -oy));
+ let ctx = Ctx {
+ frame: job.frame,
+ rasters: job.rasters,
+ area: Some(IRect::from_xywh(ox as i32, oy as i32, TILE as i32, TILE as i32)),
+ swap: job.swap,
+ sampling: None,
+ onions: job.onions,
+ flat: true,
+ doc: Some(job.doc),
+ references: job.references,
+ };
+ units(items).into_iter().try_for_each(|unit| match unit {
+ Unit::Pixels { tile, opacity, blend } => {
+ canvas.draw_image(tile_image(tile)?, (ox, oy), Some(&layer_paint(opacity, blend)));
+ Ok(())
+ }
+ Unit::Layers(base, clipped) => draw_clipped(canvas, base, &clipped, ctx),
+ })?;
+ let mut out = vec![half::f16::ZERO; TILE * TILE * 4];
+ if !surface.read_pixels(&info, bytemuck::cast_slice_mut(&mut out), TILE * 8, (0, 0)) {
+ return Err(anyhow!("cannot read tile pixels"));
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod look_tests;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_brush::{BrushSet, replay};
+ use klad_core::doc::{Cel, Linear, Node, Paint as Fill, Shape, Stop, StrokeStyle};
+ use klad_core::stroke::Stroke;
+
+ fn rect(id: &str, x: f32, y: f32, w: f32, h: f32, fill: &str) -> Node {
+ Node::new(
+ id,
+ Shape::Rect {
+ x,
+ y,
+ w,
+ h,
+ radius: 0.0,
+ },
+ )
+ .filled(fill)
+ }
+
+ fn close(a: [u8; 4], b: [u8; 4]) -> bool {
+ a.iter().zip(&b).all(|(x, y)| x.abs_diff(*y) <= 2)
+ }
+
+ #[test]
+ fn vector_and_paint_layers_compose_in_order() {
+ let mut doc = Document::new(64, 64);
+ doc.layers.push(Layer::vector(
+ "bg",
+ "bg",
+ "c1",
+ vec![rect("n1", 0.0, 0.0, 64.0, 64.0, "#0000ff")],
+ ));
+ doc.layers.push(Layer::paint("ink", "ink", "c2"));
+ let stroke = Stroke::new(1, "ink", [1.0, 0.0, 0.0, 1.0], 12.0, 1).with_points(&[(32.0, 32.0, 1.0)], 0.0);
+ let raster = replay(64, 64, &[stroke.into()], &BrushSet::presets()).unwrap().raster;
+ let rasters = Rasters::from([("c2".to_string(), raster)]);
+ let mut frame = compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ assert_eq!(frame.pixel(32, 32), [255, 0, 0, 255]);
+ assert_eq!(frame.pixel(2, 2), [0, 0, 255, 255]);
+ assert_eq!(compose(&doc, 0, &rasters, View::scaled(0.5)).unwrap().width, 32);
+ assert!(frame.png().unwrap().starts_with(&[0x89, b'P', b'N', b'G']));
+ let zoomed = compose(
+ &doc,
+ 0,
+ &rasters,
+ View {
+ scale: 2.0,
+ region: Some([28, 28, 8, 8]),
+ references: false,
+ },
+ )
+ .unwrap();
+ assert_eq!((zoomed.width, zoomed.height), (16, 16));
+ assert_eq!(zoomed.pixel(8, 8), [255, 0, 0, 255]);
+ }
+
+ #[test]
+ fn groups_isolate_opacity_and_blend() {
+ let mut doc = Document::new(8, 8);
+ doc.layers.push(Layer::vector(
+ "a",
+ "a",
+ "c1",
+ vec![rect("n1", 0.0, 0.0, 8.0, 8.0, "#ffffff")],
+ ));
+ let black = Layer::vector("b", "b", "c2", vec![rect("n2", 0.0, 0.0, 8.0, 8.0, "#000000")]);
+ let mut group = Layer::group("g", "g", vec![black]);
+ group.opacity = 0.5;
+ doc.layers.push(group);
+ let grey = compose(&doc, 0, &Rasters::new(), View::scaled(1.0))
+ .unwrap()
+ .pixel(4, 4);
+ assert!((126..=129).contains(&grey[0]), "{grey:?}");
+ doc.layers[1].opacity = 1.0;
+ doc.layers[1].blend = Blend::Multiply;
+ assert_eq!(
+ compose(&doc, 0, &Rasters::new(), View::scaled(1.0))
+ .unwrap()
+ .pixel(4, 4),
+ [0, 0, 0, 255]
+ );
+ doc.layers[1].visible = false;
+ assert_eq!(
+ compose(&doc, 0, &Rasters::new(), View::scaled(1.0))
+ .unwrap()
+ .pixel(4, 4),
+ [255, 255, 255, 255]
+ );
+ }
+
+ #[test]
+ fn frames_pick_their_cels() {
+ let mut doc = Document::new(4, 4);
+ doc.timeline.frames = 3;
+ let mut layer = Layer::vector("v", "v", "c1", vec![rect("n1", 0.0, 0.0, 4.0, 4.0, "#ff0000")]);
+ if let Some(cels) = layer.cels_mut() {
+ cels[0].hold = Some(1);
+ let mut second = Cel::at("c2", 1);
+ second.nodes = vec![rect("n2", 0.0, 0.0, 4.0, 4.0, "#00ff00")];
+ second.hold = Some(1);
+ cels.push(second);
+ cels.push(Cel {
+ link: Some("c1".into()),
+ ..Cel::at("c3", 2)
+ });
+ }
+ doc.layers.push(layer);
+ let at = |f| {
+ compose(&doc, f, &Rasters::new(), View::scaled(1.0))
+ .unwrap()
+ .pixel(1, 1)
+ };
+ assert_eq!(
+ [at(0), at(1), at(2)],
+ [[255, 0, 0, 255], [0, 255, 0, 255], [255, 0, 0, 255]]
+ );
+ }
+
+ #[test]
+ fn transforms_gradients_and_strokes_render() {
+ let mut doc = Document::new(100, 100);
+ let mut bar = rect("bar", 40.0, 0.0, 20.0, 100.0, "#000000");
+ bar.transform.rotate = 90.0;
+ let mut sky = rect("sky", 0.0, 0.0, 100.0, 100.0, "#000000");
+ sky.fill = Some(Fill::Linear {
+ linear: Linear {
+ from: [0.0, 0.0],
+ to: [0.0, 100.0],
+ stops: vec![Stop(0.0, "#ff0000".into()), Stop(1.0, "#0000ff".into())],
+ },
+ });
+ let mut ring = Node::new(
+ "ring",
+ Shape::Ellipse {
+ cx: 80.0,
+ cy: 80.0,
+ rx: 10.0,
+ ry: 10.0,
+ },
+ );
+ ring.fill = Some(Fill::Solid("none".into()));
+ ring.stroke = Some(StrokeStyle {
+ paint: Fill::Solid("#00ff00".into()),
+ width: 4.0,
+ cap: Default::default(),
+ join: Default::default(),
+ dash: Vec::new(),
+ });
+ doc.layers.push(Layer::vector("v", "v", "c1", vec![sky, bar, ring]));
+ let frame = compose(&doc, 0, &Rasters::new(), View::scaled(1.0)).unwrap();
+ let top = frame.pixel(5, 2);
+ let bottom = frame.pixel(5, 97);
+ assert!(top[0] > 240 && top[2] < 15, "{top:?}");
+ assert!(bottom[2] > 240 && bottom[0] < 15, "{bottom:?}");
+ assert_eq!(frame.pixel(5, 50), [0, 0, 0, 255]);
+ assert_ne!(frame.pixel(50, 5), [0, 0, 0, 255]);
+ assert!(close(frame.pixel(90, 80), [0, 255, 0, 255]));
+ assert_ne!(frame.pixel(80, 80)[1], 255);
+ let bounds = vector::node_bounds(&doc.layers[0].cels()[0].nodes[1], &skia_safe::Matrix::new_identity())
+ .unwrap()
+ .unwrap();
+ assert!((bounds.left - 0.0).abs() < 0.01 && (bounds.width() - 100.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn blur_softens_edges() {
+ let mut doc = Document::new(100, 40);
+ let mut soft = rect("soft", 50.0, 0.0, 50.0, 40.0, "#000000");
+ soft.blur = 6.0;
+ doc.layers.push(Layer::vector(
+ "v",
+ "v",
+ "c1",
+ vec![rect("hard", 0.0, 0.0, 50.0, 40.0, "#000000"), soft],
+ ));
+ let frame = compose(&doc, 0, &Rasters::new(), View::scaled(1.0)).unwrap();
+ assert_eq!(frame.pixel(25, 20)[3], 255);
+ assert_eq!(frame.pixel(75, 20)[3], 255);
+ let edge = frame.pixel(98, 20)[3];
+ assert!(edge > 20 && edge < 200, "{edge}");
+ assert_eq!(frame.pixel(48, 2)[3], 255);
+ }
+
+ #[test]
+ fn clip_paths_cut_children() {
+ let mut doc = Document::new(100, 100);
+ let mut g = Node::new(
+ "g",
+ Shape::Group {
+ children: vec![rect("r", 0.0, 0.0, 100.0, 100.0, "#ff0000")],
+ },
+ );
+ g.clip = Some("M0 0 L50 0 L50 100 L0 100 Z".into());
+ doc.layers.push(Layer::vector("v", "v", "c1", vec![g]));
+ let frame = compose(&doc, 0, &Rasters::new(), View::scaled(1.0)).unwrap();
+ assert_eq!(frame.pixel(25, 50), [255, 0, 0, 255]);
+ assert_eq!(frame.pixel(75, 50)[3], 0);
+ let b = vector::node_box(&doc.layers[0].cels()[0].nodes[0]).unwrap().unwrap();
+ assert!((b[2] - 50.0).abs() < 0.01, "{b:?}");
+ }
+
+ #[test]
+ fn rasterized_vectors_and_swapped_tiles_match() {
+ let mut doc = Document::new(600, 300);
+ let mut ring = Node::new(
+ "ring",
+ Shape::Ellipse {
+ cx: 300.0,
+ cy: 150.0,
+ rx: 200.0,
+ ry: 100.0,
+ },
+ )
+ .filled("#3366aa");
+ ring.blur = 3.0;
+ doc.layers.push(Layer::vector("v", "v", "cv", vec![ring]));
+ let ink = Layer::paint("p", "p", "cp");
+ doc.layers.push(Layer::group("g", "g", vec![ink]));
+ let stroke = Stroke::new(1, "ink", [0.9, 0.1, 0.1, 1.0], 40.0, 1)
+ .with_points(&[(20.0, 20.0, 1.0), (580.0, 280.0, 1.0)], 5.0);
+ let raster = replay(600, 300, &[stroke.into()], &BrushSet::presets()).unwrap().raster;
+ let plain = Rasters::from([("cp".to_string(), raster.clone())]);
+ let full = compose(&doc, 0, &plain, View::scaled(1.0)).unwrap();
+ let mut cached = plain.clone();
+ cached.insert(
+ "cv".into(),
+ rasterize_nodes(&doc.layers[0].cels()[0].nodes, 600, 300).unwrap(),
+ );
+ let items: Vec<TileItem> = doc.layers.iter().map(TileItem::Layer).collect();
+ let empty = SwapTiles::from([(1usize, None)]);
+ let tile = |swap| {
+ compose_tile(
+ &items,
+ &TileJob {
+ frame: 0,
+ rasters: &cached,
+ background: None,
+ tx: 1,
+ ty: 0,
+ swap,
+ onions: None,
+ doc: &doc,
+ references: false,
+ },
+ )
+ .unwrap()
+ };
+ let px = |t: &[half::f16], x: usize, y: usize| -> [u8; 3] {
+ let at = (y * TILE + x) * 4;
+ let a = t[at + 3].to_f32().max(1e-6);
+ [0, 1, 2].map(|c| (t[at + c].to_f32() / a * 255.0).round() as u8)
+ };
+ let ours = tile(None);
+ [(10usize, 150usize), (60, 120), (200, 30)].iter().for_each(|&(x, y)| {
+ let reference = full.pixel((256 + x) as u32, y as u32);
+ let got = px(&ours, x, y);
+ assert!(
+ got.iter().zip(&reference[..3]).all(|(a, b)| a.abs_diff(*b) <= 1),
+ "({x},{y}) {got:?} vs {reference:?}"
+ );
+ });
+ let without_ink = tile(Some(Swap {
+ cel: "cp",
+ cols: 3,
+ rows: 2,
+ tiles: &empty,
+ }));
+ let ring_only = compose(&doc, 0, &Rasters::new(), View::scaled(1.0)).unwrap();
+ let reference = ring_only.pixel(256 + 60, 120);
+ assert_eq!(px(&without_ink, 60, 120), [reference[0], reference[1], reference[2]]);
+ }
+
+ #[test]
+ fn tiles_match_the_full_composite() {
+ let mut doc = Document::new(512, 300);
+ doc.layers.push(Layer::vector(
+ "bg",
+ "bg",
+ "c1",
+ vec![
+ Node::new(
+ "n1",
+ Shape::Ellipse {
+ cx: 256.0,
+ cy: 150.0,
+ rx: 200.0,
+ ry: 120.0,
+ },
+ )
+ .filled("#336699"),
+ ],
+ ));
+ let mut ink = Layer::paint("ink", "ink", "c2");
+ ink.opacity = 0.7;
+ doc.layers.push(ink);
+ let stroke = Stroke::new(1, "ink", [0.9, 0.2, 0.1, 1.0], 30.0, 1)
+ .with_points(&[(40.0, 40.0, 1.0), (300.0, 260.0, 0.6), (480.0, 60.0, 0.9)], 5.0);
+ let raster = replay(512, 300, &[stroke.into()], &BrushSet::presets()).unwrap().raster;
+ let rasters = Rasters::from([("c2".to_string(), raster)]);
+ let full = compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ let tile = rasters["c2"].get(1, 0).unwrap();
+ let items = [
+ TileItem::Layer(&doc.layers[0]),
+ TileItem::Pixels {
+ tile,
+ opacity: 0.7,
+ blend: Blend::Normal,
+ },
+ ];
+ let job = TileJob {
+ frame: 0,
+ rasters: &rasters,
+ background: None,
+ tx: 1,
+ ty: 0,
+ swap: None,
+ onions: None,
+ doc: &doc,
+ references: false,
+ };
+ let composed = compose_tile(&items, &job).unwrap();
+ let px = &composed[(100 * TILE + 44) * 4..(100 * TILE + 44) * 4 + 4];
+ let a = px[3].to_f32();
+ let rgb: Vec<u8> = px[..3].iter().map(|v| (v.to_f32() / a * 255.0).round() as u8).collect();
+ let reference = full.pixel(256 + 44, 100);
+ assert!(
+ rgb.iter().zip(&reference[..3]).all(|(x, y)| x.abs_diff(*y) <= 1),
+ "{rgb:?} vs {reference:?}"
+ );
+ }
+
+ #[test]
+ fn onion_skin_sits_under_its_layer_and_tiles_agree() {
+ let mut doc = Document::new(256, 64);
+ doc.canvas.background = Some("#ffffff".into());
+ doc.timeline.frames = 3;
+ let mut ball = Layer::paint("ball", "ball", "c1");
+ *ball.cels_mut().unwrap() = vec![
+ Cel {
+ hold: Some(1),
+ ..Cel::at("c1", 0)
+ },
+ Cel {
+ hold: Some(1),
+ ..Cel::at("c2", 1)
+ },
+ Cel::at("c3", 2),
+ ];
+ let mut cover = Layer::paint("top", "top", "c9");
+ cover.opacity = 0.5;
+ doc.layers = vec![ball, cover];
+ let dot = |x: f32| {
+ let stroke = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 30.0, 1).with_points(&[(x, 32.0, 1.0)], 0.0);
+ replay(256, 64, &[stroke.into()], &BrushSet::presets()).unwrap().raster
+ };
+ let rasters = Rasters::from([
+ ("c1".to_string(), dot(40.0)),
+ ("c2".to_string(), dot(128.0)),
+ ("c3".to_string(), dot(216.0)),
+ ("c9".to_string(), dot(40.0)),
+ ]);
+ let plan = onion::plan(&doc, 1, &onion::animated(&doc), &onion::Onion::default());
+ assert_eq!(plan.len(), 1);
+ let onions = onion::build(&doc, &plan, &rasters);
+ let full = compose_view(&doc, 1, &rasters, View::scaled(1.0), None, Some(&onions)).unwrap();
+ let plain = compose(&doc, 1, &rasters, View::scaled(1.0)).unwrap();
+ let before = full.pixel(216 - 176, 32);
+ let after = full.pixel(216, 32);
+ assert!(
+ before[0] > before[1] + 25,
+ "red before, under the top layer: {before:?}"
+ );
+ assert!(after[1] > after[0] + 40, "green after: {after:?}");
+ assert_eq!(full.pixel(128, 32), plain.pixel(128, 32));
+ assert_eq!(plain.pixel(216, 32), [255, 255, 255, 255]);
+ let items: Vec<TileItem> = doc.layers.iter().map(TileItem::Layer).collect();
+ let tile = compose_tile(
+ &items,
+ &TileJob {
+ frame: 1,
+ rasters: &rasters,
+ background: Some("#ffffff"),
+ tx: 0,
+ ty: 0,
+ swap: None,
+ onions: Some(&onions),
+ doc: &doc,
+ references: false,
+ },
+ )
+ .unwrap();
+ [40usize, 128, 216].iter().for_each(|&x| {
+ let at = (32 * TILE + x) * 4;
+ let got: Vec<u8> = (0..3).map(|c| (tile[at + c].to_f32() * 255.0).round() as u8).collect();
+ let want = full.pixel(x as u32, 32);
+ assert!(
+ got.iter().zip(&want[..3]).all(|(a, b)| a.abs_diff(*b) <= 1),
+ "{x}: {got:?} vs {want:?}"
+ );
+ });
+ }
+
+ #[test]
+ fn masks_hide_and_clipped_layers_stay_inside_their_base() {
+ let mut doc = Document::new(256, 128);
+ doc.canvas.background = Some("#ffffff".into());
+ let flat = Layer::vector(
+ "flat",
+ "flat",
+ "c1",
+ vec![rect("n1", 40.0, 20.0, 120.0, 80.0, "#d0a060")],
+ );
+ let mut shade = Layer::paint("shade", "shade", "c2");
+ shade.clip = true;
+ shade.blend = Blend::Multiply;
+ let mut light = Layer::paint("light", "light", "c3");
+ light.clip = true;
+ light.mask = Some(Box::new(Layer::paint("m", "mask", "c4")));
+ doc.layers = vec![flat, shade, light];
+ let line = |id: u32, y: f32, color: [f32; 4], size: f32| {
+ Stroke::new(id, "ink", color, size, 1).with_points(&[(0.0, y, 1.0), (256.0, y, 1.0)], 5.0)
+ };
+ let paint = |strokes: Vec<Stroke>| {
+ replay(
+ 256,
+ 128,
+ &strokes.into_iter().map(Into::into).collect::<Vec<_>>(),
+ &BrushSet::presets(),
+ )
+ .unwrap()
+ .raster
+ };
+ let rasters = Rasters::from([
+ ("c2".to_string(), paint(vec![line(1, 60.0, [0.2, 0.2, 0.5, 1.0], 30.0)])),
+ ("c3".to_string(), paint(vec![line(1, 30.0, [1.0, 1.0, 1.0, 1.0], 12.0)])),
+ (
+ "c4".to_string(),
+ paint(vec![
+ Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 30.0, 1)
+ .with_points(&[(100.0, 30.0, 1.0), (256.0, 30.0, 1.0)], 5.0),
+ ]),
+ ),
+ ]);
+ let frame = compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ let shaded = frame.pixel(100, 60);
+ assert!(shaded[2] < 140 && shaded[0] < 60, "{shaded:?}");
+ assert_eq!(frame.pixel(10, 60), [255, 255, 255, 255]);
+ assert_eq!(frame.pixel(200, 60), [255, 255, 255, 255]);
+ assert_eq!(frame.pixel(60, 30), [255, 255, 255, 255]);
+ assert_eq!(frame.pixel(10, 30), [255, 255, 255, 255]);
+ assert!(
+ close(frame.pixel(130, 30), [0xd0, 0xa0, 0x60, 255]),
+ "{:?}",
+ frame.pixel(130, 30)
+ );
+ let items: Vec<TileItem> = doc.layers.iter().map(TileItem::Layer).collect();
+ let tile = compose_tile(
+ &items,
+ &TileJob {
+ frame: 0,
+ rasters: &rasters,
+ background: Some("#ffffff"),
+ tx: 0,
+ ty: 0,
+ swap: None,
+ onions: None,
+ doc: &doc,
+ references: false,
+ },
+ )
+ .unwrap();
+ [(100usize, 60usize), (60, 30), (130, 30), (200, 60)]
+ .iter()
+ .for_each(|&(x, y)| {
+ let at = (y * TILE + x) * 4;
+ let got: Vec<u8> = (0..3).map(|c| (tile[at + c].to_f32() * 255.0).round() as u8).collect();
+ let want = frame.pixel(x as u32, y as u32);
+ assert!(
+ got.iter().zip(&want[..3]).all(|(a, b)| a.abs_diff(*b) <= 1),
+ "({x},{y}) {got:?} vs {want:?}"
+ );
+ });
+ doc.layers[0].visible = false;
+ let hidden = compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ assert_eq!(hidden.pixel(100, 60), [255, 255, 255, 255]);
+ doc.layers.remove(0);
+ let leading = compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ assert!(leading.pixel(10, 60)[2] < 200, "{:?}", leading.pixel(10, 60));
+ }
+}
diff --git a/crates/render/src/look_tests.rs b/crates/render/src/look_tests.rs
new file mode 100644
index 0000000..8c52c87
--- /dev/null
+++ b/crates/render/src/look_tests.rs
@@ -0,0 +1,504 @@
+use super::*;
+use klad_core::doc::{Node, Shape};
+use klad_core::look::{Curves, Displace, Hsl, Rays};
+
+fn disc(id: &str, cx: f32, cy: f32, r: f32, color: &str) -> Layer {
+ Layer::vector(
+ id,
+ id,
+ &format!("c{id}"),
+ vec![Node::new(&format!("n{id}"), Shape::Ellipse { cx, cy, rx: r, ry: r }).filled(color)],
+ )
+}
+
+fn rect(id: &str, x: f32, y: f32, w: f32, h: f32, color: &str) -> Layer {
+ Layer::vector(
+ id,
+ id,
+ &format!("c{id}"),
+ vec![
+ Node::new(
+ &format!("n{id}"),
+ Shape::Rect {
+ x,
+ y,
+ w,
+ h,
+ radius: 0.0,
+ },
+ )
+ .filled(color),
+ ],
+ )
+}
+
+fn rasters(doc: &Document) -> Rasters {
+ fn walk(layers: &[Layer], doc: &Document, out: &mut Rasters) {
+ layers.iter().for_each(|l| {
+ if let Some(cel) = l.cels().first().filter(|_| l.kind() == Kind::Vector) {
+ let raster = rasterize_nodes(&cel.nodes, doc.canvas.width, doc.canvas.height).unwrap();
+ out.insert(cel.id.clone(), raster);
+ }
+ walk(l.children(), doc, out);
+ });
+ }
+ let mut out = Rasters::new();
+ walk(&doc.layers, doc, &mut out);
+ out
+}
+
+fn full(doc: &Document) -> Frame {
+ compose(doc, 0, &rasters(doc), View::scaled(1.0)).unwrap()
+}
+
+fn tiled(doc: &Document) -> Frame {
+ let layers: Vec<&Layer> = doc.layers.iter().collect();
+ let raster = flatten(doc, 0, &rasters(doc), &layers, doc.canvas.background.as_deref()).unwrap();
+ read_rgba8(&raster_image(&raster).unwrap()).unwrap()
+}
+
+fn worst(a: &Frame, b: &Frame) -> u8 {
+ a.rgba
+ .iter()
+ .zip(&b.rgba)
+ .map(|(x, y)| x.abs_diff(*y))
+ .max()
+ .unwrap_or(0)
+}
+
+fn effects(json: &str) -> Vec<Effect> {
+ serde_json::from_str(json).unwrap()
+}
+
+#[test]
+fn effects_compose_the_same_in_tiles_as_in_one_piece() {
+ let mut doc = Document::new(600, 420);
+ doc.canvas.background = Some("#203040".into());
+ let mut lantern = disc("l1", 300.0, 240.0, 70.0, "#e0a040");
+ lantern.effects = effects(
+ r##"[{"shadow":{"x":8,"y":10,"radius":5}},{"outline":{"width":5,"color":"#101010"}},{"noise":{"amount":0.15,"size":2}},{"displace":{"amount":5,"size":30}},{"glow":{"radius":16,"color":"#ffd080"}},{"blur":{"radius":1}}]"##,
+ );
+ let mut halo = disc("l2", 250.0, 255.0, 30.0, "#80c0ff");
+ halo.effects = effects(r#"[{"glow":{"radius":40,"strength":1.5,"blend":"add"}}]"#);
+ halo.opacity = 0.8;
+ doc.layers = vec![lantern, halo];
+ let (a, b) = (full(&doc), tiled(&doc));
+ assert_eq!(worst(&a, &b), 0, "tiles differ from the whole");
+ let plain = {
+ let mut d = doc.clone();
+ d.layers.iter_mut().for_each(|l| l.effects.clear());
+ full(&d)
+ };
+ let (x, y) = (300 + 70 + 3, 240);
+ assert_ne!(
+ a.pixel(x, y),
+ plain.pixel(x, y),
+ "the outline and glow show past the edge"
+ );
+ assert!(
+ a.pixel(300 + 70 + 20, 240)[0] > plain.pixel(300 + 70 + 20, 240)[0] + 10,
+ "the glow spreads"
+ );
+}
+
+#[test]
+fn blend_modes_meet_their_formulas() {
+ let back = parse_hex("#3366cc").unwrap();
+ let top = parse_hex("#e08040").unwrap();
+ Blend::ALL.iter().for_each(|&mode| {
+ let mut doc = Document::new(32, 32);
+ let mut over = rect("l2", 0.0, 0.0, 32.0, 32.0, "#e08040");
+ over.blend = mode;
+ over.opacity = 0.6;
+ doc.layers = vec![rect("l1", 0.0, 0.0, 32.0, 32.0, "#3366cc"), over];
+ let got = full(&doc).pixel(16, 16);
+ let source = [top[0] * 0.6, top[1] * 0.6, top[2] * 0.6, 0.6];
+ let want = look::composite(mode, back, source);
+ let want: Vec<u8> = (0..3).map(|c| (want[c] / want[3] * 255.0).round() as u8).collect();
+ assert!(
+ got.iter().zip(&want).all(|(g, w)| g.abs_diff(*w) <= 2),
+ "{}: {got:?} vs {want:?}",
+ mode.name()
+ );
+ });
+}
+
+#[test]
+fn adjustments_change_what_is_under_them_in_their_group_or_clip() {
+ let mut doc = Document::new(512, 300);
+ let curve = Adjustment::Curves(Curves {
+ points: vec![[0.0, 0.0], [0.5, 0.25], [1.0, 1.0]],
+ ..Curves::default()
+ });
+ let group = Layer::group(
+ "g",
+ "g",
+ vec![
+ rect("l2", 256.0, 0.0, 256.0, 150.0, "#808080"),
+ Layer::adjust("a1", "curves", curve.clone()),
+ ],
+ );
+ let mut turn = Layer::adjust(
+ "a2",
+ "hue",
+ Adjustment::Hsl(Hsl {
+ hue: 120.0,
+ ..Hsl::default()
+ }),
+ );
+ turn.clip = true;
+ doc.layers = vec![
+ rect("l1", 0.0, 0.0, 256.0, 150.0, "#808080"),
+ group,
+ rect("l3", 100.0, 180.0, 200.0, 80.0, "#ff0000"),
+ turn,
+ ];
+ let frame = full(&doc);
+ assert_eq!(frame.pixel(100, 75), [128, 128, 128, 255], "outside the group");
+ let expected = (curve.prepare().unwrap().apply([128.0 / 255.0; 3])[0] * 255.0).round() as u8;
+ assert!(
+ frame.pixel(400, 75)[0].abs_diff(expected) <= 1,
+ "{:?} vs {expected}",
+ frame.pixel(400, 75)
+ );
+ let p = frame.pixel(200, 220);
+ assert!(p[1] > 240 && p[0] < 10, "the clipped hue turn {p:?}");
+ assert_eq!(
+ frame.pixel(50, 220)[3],
+ 0,
+ "the clip keeps the adjustment off empty pixels"
+ );
+ assert!(worst(&frame, &tiled(&doc)) <= 1);
+}
+
+#[test]
+fn displacement_follows_another_layer() {
+ let mut doc = Document::new(400, 200);
+ let mut map = rect("l9", 0.0, 0.0, 400.0, 200.0, "#ff8080");
+ map.visible = false;
+ let mut body = rect("l1", 0.0, 0.0, 200.0, 200.0, "#204060");
+ body.effects = vec![Effect::Displace(Displace {
+ amount: 10.0,
+ by: Some("l9".into()),
+ ..Displace::default()
+ })];
+ doc.layers = vec![map, body];
+ let frame = full(&doc);
+ assert!(frame.pixel(185, 100)[3] > 250 && frame.pixel(195, 100)[3] < 5);
+ assert!(worst(&frame, &tiled(&doc)) <= 1);
+}
+
+#[test]
+fn rays_shine_where_they_point_and_repeat() {
+ let mut doc = Document::new(400, 400);
+ doc.canvas.background = Some("#000000".into());
+ let mut node = Node::new(
+ "n1",
+ Shape::Rays(Rays {
+ x: 200.0,
+ y: 0.0,
+ spread: 30.0,
+ count: 6,
+ length: 380.0,
+ ..Rays::default()
+ }),
+ )
+ .filled("#fff2c0");
+ node.blur = 4.0;
+ doc.layers = vec![Layer::vector("l1", "rays", "c1", vec![node])];
+ let (a, b) = (full(&doc), full(&doc));
+ assert_eq!(a.hash(), b.hash());
+ let lit = (100..300).map(|y| a.pixel(200, y)[0] as u32).sum::<u32>();
+ let dark = (100..300).map(|y| a.pixel(20, y)[0] as u32).sum::<u32>();
+ assert!(lit > 2000 && dark == 0, "lit {lit} dark {dark}");
+ assert!(worst(&a, &tiled(&doc)) <= 1);
+}
+
+#[test]
+#[ignore = "timing: cargo test --release -p klad-render glow_timing -- --ignored --nocapture"]
+fn glow_timing() {
+ use std::time::Instant;
+ let mut doc = Document::new(2048, 2048);
+ doc.canvas.background = Some("#101820".into());
+ let mut lamps = Layer::vector(
+ "l1",
+ "lamps",
+ "c1",
+ (0..40)
+ .map(|i| {
+ let (x, y) = ((i % 8) as f32 * 250.0 + 120.0, (i / 8) as f32 * 400.0 + 200.0);
+ Node::new(
+ &format!("n{i}"),
+ Shape::Ellipse {
+ cx: x,
+ cy: y,
+ rx: 40.0,
+ ry: 40.0,
+ },
+ )
+ .filled("#ffc060")
+ })
+ .collect(),
+ );
+ lamps.effects = vec![Effect::Glow(klad_core::look::Glow {
+ radius: 32.0 / 3.0,
+ ..klad_core::look::Glow::default()
+ })];
+ doc.layers = vec![rect("l0", 0.0, 0.0, 2048.0, 2048.0, "#203040"), lamps];
+ let rasters = rasters(&doc);
+ let time = |f: &dyn Fn()| {
+ let runs: Vec<f64> = (0..5)
+ .map(|_| {
+ let t = Instant::now();
+ f();
+ t.elapsed().as_secs_f64() * 1000.0
+ })
+ .collect();
+ runs.iter().cloned().fold(f64::MAX, f64::min)
+ };
+ let whole = time(&|| {
+ compose(&doc, 0, &rasters, View::scaled(1.0)).unwrap();
+ });
+ let layers: Vec<&Layer> = doc.layers.iter().collect();
+ let tiled = time(&|| {
+ flatten(&doc, 0, &rasters, &layers, doc.canvas.background.as_deref()).unwrap();
+ });
+ let items: Vec<TileItem> = doc.layers.iter().map(TileItem::Layer).collect();
+ let one = time(&|| {
+ compose_tile(
+ &items,
+ &TileJob {
+ frame: 0,
+ rasters: &rasters,
+ background: doc.canvas.background.as_deref(),
+ tx: 3,
+ ty: 3,
+ swap: None,
+ onions: None,
+ doc: &doc,
+ references: false,
+ },
+ )
+ .unwrap();
+ });
+ println!(
+ "2048 px with a 32 px glow on 40 lamps: whole canvas {whole:.0} ms, all 64 tiles {tiled:.0} ms, one dirty tile {one:.2} ms"
+ );
+}
+
+fn plane(id: &str, depth: Option<f32>, child: Layer) -> Layer {
+ let mut g = Layer::group(id, id, vec![child]);
+ g.depth = depth;
+ g
+}
+
+#[test]
+fn far_planes_take_the_fog_and_blur_and_near_ones_stay() {
+ let mut doc = Document::new(300, 200);
+ doc.canvas.background = Some("#000000".into());
+ doc.atmosphere = Some(klad_core::look::Atmosphere {
+ color: "#c0d0e0".into(),
+ density: 1.0,
+ blur: 2.0,
+ desaturate: 0.5,
+ ..klad_core::look::Atmosphere::default()
+ });
+ doc.layers = vec![
+ plane("far", Some(2.0), rect("l1", 20.0, 20.0, 100.0, 160.0, "#ff0000")),
+ plane("near", Some(0.0), rect("l2", 180.0, 20.0, 100.0, 160.0, "#ff0000")),
+ ];
+ let frame = full(&doc);
+ assert_eq!(
+ frame.pixel(230, 100),
+ [255, 0, 0, 255],
+ "a plane at depth 0 stays as it is"
+ );
+ let far = frame.pixel(70, 100);
+ assert!(
+ far[1] > 120 && far[2] > 120 && far[0] > 150,
+ "the far plane is mostly fog: {far:?}"
+ );
+ assert!(
+ frame.pixel(20, 100)[1] > frame.pixel(70, 100)[1] / 3,
+ "and its edge is soft"
+ );
+ assert_eq!(worst(&frame, &tiled(&doc)), 0);
+}
+
+#[test]
+fn references_stay_out_of_renders_unless_asked() {
+ let mut doc = Document::new(64, 64);
+ let mut photo = rect("l1", 0.0, 0.0, 64.0, 64.0, "#336699");
+ photo.reference = true;
+ doc.layers = vec![photo];
+ let hidden = compose(&doc, 0, &rasters(&doc), View::scaled(1.0)).unwrap();
+ assert_eq!(hidden.pixel(32, 32)[3], 0);
+ let shown = compose(
+ &doc,
+ 0,
+ &rasters(&doc),
+ View {
+ references: true,
+ ..View::scaled(1.0)
+ },
+ )
+ .unwrap();
+ assert_eq!(shown.pixel(32, 32), [0x33, 0x66, 0x99, 255]);
+}
+
+#[test]
+fn generators_draw_their_copies_the_same_in_tiles() {
+ use klad_core::generators::{Mirror, Repeat, Scatter};
+ let dot = |id: &str| {
+ Node::new(
+ id,
+ Shape::Ellipse {
+ cx: 0.0,
+ cy: 0.0,
+ rx: 8.0,
+ ry: 8.0,
+ },
+ )
+ .filled("#204060")
+ };
+ let mut doc = Document::new(600, 300);
+ let nodes = vec![
+ Node::new(
+ "r",
+ Shape::Repeat(Repeat {
+ count: 3,
+ step: [60.0, 0.0],
+ children: vec![
+ Node::new(
+ "r1",
+ Shape::Rect {
+ x: 20.0,
+ y: 20.0,
+ w: 30.0,
+ h: 30.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#a03020"),
+ ],
+ ..Repeat::default()
+ }),
+ ),
+ Node::new(
+ "m",
+ Shape::Mirror(Mirror {
+ x: 300.0,
+ children: vec![
+ Node::new(
+ "m1",
+ Shape::Path {
+ d: "M250 100 L280 100 L280 140 Z".into(),
+ },
+ )
+ .filled("#208040"),
+ ],
+ ..Mirror::default()
+ }),
+ ),
+ Node::new(
+ "s",
+ Shape::Scatter(Scatter {
+ x: 20.0,
+ y: 180.0,
+ w: 560.0,
+ h: 100.0,
+ count: 30,
+ children: vec![dot("s1")],
+ ..Scatter::default()
+ }),
+ ),
+ ];
+ doc.layers = vec![Layer::vector("l1", "gen", "c1", nodes)];
+ let frame = full(&doc);
+ [35u32, 95, 155]
+ .iter()
+ .for_each(|x| assert_eq!(frame.pixel(*x, 35)[0], 0xa0, "copy at {x}"));
+ assert_eq!(frame.pixel(215, 35)[3], 0, "only three copies");
+ assert!(
+ frame.pixel(275, 130)[1] > 100 && frame.pixel(325, 130)[1] > 100,
+ "the mirror shows both sides"
+ );
+ let dots = (180..280)
+ .flat_map(|y| (0..600).map(move |x| (x, y)))
+ .filter(|&(x, y)| frame.pixel(x, y)[3] > 0)
+ .count();
+ assert!(dots > 2000, "the scatter lays its copies ({dots} px)");
+ assert_eq!(worst(&frame, &tiled(&doc)), 0);
+}
+
+#[test]
+fn text_draws_the_font_s_outlines_and_names_a_missing_font() {
+ use klad_core::generators::Text;
+ let root = std::env::temp_dir().join(format!("draw-text-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let font = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../app/assets/Phosphor.ttf");
+ let name = crate::assets::import_font(&root, &font).unwrap();
+ crate::assets::add_root(&root);
+ let text = |font: &str| {
+ Node::new(
+ "t",
+ Shape::Text(Text {
+ text: "\u{E472}\u{E434}".into(),
+ font: font.into(),
+ x: 20.0,
+ y: 20.0,
+ size: 64.0,
+ ..Text::default()
+ }),
+ )
+ .filled("#101010")
+ };
+ let mut doc = Document::new(200, 120);
+ doc.layers = vec![Layer::vector("l1", "sign", "c1", vec![text(&name)])];
+ let frame = full(&doc);
+ let inked = (0..120)
+ .flat_map(|y| (0..200).map(move |x| (x, y)))
+ .filter(|&(x, y)| frame.pixel(x, y)[3] > 128)
+ .count();
+ assert!(inked > 300, "the glyphs are drawn ({inked} px)");
+ assert_eq!(frame.hash(), full(&doc).hash());
+ doc.layers = vec![Layer::vector("l1", "sign", "c1", vec![text("Missing.ttf")])];
+ let err = compose(&doc, 0, &Rasters::new(), View::scaled(1.0)).err().unwrap();
+ assert!(format!("{err:#}").contains("Missing.ttf"), "{err:#}");
+ let _ = std::fs::remove_dir_all(&root);
+}
+
+#[test]
+fn an_imported_picture_draws_where_it_is_placed() {
+ use klad_core::generators::Picture;
+ let root = std::env::temp_dir().join(format!("draw-picture-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let rgba = crate::assets::Rgba {
+ width: 2,
+ height: 2,
+ pixels: vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255],
+ };
+ let (src, w, h) = crate::assets::import_image(&root, &crate::assets::encode_png(&rgba).unwrap()).unwrap();
+ crate::assets::add_root(&root);
+ let mut doc = Document::new(100, 100);
+ doc.layers = vec![Layer::vector(
+ "l1",
+ "photo",
+ "c1",
+ vec![Node::new(
+ "p",
+ Shape::Image(Picture {
+ src,
+ x: 10.0,
+ y: 10.0,
+ w: w as f32 * 40.0,
+ h: h as f32 * 40.0,
+ }),
+ )],
+ )];
+ let frame = full(&doc);
+ assert_eq!(frame.pixel(15, 15), [255, 0, 0, 255]);
+ assert_eq!(frame.pixel(85, 85), [255, 255, 255, 255]);
+ assert_eq!(frame.pixel(5, 5)[3], 0);
+ let _ = std::fs::remove_dir_all(&root);
+}
diff --git a/crates/render/src/onion.rs b/crates/render/src/onion.rs
new file mode 100644
index 0000000..8fe21af
--- /dev/null
+++ b/crates/render/src/onion.rs
@@ -0,0 +1,402 @@
+use crate::Rasters;
+use half::f16;
+use klad_brush::Raster;
+use klad_brush::tiles::TILE_PX;
+use klad_core::doc::{Document, Kind, Layer};
+use klad_core::timing::ends;
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+
+pub type Onions = BTreeMap<String, Raster>;
+
+pub const BEFORE: [f32; 3] = [0.88, 0.16, 0.16];
+pub const AFTER: [f32; 3] = [0.1, 0.62, 0.24];
+const TINT: f32 = 0.75;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum By {
+ Drawings,
+ Frames,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Onion {
+ pub before: u32,
+ pub after: u32,
+ pub by: By,
+ pub opacity: f32,
+ pub falloff: f32,
+ pub tint: bool,
+ pub wrap: Option<(u32, u32)>,
+}
+
+impl Default for Onion {
+ fn default() -> Self {
+ Self {
+ before: 2,
+ after: 2,
+ by: By::Drawings,
+ opacity: 0.5,
+ falloff: 0.6,
+ tint: true,
+ wrap: None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Ghost {
+ pub cel: String,
+ pub step: i32,
+ pub alpha: f32,
+ pub tint: Option<[f32; 3]>,
+}
+
+struct Exposure {
+ start: u32,
+ content: String,
+}
+
+fn exposures(layer: &Layer, from: u32, to: u32) -> Vec<Exposure> {
+ let cels = layer.cels();
+ cels.iter()
+ .zip(ends(cels))
+ .filter(|(c, end)| c.frame <= to && *end > from)
+ .map(|(c, _)| Exposure {
+ start: c.frame.max(from),
+ content: layer.content_of(c).id.clone(),
+ })
+ .collect()
+}
+
+fn window(onion: &Onion, frame: u32, frames: u32) -> (u32, u32, bool) {
+ match onion.wrap {
+ Some((a, b)) if a <= frame && frame <= b && b < frames => (a, b, true),
+ _ => (0, frames.saturating_sub(1), false),
+ }
+}
+
+fn by_drawings(layer: &Layer, frame: u32, onion: &Onion, (from, to, wraps): (u32, u32, bool)) -> Vec<(i32, String)> {
+ let list = exposures(layer, from, to);
+ let current = layer.cel_at(frame).map_or(frame, |c| c.frame.max(from));
+ let earlier: Vec<&Exposure> = list.iter().filter(|e| e.start < current).rev().collect();
+ let later: Vec<&Exposure> = list.iter().filter(|e| e.start > frame).collect();
+ let (before, after): (Vec<&Exposure>, Vec<&Exposure>) = match wraps {
+ true => (
+ earlier.iter().chain(later.iter().rev()).copied().collect(),
+ later.iter().chain(earlier.iter().rev()).copied().collect(),
+ ),
+ false => (earlier, later),
+ };
+ let side = |list: Vec<&Exposure>, count: u32, sign: i32| -> Vec<(i32, String)> {
+ list.into_iter()
+ .take(count as usize)
+ .enumerate()
+ .map(|(k, e)| (sign * (k as i32 + 1), e.content.clone()))
+ .collect()
+ };
+ let mut out = side(before, onion.before, -1);
+ out.extend(side(after, onion.after, 1));
+ out
+}
+
+fn by_frames(layer: &Layer, frame: u32, onion: &Onion, (from, to, wraps): (u32, u32, bool)) -> Vec<(i32, String)> {
+ let len = (to - from + 1) as i64;
+ let at = |k: i64| -> Option<u32> {
+ let f = frame as i64 + k;
+ match wraps {
+ true => Some((from as i64 + (f - from as i64).rem_euclid(len)) as u32),
+ false => (from as i64..=to as i64).contains(&f).then_some(f as u32),
+ }
+ };
+ let side = |count: u32, sign: i64| -> Vec<(i32, String)> {
+ (1..=count as i64)
+ .map_while(|k| at(sign * k).map(|f| (k, f)))
+ .filter_map(|(k, f)| layer.content_at(f).map(|c| ((sign * k) as i32, c.id.clone())))
+ .collect()
+ };
+ let mut out = side(onion.before, -1);
+ out.extend(side(onion.after, 1));
+ out
+}
+
+pub fn ghosts(layer: &Layer, frame: u32, frames: u32, onion: &Onion) -> Vec<Ghost> {
+ if layer.kind() == Kind::Group || frames == 0 {
+ return Vec::new();
+ }
+ let span = window(onion, frame, frames);
+ let steps = match onion.by {
+ By::Drawings => by_drawings(layer, frame, onion, span),
+ By::Frames => by_frames(layer, frame, onion, span),
+ };
+ let current = layer.content_at(frame).map(|c| c.id.clone());
+ let mut nearest: Vec<(i32, String)> = steps
+ .into_iter()
+ .filter(|(_, cel)| Some(cel) != current.as_ref())
+ .collect();
+ nearest.sort_by_key(|(step, _)| (step.abs(), *step > 0));
+ let mut seen = BTreeSet::new();
+ let mut out: Vec<Ghost> = nearest
+ .into_iter()
+ .filter(|(_, cel)| seen.insert(cel.clone()))
+ .map(|(step, cel)| Ghost {
+ alpha: onion.opacity * onion.falloff.powi(step.abs() - 1),
+ tint: onion.tint.then_some(if step < 0 { BEFORE } else { AFTER }),
+ cel,
+ step,
+ })
+ .collect();
+ out.reverse();
+ out
+}
+
+pub fn animated(doc: &Document) -> Vec<String> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| matches!(l.kind(), Kind::Paint | Kind::Vector) && !doc.is_mask(&l.id))
+ .filter(|l| {
+ l.cels()
+ .iter()
+ .map(|c| &l.content_of(c).id)
+ .collect::<BTreeSet<_>>()
+ .len()
+ > 1
+ })
+ .map(|l| l.id.clone())
+ .collect()
+}
+
+pub fn plan(doc: &Document, frame: u32, layers: &[String], onion: &Onion) -> Vec<(String, Vec<Ghost>)> {
+ layers
+ .iter()
+ .filter_map(|id| doc.layer(id))
+ .filter(|l| l.visible)
+ .map(|l| (l.id.clone(), ghosts(l, frame, doc.timeline.frames, onion)))
+ .filter(|(_, g)| !g.is_empty())
+ .collect()
+}
+
+pub fn needed(doc: &Document, plan: &[(String, Vec<Ghost>)]) -> Vec<(String, String, Kind)> {
+ plan.iter()
+ .filter_map(|(layer, ghosts)| doc.layer(layer).map(|l| (l, ghosts)))
+ .flat_map(|(l, ghosts)| ghosts.iter().map(move |g| (l.id.clone(), g.cel.clone(), l.kind())))
+ .collect()
+}
+
+fn mix(acc: &mut [f32], tile: &[f16], alpha: f32, tint: Option<[f32; 3]>) {
+ acc.as_chunks_mut::<4>()
+ .0
+ .iter_mut()
+ .zip(tile.as_chunks::<4>().0)
+ .for_each(|(d, s)| {
+ let a = s[3].to_f32();
+ if a <= 0.0 {
+ return;
+ }
+ let rgb = [0, 1, 2].map(|c| {
+ let v = s[c].to_f32();
+ match tint {
+ Some(t) => v * (1.0 - TINT) + t[c] * a * TINT,
+ None => v,
+ }
+ });
+ let src = [rgb[0] * alpha, rgb[1] * alpha, rgb[2] * alpha, a * alpha];
+ let keep = 1.0 - src[3];
+ (0..4).for_each(|c| d[c] = src[c] + d[c] * keep);
+ });
+}
+
+pub fn paint(ghosts: &[Ghost], rasters: &Rasters, width: u32, height: u32) -> Raster {
+ let mut out = Raster::new(width, height);
+ let sources: Vec<(&Raster, &Ghost)> = ghosts
+ .iter()
+ .filter_map(|g| rasters.get(&g.cel).map(|r| (r, g)))
+ .collect();
+ let tiles: BTreeSet<usize> = sources.iter().flat_map(|(r, _)| r.occupied().map(|(i, _)| i)).collect();
+ let done: Vec<(usize, Vec<f16>)> = tiles
+ .into_par_iter()
+ .map(|index| {
+ let mut acc = vec![0.0f32; TILE_PX * 4];
+ sources.iter().for_each(|(r, g)| {
+ if let Some(tile) = r.at(index) {
+ mix(&mut acc, tile, g.alpha, g.tint);
+ }
+ });
+ (index, acc.into_iter().map(f16::from_f32).collect())
+ })
+ .collect();
+ done.into_iter()
+ .filter(|(_, t)| t.as_chunks::<4>().0.iter().any(|px| px[3].to_f32() > 0.0))
+ .for_each(|(i, t)| out.put(i, t.into_boxed_slice()));
+ out
+}
+
+pub fn build(doc: &Document, plan: &[(String, Vec<Ghost>)], rasters: &Rasters) -> Onions {
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ plan.iter()
+ .map(|(layer, ghosts)| (layer.clone(), paint(ghosts, rasters, w, h)))
+ .filter(|(_, r)| r.count() > 0)
+ .collect()
+}
+
+pub fn plan_hash(plan: &[(String, Vec<Ghost>)], version: impl Fn(&str) -> u64) -> u64 {
+ use klad_core::rng::{FNV_OFFSET, fnv};
+ plan.iter().fold(FNV_OFFSET, |h, (layer, ghosts)| {
+ ghosts.iter().fold(fnv(h, layer.as_bytes()), |h, g| {
+ let tint = g.tint.unwrap_or([-1.0; 3]);
+ let numbers = [g.alpha, tint[0], tint[1], tint[2]].map(f32::to_le_bytes).concat();
+ fnv(fnv(fnv(h, g.cel.as_bytes()), &numbers), &version(&g.cel).to_le_bytes())
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Cel;
+
+ fn layer(cels: Vec<Cel>) -> Layer {
+ let mut l = Layer::paint("l", "l", "x");
+ *l.cels_mut().unwrap() = cels;
+ l
+ }
+
+ fn held(id: &str, frame: u32, hold: u32) -> Cel {
+ Cel {
+ hold: Some(hold),
+ ..Cel::at(id, frame)
+ }
+ }
+
+ fn link(id: &str, frame: u32, to: &str) -> Cel {
+ Cel {
+ link: Some(to.into()),
+ ..Cel::at(id, frame)
+ }
+ }
+
+ fn steps(g: &[Ghost]) -> Vec<(i32, &str)> {
+ g.iter().map(|g| (g.step, g.cel.as_str())).collect()
+ }
+
+ #[test]
+ fn drawings_before_and_after_skip_holds_links_to_the_current_and_repeats() {
+ let l = layer(vec![
+ held("a", 0, 2),
+ held("b", 2, 2),
+ held("c", 4, 2),
+ held("d", 6, 2),
+ link("e", 8, "b"),
+ ]);
+ let onion = Onion::default();
+ assert_eq!(steps(&ghosts(&l, 4, 10, &onion)), [(-2, "a"), (1, "d"), (-1, "b")]);
+ assert_eq!(steps(&ghosts(&l, 5, 10, &onion)), steps(&ghosts(&l, 4, 10, &onion)));
+ assert_eq!(steps(&ghosts(&l, 2, 10, &onion)), [(2, "d"), (1, "c"), (-1, "a")]);
+ let g = ghosts(&l, 4, 10, &onion);
+ assert_eq!((g[2].alpha, g[2].tint), (0.5, Some(BEFORE)));
+ assert!((g[0].alpha - 0.3).abs() < 1e-6);
+ assert_eq!(g[1].tint, Some(AFTER));
+ }
+
+ #[test]
+ fn frames_count_distance_in_frames_and_blanks_show_neighbours() {
+ let l = layer(vec![held("a", 0, 2), held("b", 2, 2), held("c", 6, 2)]);
+ let onion = Onion {
+ by: By::Frames,
+ before: 3,
+ after: 3,
+ tint: false,
+ ..Onion::default()
+ };
+ assert_eq!(steps(&ghosts(&l, 2, 8, &onion)), [(-1, "a")]);
+ assert_eq!(steps(&ghosts(&l, 3, 8, &onion)), [(3, "c"), (-2, "a")]);
+ assert_eq!(steps(&ghosts(&l, 4, 8, &onion)), [(-3, "a"), (2, "c"), (-1, "b")]);
+ assert!(ghosts(&l, 4, 8, &onion).iter().all(|g| g.tint.is_none()));
+ let drawings = Onion {
+ tint: false,
+ ..Onion::default()
+ };
+ assert_eq!(steps(&ghosts(&l, 4, 8, &drawings)), [(-2, "a"), (1, "c"), (-1, "b")]);
+ }
+
+ #[test]
+ fn a_looping_range_wraps_the_onion() {
+ let l = layer(vec![
+ held("a", 0, 2),
+ held("b", 2, 2),
+ held("c", 4, 2),
+ held("d", 6, 2),
+ held("z", 8, 4),
+ ]);
+ let wrap = Onion {
+ wrap: Some((0, 7)),
+ before: 1,
+ after: 1,
+ ..Onion::default()
+ };
+ assert_eq!(steps(&ghosts(&l, 6, 12, &wrap)), [(1, "a"), (-1, "c")]);
+ assert_eq!(steps(&ghosts(&l, 0, 12, &wrap)), [(1, "b"), (-1, "d")]);
+ assert_eq!(steps(&ghosts(&l, 9, 12, &wrap)), [(-1, "d")]);
+ let frames = Onion {
+ by: By::Frames,
+ before: 2,
+ after: 2,
+ ..wrap.clone()
+ };
+ assert_eq!(steps(&ghosts(&l, 7, 12, &frames)), [(-2, "c"), (1, "a")]);
+ let unwrapped = Onion { wrap: None, ..wrap };
+ assert_eq!(steps(&ghosts(&l, 6, 12, &unwrapped)), [(1, "z"), (-1, "c")]);
+ }
+
+ #[test]
+ fn painted_ghosts_tint_fade_and_stack_furthest_first() {
+ let mut solid = Raster::new(256, 256);
+ let px = [0.2, 0.4, 0.6, 1.0].map(f16::from_f32);
+ solid.put(
+ 0,
+ px.iter()
+ .copied()
+ .cycle()
+ .take(TILE_PX * 4)
+ .collect::<Vec<_>>()
+ .into_boxed_slice(),
+ );
+ let rasters = Rasters::from([("a".to_string(), solid.clone()), ("b".to_string(), solid)]);
+ let plain = paint(
+ &[Ghost {
+ cel: "a".into(),
+ step: -1,
+ alpha: 0.5,
+ tint: None,
+ }],
+ &rasters,
+ 256,
+ 256,
+ );
+ let got: Vec<f32> = plain.at(0).unwrap()[..4].iter().map(|v| v.to_f32()).collect();
+ assert!((got[0] - 0.1).abs() < 1e-3 && (got[3] - 0.5).abs() < 1e-3, "{got:?}");
+ let tinted = paint(
+ &[
+ Ghost {
+ cel: "a".into(),
+ step: -2,
+ alpha: 0.25,
+ tint: Some(BEFORE),
+ },
+ Ghost {
+ cel: "b".into(),
+ step: 1,
+ alpha: 0.5,
+ tint: Some(AFTER),
+ },
+ ],
+ &rasters,
+ 256,
+ 256,
+ );
+ let got: Vec<f32> = tinted.at(0).unwrap()[..4].iter().map(|v| v.to_f32()).collect();
+ assert!(got[1] > got[0], "the nearer green ghost is on top: {got:?}");
+ assert!((got[3] - (0.5 + 0.25 * 0.5)).abs() < 1e-3, "{got:?}");
+ assert_eq!(paint(&[], &rasters, 256, 256).count(), 0);
+ }
+}
diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rs
new file mode 100644
index 0000000..5d3a9d5
--- /dev/null
+++ b/crates/render/src/overlay.rs
@@ -0,0 +1,688 @@
+use crate::{Frame, View, read_rgba8, vector};
+use anyhow::{Result, anyhow};
+use klad_core::doc::{Document, Kind, Layer, Node};
+use skia_safe::{
+ AlphaType, Canvas, Color4f, ColorSpace, ColorType, Data, ImageInfo, Matrix, Paint, PaintStyle, Rect, images,
+ surfaces,
+};
+
+const GLYPHS: &[(char, [u8; 7])] = &[
+ ('0', [0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E]),
+ ('1', [0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E]),
+ ('2', [0x0E, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1F]),
+ ('3', [0x1F, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0E]),
+ ('4', [0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02]),
+ ('5', [0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E]),
+ ('6', [0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E]),
+ ('7', [0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08]),
+ ('8', [0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E]),
+ ('9', [0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C]),
+ ('A', [0x0E, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11]),
+ ('B', [0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E]),
+ ('C', [0x0E, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0E]),
+ ('D', [0x1C, 0x12, 0x11, 0x11, 0x11, 0x12, 0x1C]),
+ ('E', [0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F]),
+ ('F', [0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10]),
+ ('G', [0x0E, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0F]),
+ ('H', [0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11]),
+ ('I', [0x0E, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E]),
+ ('J', [0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0C]),
+ ('K', [0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11]),
+ ('L', [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F]),
+ ('M', [0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11]),
+ ('N', [0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11]),
+ ('O', [0x0E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E]),
+ ('P', [0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10]),
+ ('Q', [0x0E, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0D]),
+ ('R', [0x1E, 0x11, 0x11, 0x1E, 0x14, 0x12, 0x11]),
+ ('S', [0x0F, 0x10, 0x10, 0x0E, 0x01, 0x01, 0x1E]),
+ ('T', [0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04]),
+ ('U', [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E]),
+ ('V', [0x11, 0x11, 0x11, 0x11, 0x11, 0x0A, 0x04]),
+ ('W', [0x11, 0x11, 0x11, 0x15, 0x15, 0x15, 0x0A]),
+ ('X', [0x11, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x11]),
+ ('Y', [0x11, 0x11, 0x11, 0x0A, 0x04, 0x04, 0x04]),
+ ('Z', [0x1F, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1F]),
+ ('a', [0x00, 0x00, 0x0E, 0x01, 0x0F, 0x11, 0x0F]),
+ ('b', [0x10, 0x10, 0x16, 0x19, 0x11, 0x11, 0x1E]),
+ ('c', [0x00, 0x00, 0x0E, 0x10, 0x10, 0x11, 0x0E]),
+ ('d', [0x01, 0x01, 0x0D, 0x13, 0x11, 0x11, 0x0F]),
+ ('e', [0x00, 0x00, 0x0E, 0x11, 0x1F, 0x10, 0x0E]),
+ ('f', [0x06, 0x09, 0x08, 0x1C, 0x08, 0x08, 0x08]),
+ ('g', [0x00, 0x00, 0x0F, 0x11, 0x0F, 0x01, 0x0E]),
+ ('h', [0x10, 0x10, 0x16, 0x19, 0x11, 0x11, 0x11]),
+ ('i', [0x04, 0x00, 0x0C, 0x04, 0x04, 0x04, 0x0E]),
+ ('j', [0x02, 0x00, 0x06, 0x02, 0x02, 0x12, 0x0C]),
+ ('k', [0x10, 0x10, 0x12, 0x14, 0x18, 0x14, 0x12]),
+ ('l', [0x0C, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E]),
+ ('m', [0x00, 0x00, 0x1A, 0x15, 0x15, 0x11, 0x11]),
+ ('n', [0x00, 0x00, 0x16, 0x19, 0x11, 0x11, 0x11]),
+ ('o', [0x00, 0x00, 0x0E, 0x11, 0x11, 0x11, 0x0E]),
+ ('p', [0x00, 0x00, 0x1E, 0x11, 0x1E, 0x10, 0x10]),
+ ('q', [0x00, 0x00, 0x0D, 0x13, 0x0F, 0x01, 0x01]),
+ ('r', [0x00, 0x00, 0x16, 0x19, 0x10, 0x10, 0x10]),
+ ('s', [0x00, 0x00, 0x0E, 0x10, 0x0E, 0x01, 0x1E]),
+ ('t', [0x08, 0x08, 0x1C, 0x08, 0x08, 0x09, 0x06]),
+ ('u', [0x00, 0x00, 0x11, 0x11, 0x11, 0x13, 0x0D]),
+ ('v', [0x00, 0x00, 0x11, 0x11, 0x11, 0x0A, 0x04]),
+ ('w', [0x00, 0x00, 0x11, 0x11, 0x15, 0x15, 0x0A]),
+ ('x', [0x00, 0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11]),
+ ('y', [0x00, 0x00, 0x11, 0x11, 0x0F, 0x01, 0x0E]),
+ ('z', [0x00, 0x00, 0x1F, 0x02, 0x04, 0x08, 0x1F]),
+ ('-', [0, 0, 0, 0x1F, 0, 0, 0]),
+ ('_', [0, 0, 0, 0, 0, 0, 0x1F]),
+ ('.', [0, 0, 0, 0, 0, 0x0C, 0x0C]),
+ (',', [0, 0, 0, 0, 0x0C, 0x04, 0x08]),
+ (':', [0, 0x0C, 0x0C, 0, 0x0C, 0x0C, 0]),
+ ('/', [0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10]),
+ ('>', [0x08, 0x04, 0x02, 0x01, 0x02, 0x04, 0x08]),
+ ('(', [0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02]),
+ (')', [0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08]),
+ ('#', [0x0A, 0x0A, 0x1F, 0x0A, 0x1F, 0x0A, 0x0A]),
+ ('+', [0, 0x04, 0x04, 0x1F, 0x04, 0x04, 0]),
+ ('=', [0, 0, 0x1F, 0, 0x1F, 0, 0]),
+ ('?', [0x0E, 0x11, 0x01, 0x02, 0x04, 0, 0x04]),
+ ('|', [0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04]),
+ ('[', [0x0E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0E]),
+ (']', [0x0E, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0E]),
+];
+
+const HUES: [[f32; 3]; 8] = [
+ [1.0, 0.36, 0.36],
+ [0.25, 0.8, 1.0],
+ [1.0, 0.82, 0.2],
+ [0.45, 1.0, 0.45],
+ [0.95, 0.45, 1.0],
+ [1.0, 0.6, 0.25],
+ [0.4, 0.55, 1.0],
+ [0.3, 1.0, 0.85],
+];
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Mark {
+ pub label: String,
+ pub rect: [f32; 4],
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Arc {
+ pub label: String,
+ pub points: Vec<(u32, [f32; 2])>,
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct Overlay {
+ pub marks: Vec<Mark>,
+ pub boxes: bool,
+ pub ids: bool,
+ pub grid: bool,
+ pub arcs: Vec<Arc>,
+ pub frame: Option<u32>,
+ pub numbers: bool,
+}
+
+fn draw_arcs(canvas: &Canvas, overlay: &Overlay, to_out: impl Fn([f32; 2]) -> (f32, f32), px: f32) {
+ let mut placed: Vec<Rect> = Vec::new();
+ overlay.arcs.iter().enumerate().for_each(|(i, arc)| {
+ let hue = HUES[(i + 3) % HUES.len()];
+ let pts: Vec<(u32, (f32, f32))> = arc.points.iter().map(|(f, p)| (*f, to_out(*p))).collect();
+ let pen = |rgb: [f32; 3], a: f32, width: f32| {
+ let mut paint = color(rgb, a);
+ paint.set_anti_alias(true);
+ paint.set_style(PaintStyle::Stroke);
+ paint.set_stroke_width(width);
+ paint
+ };
+ let (back, front) = (pen([0.0, 0.0, 0.0], 0.6, 3.5 * px), pen(hue, 1.0, 1.5 * px));
+ pts.windows(2).for_each(|w| {
+ canvas.draw_line(w[0].1, w[1].1, &back);
+ canvas.draw_line(w[0].1, w[1].1, &front);
+ });
+ let mut dot = color(hue, 1.0);
+ dot.set_anti_alias(true);
+ pts.iter().enumerate().for_each(|(k, (frame, at))| {
+ let prev = pts[k.saturating_sub(1)].1;
+ let next = pts[(k + 1).min(pts.len() - 1)].1;
+ let (dx, dy) = (next.0 - prev.0, next.1 - prev.1);
+ let len = (dx * dx + dy * dy).sqrt();
+ let (nx, ny) = if len < 1e-3 { (0.0, 1.0) } else { (-dy / len, dx / len) };
+ let tick = 6.0 * px;
+ let ends = (
+ (at.0 - nx * tick, at.1 - ny * tick),
+ (at.0 + nx * tick, at.1 + ny * tick),
+ );
+ canvas.draw_line(ends.0, ends.1, &back);
+ canvas.draw_line(ends.0, ends.1, &front);
+ let current = overlay.frame == Some(*frame);
+ if current {
+ canvas.draw_circle(*at, 5.5 * px, &pen([1.0, 1.0, 1.0], 1.0, 2.0 * px));
+ }
+ canvas.draw_circle(*at, if current { 4.0 } else { 2.5 } * px, &dot);
+ if overlay.numbers || current {
+ let text = frame.to_string();
+ let (tx, ty) = (at.0 + nx * 9.0 * px + 2.0, at.1 + ny * 9.0 * px - 3.5 * px);
+ draw_text(canvas, &text, tx + px, ty + px, px, [0.0, 0.0, 0.0]);
+ draw_text(canvas, &text, tx, ty, px, hue);
+ }
+ });
+ if let Some((_, first)) = pts.first() {
+ let (lw, lh) = (text_width(&arc.label, px) + 4.0 * px + 3.0, 11.0 * px);
+ let mut at = Rect::from_xywh(first.0 + 10.0 * px, first.1 - 16.0 * px, lw, lh);
+ while placed.iter().any(|p| Rect::intersects2(p, at)) {
+ at.offset((0.0, -(lh + 1.0)));
+ }
+ draw_label(canvas, &arc.label, at.left, at.top, px, hue);
+ placed.push(at);
+ }
+ });
+}
+
+fn glyph(c: char) -> [u8; 7] {
+ GLYPHS
+ .iter()
+ .find(|(g, _)| *g == c)
+ .or_else(|| GLYPHS.iter().find(|(g, _)| *g == c.to_ascii_uppercase()))
+ .map_or([0; 7], |(_, rows)| *rows)
+}
+
+fn color(rgb: [f32; 3], a: f32) -> Paint {
+ let mut paint = Paint::new(Color4f::new(rgb[0], rgb[1], rgb[2], a), &ColorSpace::new_srgb());
+ paint.set_anti_alias(false);
+ paint
+}
+
+pub fn text_width(text: &str, px: f32) -> f32 {
+ text.chars().count() as f32 * 6.0 * px - px
+}
+
+pub fn draw_text(canvas: &Canvas, text: &str, x: f32, y: f32, px: f32, rgb: [f32; 3]) {
+ let paint = color(rgb, 1.0);
+ text.chars().enumerate().for_each(|(i, c)| {
+ let ox = x + i as f32 * 6.0 * px;
+ glyph(c).iter().enumerate().for_each(|(row, bits)| {
+ (0..5).filter(|col| bits & (0x10 >> col) != 0).for_each(|col| {
+ canvas.draw_rect(
+ Rect::from_xywh(ox + col as f32 * px, y + row as f32 * px, px, px),
+ &paint,
+ );
+ });
+ });
+ });
+}
+
+pub fn draw_label(canvas: &Canvas, text: &str, x: f32, y: f32, px: f32, accent: [f32; 3]) {
+ let w = text_width(text, px) + 4.0 * px + 3.0;
+ let h = 11.0 * px;
+ canvas.draw_rect(Rect::from_xywh(x, y, w, h), &color([0.05, 0.06, 0.08], 0.78));
+ canvas.draw_rect(Rect::from_xywh(x, y, 3.0, h), &color(accent, 1.0));
+ draw_text(canvas, text, x + 3.0 + 2.0 * px, y + 2.0 * px, px, [1.0, 1.0, 1.0]);
+}
+
+fn grid_step(scale: f32) -> f32 {
+ [8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0]
+ .into_iter()
+ .find(|s| s * scale >= 70.0)
+ .unwrap_or(4096.0)
+}
+
+fn draw_grid(canvas: &Canvas, origin: (f32, f32), scale: f32, size: (f32, f32), px: f32) {
+ let step = grid_step(scale);
+ let mut line = color([1.0, 1.0, 1.0], 0.35);
+ line.set_style(PaintStyle::Stroke);
+ line.set_stroke_width(1.0);
+ let mut shade = color([0.0, 0.0, 0.0], 0.35);
+ shade.set_style(PaintStyle::Stroke);
+ shade.set_stroke_width(1.0);
+ let first = |o: f32| (o / step).ceil() * step;
+ let xs = std::iter::successors(Some(first(origin.0)), |v| Some(v + step))
+ .take_while(|v| (v - origin.0) * scale <= size.0);
+ xs.for_each(|v| {
+ let x = ((v - origin.0) * scale).round() + 0.5;
+ canvas.draw_line((x + 1.0, 0.0), (x + 1.0, size.1), &shade);
+ canvas.draw_line((x, 0.0), (x, size.1), &line);
+ draw_label(canvas, &format!("{v:.0}"), x + 2.0, 2.0, px, [1.0, 1.0, 1.0]);
+ });
+ let ys = std::iter::successors(Some(first(origin.1)), |v| Some(v + step))
+ .take_while(|v| (v - origin.1) * scale <= size.1);
+ ys.for_each(|v| {
+ let y = ((v - origin.1) * scale).round() + 0.5;
+ canvas.draw_line((0.0, y + 1.0), (size.0, y + 1.0), &shade);
+ canvas.draw_line((0.0, y), (size.0, y), &line);
+ draw_label(canvas, &format!("{v:.0}"), 2.0, y + 2.0, px, [1.0, 1.0, 1.0]);
+ });
+}
+
+pub fn apply(image: &skia_safe::Image, overlay: &Overlay, view: &View) -> Result<Frame> {
+ let (w, h) = (image.width(), image.height());
+ let info = crate::f16_info(w as u32, h as u32);
+ let mut surface = surfaces::raster(&info, None, None).ok_or_else(|| anyhow!("cannot allocate {w}x{h}"))?;
+ let canvas = surface.canvas();
+ canvas.draw_image(image, (0, 0), None);
+ let origin = view.region.map_or((0.0, 0.0), |[x, y, _, _]| (x as f32, y as f32));
+ let s = view.scale;
+ let px = if w.max(h) >= 1400 { 2.0 } else { 1.0 };
+ if overlay.grid {
+ draw_grid(canvas, origin, s, (w as f32, h as f32), px);
+ }
+ let to_out = |r: [f32; 4]| [(r[0] - origin.0) * s, (r[1] - origin.1) * s, r[2] * s, r[3] * s];
+ if overlay.boxes {
+ overlay.marks.iter().enumerate().for_each(|(i, m)| {
+ let [x, y, bw, bh] = to_out(m.rect);
+ let mut back = color([0.0, 0.0, 0.0], 0.55);
+ back.set_style(PaintStyle::Stroke);
+ back.set_stroke_width(3.0);
+ let mut front = color(HUES[i % HUES.len()], 1.0);
+ front.set_style(PaintStyle::Stroke);
+ front.set_stroke_width(1.5);
+ let rect = Rect::from_xywh(x, y, bw, bh);
+ canvas.draw_rect(rect, &back);
+ canvas.draw_rect(rect, &front);
+ });
+ }
+ draw_arcs(canvas, overlay, |p| ((p[0] - origin.0) * s, (p[1] - origin.1) * s), px);
+ if overlay.ids {
+ let mut placed: Vec<Rect> = Vec::new();
+ overlay.marks.iter().enumerate().for_each(|(i, m)| {
+ let [x, y, _, _] = to_out(m.rect);
+ let lw = text_width(&m.label, px) + 4.0 * px + 3.0;
+ let lh = 11.0 * px;
+ let mut at = Rect::from_xywh(
+ x.clamp(0.0, (w as f32 - lw).max(0.0)),
+ y.clamp(0.0, (h as f32 - lh).max(0.0)),
+ lw,
+ lh,
+ );
+ while placed.iter().any(|p| Rect::intersects2(p, at)) && at.bottom < h as f32 - lh {
+ at.offset((0.0, lh + 1.0));
+ }
+ draw_label(canvas, &m.label, at.left, at.top, px, HUES[i % HUES.len()]);
+ placed.push(at);
+ });
+ }
+ read_rgba8(&surface.image_snapshot())
+}
+
+fn layer_marks(layer: &Layer, frame: u32, depth: usize, out: &mut Vec<Mark>) -> anyhow::Result<()> {
+ if !layer.visible {
+ return Ok(());
+ }
+ match layer.kind() {
+ Kind::Vector => layer.content_at(frame).map_or(Ok(()), |cel| {
+ node_marks(&cel.nodes, &Matrix::new_identity(), depth, out)
+ }),
+ Kind::Group => layer
+ .children()
+ .iter()
+ .try_for_each(|c| layer_marks(c, frame, depth, out)),
+ Kind::Paint | Kind::Adjust => Ok(()),
+ }
+}
+
+fn node_marks(nodes: &[Node], parent: &Matrix, depth: usize, out: &mut Vec<Mark>) -> anyhow::Result<()> {
+ nodes.iter().filter(|n| n.visible).try_for_each(|n| {
+ if depth > 1 && !n.children().is_empty() {
+ let m = Matrix::concat(parent, &vector::node_matrix(n)?);
+ return node_marks(n.children(), &m, depth - 1, out);
+ }
+ if let Some(r) = vector::node_bounds(n, parent)? {
+ let label = if n.name.is_empty() {
+ n.id.clone()
+ } else {
+ format!("{} {}", n.id, n.name)
+ };
+ out.push(Mark {
+ label,
+ rect: vector::to_box(r),
+ });
+ }
+ Ok(())
+ })
+}
+
+pub fn vector_marks(doc: &Document, frame: u32, depth: usize) -> Result<Vec<Mark>> {
+ let mut out = Vec::new();
+ doc.layers
+ .iter()
+ .try_for_each(|l| layer_marks(l, frame, depth, &mut out))?;
+ Ok(out)
+}
+
+pub fn scoped_marks(doc: &Document, id: &str, frame: u32, depth: usize) -> Result<Vec<Mark>> {
+ let mut out = Vec::new();
+ match doc.item(id) {
+ Some(klad_core::doc::Item::Layer(layer)) => layer_marks(layer, frame, depth, &mut out)?,
+ Some(klad_core::doc::Item::Node(..)) => {
+ let (node, matrix) = node_world(doc, id)?.ok_or_else(|| anyhow!("no node {id}"))?;
+ if node.children().is_empty() {
+ node_marks(std::slice::from_ref(node), &matrix, 1, &mut out)?;
+ } else {
+ let inner = Matrix::concat(&matrix, &vector::node_matrix(node)?);
+ node_marks(node.children(), &inner, depth, &mut out)?;
+ }
+ }
+ _ => {}
+ }
+ Ok(out)
+}
+
+fn find_node<'a>(nodes: &'a [Node], id: &str, parent: &Matrix) -> Result<Option<(&'a Node, Matrix)>> {
+ for n in nodes {
+ if n.id == id {
+ return Ok(Some((n, *parent)));
+ }
+ if !n.children().is_empty() {
+ let m = Matrix::concat(parent, &vector::node_matrix(n)?);
+ if let Some(found) = find_node(n.children(), id, &m)? {
+ return Ok(Some(found));
+ }
+ }
+ }
+ Ok(None)
+}
+
+pub fn node_world<'a>(doc: &'a Document, id: &str) -> Result<Option<(&'a Node, Matrix)>> {
+ for layer in doc.all_layers() {
+ for cel in layer.cels() {
+ if let Some(found) = find_node(&cel.nodes, id, &Matrix::new_identity())? {
+ return Ok(Some(found));
+ }
+ }
+ }
+ Ok(None)
+}
+
+fn node_hits(node: &Node, parent: &Matrix, point: (f32, f32)) -> Result<bool> {
+ if !node.visible {
+ return Ok(false);
+ }
+ let m = Matrix::concat(parent, &vector::node_matrix(node)?);
+ let Some(inverse) = m.invert() else {
+ return Ok(false);
+ };
+ let local = inverse.map_point(point);
+ if let Some(clip) = &node.clip
+ && !skia_safe::Path::from_svg(clip).is_some_and(|p| p.contains(local))
+ {
+ return Ok(false);
+ }
+ if !node.children().is_empty() {
+ return vector::instances(&node.shape).iter().try_fold(false, |hit, at| {
+ let placed = Matrix::concat(&m, at);
+ node.children()
+ .iter()
+ .rev()
+ .try_fold(hit, |hit, child| Ok(hit || node_hits(child, &placed, point)?))
+ });
+ }
+ let Some(path) = vector::shape_path(&node.shape)? else {
+ return Ok(false);
+ };
+ let filled = !matches!(&node.fill, Some(klad_core::doc::Paint::Solid(c)) if c == "none");
+ if filled && path.contains(local) {
+ return Ok(true);
+ }
+ let inside = |r: Rect| local.x >= r.left && local.x <= r.right && local.y >= r.top && local.y <= r.bottom;
+ Ok(node.stroke.as_ref().is_some_and(|s| {
+ let pad = s.width / 2.0 + 2.0;
+ let bounds = path.compute_tight_bounds();
+ inside(bounds.with_outset((pad, pad))) && !inside(bounds.with_inset((pad, pad)))
+ }))
+}
+
+fn layer_hits(layer: &Layer, frame: u32, point: (f32, f32), out: &mut Vec<(String, String)>) -> Result<()> {
+ if !layer.visible || layer.locked {
+ return Ok(());
+ }
+ match layer.kind() {
+ Kind::Group => layer
+ .children()
+ .iter()
+ .rev()
+ .try_for_each(|child| layer_hits(child, frame, point, out)),
+ Kind::Vector => {
+ let Some(cel) = layer.content_at(frame) else {
+ return Ok(());
+ };
+ cel.nodes.iter().rev().try_for_each(|node| {
+ if node_hits(node, &Matrix::new_identity(), point)? {
+ out.push((node.id.clone(), layer.id.clone()));
+ }
+ Ok(())
+ })
+ }
+ Kind::Paint | Kind::Adjust => Ok(()),
+ }
+}
+
+pub fn hits(doc: &Document, frame: u32, point: (f32, f32)) -> Result<Vec<(String, String)>> {
+ let mut out = Vec::new();
+ doc.layers
+ .iter()
+ .rev()
+ .try_for_each(|layer| layer_hits(layer, frame, point, &mut out))?;
+ Ok(out)
+}
+
+fn leaf_hit(node: &Node, parent: &Matrix, point: (f32, f32)) -> Result<Option<String>> {
+ if !node.visible {
+ return Ok(None);
+ }
+ if node.children().is_empty() || node.shape.generates() {
+ return Ok(node_hits(node, parent, point)?.then(|| node.id.clone()));
+ }
+ let m = Matrix::concat(parent, &vector::node_matrix(node)?);
+ if let Some(clip) = &node.clip {
+ let local = m.invert().map(|inverse| inverse.map_point(point));
+ if !local.is_some_and(|l| skia_safe::Path::from_svg(clip).is_some_and(|p| p.contains(l))) {
+ return Ok(None);
+ }
+ }
+ node.children().iter().rev().try_fold(None, |found, child| match found {
+ Some(id) => Ok(Some(id)),
+ None => leaf_hit(child, &m, point),
+ })
+}
+
+pub fn leaf_hits(doc: &Document, frame: u32, point: (f32, f32)) -> Result<Vec<String>> {
+ let layers: Vec<&Layer> = doc.all_layers();
+ let mut out = Vec::new();
+ layers
+ .iter()
+ .rev()
+ .filter(|l| l.kind() == Kind::Vector && !l.locked && visible_path(doc, &l.id))
+ .try_for_each(|layer| {
+ let Some(cel) = layer.content_at(frame) else {
+ return Ok::<_, anyhow::Error>(());
+ };
+ cel.nodes.iter().rev().try_for_each(|node| {
+ if let Some(id) = leaf_hit(node, &Matrix::new_identity(), point)? {
+ out.push(id);
+ }
+ Ok(())
+ })
+ })?;
+ Ok(out)
+}
+
+fn visible_path(doc: &Document, id: &str) -> bool {
+ match doc.locate(id) {
+ Some(klad_core::doc::Loc::Layer(path)) => (1..=path.len()).all(|n| {
+ let layer = doc.layer_at(&path[..n]);
+ layer.visible && !layer.locked
+ }),
+ _ => false,
+ }
+}
+
+pub fn local_to_canvas(doc: &Document, id: &str) -> Result<Option<[f32; 6]>> {
+ let Some((node, parent)) = node_world(doc, id)? else {
+ return Ok(None);
+ };
+ let m = Matrix::concat(&parent, &vector::node_matrix(node)?);
+ Ok(Some([
+ m.scale_x(),
+ m.skew_x(),
+ m.skew_y(),
+ m.scale_y(),
+ m.translate_x(),
+ m.translate_y(),
+ ]))
+}
+
+pub fn hit(doc: &Document, frame: u32, point: (f32, f32)) -> Result<Option<(String, String)>> {
+ Ok(hits(doc, frame, point)?.into_iter().next())
+}
+
+pub fn node_world_box(doc: &Document, id: &str) -> Result<Option<[f32; 4]>> {
+ Ok(match node_world(doc, id)? {
+ Some((node, matrix)) => vector::node_bounds(node, &matrix)?.map(vector::to_box),
+ None => None,
+ })
+}
+
+pub fn side_by_side(frames: &[(&Frame, &str)]) -> Result<Frame> {
+ let gap = 16;
+ let band = 26;
+ let w: i32 = frames.iter().map(|(f, _)| f.width as i32).sum::<i32>() + gap * (frames.len() as i32 - 1).max(0);
+ let h: i32 = frames.iter().map(|(f, _)| f.height as i32).max().unwrap_or(1) + band;
+ let mut surface =
+ surfaces::raster(&crate::f16_info(w as u32, h as u32), None, None).ok_or_else(|| anyhow!("cannot allocate"))?;
+ let canvas = surface.canvas();
+ canvas.clear(Color4f::new(0.12, 0.13, 0.15, 1.0));
+ frames.iter().try_fold(0i32, |x, (frame, label)| {
+ let info = ImageInfo::new(
+ (frame.width as i32, frame.height as i32),
+ ColorType::RGBA8888,
+ AlphaType::Unpremul,
+ ColorSpace::new_srgb(),
+ );
+ let image = images::raster_from_data(&info, Data::new_copy(&frame.rgba), frame.width as usize * 4)
+ .ok_or_else(|| anyhow!("cannot wrap frame"))?;
+ canvas.draw_image(&image, (x as f32, band as f32), None);
+ draw_text(canvas, label, x as f32 + 6.0, 6.0, 2.0, [1.0, 1.0, 1.0]);
+ Ok::<_, anyhow::Error>(x + frame.width as i32 + gap)
+ })?;
+ read_rgba8(&surface.image_snapshot())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{Rasters, compose_view};
+ use klad_core::doc::Shape;
+
+ fn doc() -> Document {
+ let mut doc = Document::new(400, 200);
+ doc.canvas.background = Some("#808080".into());
+ let mut sun = Node::new(
+ "n1",
+ Shape::Ellipse {
+ cx: 100.0,
+ cy: 100.0,
+ rx: 40.0,
+ ry: 40.0,
+ },
+ )
+ .filled("#ffcc00");
+ sun.name = "sun".into();
+ let mut group = Node::new(
+ "g1",
+ Shape::Group {
+ children: vec![
+ Node::new(
+ "n2",
+ Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 50.0,
+ h: 20.0,
+ radius: 0.0,
+ },
+ )
+ .filled("#00ff00"),
+ ],
+ },
+ );
+ group.transform.x = 250.0;
+ group.transform.y = 120.0;
+ doc.layers.push(Layer::vector("l1", "shapes", "c1", vec![sun, group]));
+ doc
+ }
+
+ #[test]
+ fn marks_follow_depth_and_scope() {
+ let d = doc();
+ let top = vector_marks(&d, 0, 1).unwrap();
+ assert_eq!(
+ top.iter().map(|m| m.label.as_str()).collect::<Vec<_>>(),
+ ["n1 sun", "g1"]
+ );
+ let deep = vector_marks(&d, 0, 2).unwrap();
+ assert_eq!(deep[1].label, "n2");
+ assert!((deep[1].rect[0] - 250.0).abs() < 0.01 && (deep[1].rect[1] - 120.0).abs() < 0.01);
+ assert_eq!(scoped_marks(&d, "g1", 0, 1).unwrap()[0].label, "n2");
+ assert_eq!(node_world_box(&d, "n2").unwrap().unwrap(), [250.0, 120.0, 50.0, 20.0]);
+ }
+
+ #[test]
+ fn hits_pick_the_topmost_shape() {
+ let d = doc();
+ assert_eq!(hit(&d, 0, (100.0, 100.0)).unwrap(), Some(("n1".into(), "l1".into())));
+ assert_eq!(hit(&d, 0, (260.0, 130.0)).unwrap(), Some(("g1".into(), "l1".into())));
+ assert_eq!(hit(&d, 0, (350.0, 20.0)).unwrap(), None);
+ let mut stacked = d.clone();
+ let cover = Node::new(
+ "cover",
+ klad_core::doc::Shape::Rect {
+ x: 0.0,
+ y: 0.0,
+ w: 400.0,
+ h: 200.0,
+ radius: 0.0,
+ },
+ );
+ stacked.layers[0].cels_mut().unwrap()[0].nodes.push(cover);
+ let ids: Vec<String> = hits(&stacked, 0, (100.0, 100.0))
+ .unwrap()
+ .into_iter()
+ .map(|(n, _)| n)
+ .collect();
+ assert_eq!(ids, ["cover", "n1"]);
+ stacked.layers[0].locked = true;
+ assert!(hits(&stacked, 0, (100.0, 100.0)).unwrap().is_empty());
+ }
+
+ #[test]
+ fn direct_selection_reaches_into_groups() {
+ let d = doc();
+ assert_eq!(leaf_hits(&d, 0, (260.0, 130.0)).unwrap(), ["n2"]);
+ assert_eq!(leaf_hits(&d, 0, (100.0, 100.0)).unwrap(), ["n1"]);
+ assert!(leaf_hits(&d, 0, (350.0, 20.0)).unwrap().is_empty());
+ let m = local_to_canvas(&d, "n2").unwrap().unwrap();
+ assert_eq!(m, [1.0, 0.0, 0.0, 1.0, 250.0, 120.0]);
+ let mut hidden = d.clone();
+ hidden.layers[0].visible = false;
+ assert!(leaf_hits(&hidden, 0, (100.0, 100.0)).unwrap().is_empty());
+ }
+
+ #[test]
+ fn overlays_draw_boxes_labels_and_grid() {
+ let d = doc();
+ let view = View::scaled(1.0);
+ let plain = compose_view(&d, 0, &Rasters::new(), view, None, None).unwrap();
+ let overlay = Overlay {
+ marks: vector_marks(&d, 0, 1).unwrap(),
+ boxes: true,
+ ids: true,
+ grid: true,
+ ..Overlay::default()
+ };
+ let marked = compose_view(&d, 0, &Rasters::new(), view, Some(&overlay), None).unwrap();
+ assert_eq!((marked.width, marked.height), (plain.width, plain.height));
+ assert_ne!(marked.pixel(60, 60), plain.pixel(60, 60));
+ assert_eq!(marked.pixel(100, 150), plain.pixel(100, 150));
+ let pair = side_by_side(&[(&plain, "before"), (&marked, "after")]).unwrap();
+ assert_eq!(pair.width, 816);
+ assert!(text_width("ab", 1.0) > 0.0);
+ }
+}
diff --git a/crates/render/src/shapes.rs b/crates/render/src/shapes.rs
new file mode 100644
index 0000000..4fdc0a8
--- /dev/null
+++ b/crates/render/src/shapes.rs
@@ -0,0 +1,810 @@
+use crate::overlay;
+use anyhow::{Result, anyhow, bail};
+use klad_core::cut::inside_polygon;
+use klad_core::doc::{Document, Item, Shape};
+use klad_core::path::{flatten as flatten_d, resample};
+use klad_core::pathedit;
+use klad_core::rng::Rng;
+
+pub type P = [f32; 2];
+pub type Run = Vec<[f32; 3]>;
+
+const STEP: f32 = 2.0;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Outline {
+ pub node: String,
+ pub points: Vec<P>,
+ pub closed: bool,
+}
+
+fn sub(a: P, b: P) -> P {
+ [a[0] - b[0], a[1] - b[1]]
+}
+
+fn add(a: P, b: P) -> P {
+ [a[0] + b[0], a[1] + b[1]]
+}
+
+fn scale(a: P, k: f32) -> P {
+ [a[0] * k, a[1] * k]
+}
+
+fn len(a: P) -> f32 {
+ libm::sqrtf(a[0] * a[0] + a[1] * a[1])
+}
+
+fn unit(a: P) -> P {
+ let l = len(a);
+ if l < 1e-6 { [0.0, 0.0] } else { scale(a, 1.0 / l) }
+}
+
+fn dot(a: P, b: P) -> f32 {
+ a[0] * b[0] + a[1] * b[1]
+}
+
+fn affine(m: [f32; 6], p: P) -> P {
+ [m[0] * p[0] + m[1] * p[1] + m[4], m[2] * p[0] + m[3] * p[1] + m[5]]
+}
+
+pub fn area(polygon: &[P]) -> f32 {
+ let n = polygon.len();
+ (0..n)
+ .map(|i| {
+ let (a, b) = (polygon[i], polygon[(i + 1) % n]);
+ a[0] * b[1] - b[0] * a[1]
+ })
+ .sum::<f32>()
+ / 2.0
+}
+
+fn node_outlines(doc: &Document, id: &str, step: f32, out: &mut Vec<Outline>) -> Result<()> {
+ let Some(Item::Node(_, _, node)) = doc.item(id) else {
+ bail!("{id} is not a vector shape (rect, ellipse, path or group)");
+ };
+ if let Shape::Group { children } = &node.shape {
+ return children.iter().try_for_each(|c| node_outlines(doc, &c.id, step, out));
+ }
+ let m = overlay::local_to_canvas(doc, id)?.ok_or_else(|| anyhow!("{id} has no place on the canvas"))?;
+ let subs = pathedit::from_shape(&node.shape)?;
+ pathedit::flatten(&subs, step)
+ .into_iter()
+ .zip(subs.iter())
+ .filter(|(points, _)| points.len() >= 2)
+ .for_each(|(points, s)| {
+ let mut points: Vec<P> = points.iter().map(|p| affine(m, *p)).collect();
+ if s.closed && points.len() > 2 && len(sub(points[0], points[points.len() - 1])) < 0.01 {
+ points.pop();
+ }
+ out.push(Outline {
+ node: id.to_string(),
+ points,
+ closed: s.closed,
+ });
+ });
+ Ok(())
+}
+
+pub fn outlines(doc: &Document, ids: &[String]) -> Result<Vec<Outline>> {
+ let mut out = Vec::new();
+ ids.iter().try_for_each(|id| node_outlines(doc, id, STEP, &mut out))?;
+ Ok(out)
+}
+
+pub fn path_outlines(d: &str) -> Result<Vec<Outline>> {
+ Ok(flatten_d(d)?
+ .into_iter()
+ .filter(|l| l.len() >= 2)
+ .map(|mut points| {
+ let closed = points.len() > 2 && len(sub(points[0], points[points.len() - 1])) < 0.01;
+ if closed {
+ points.pop();
+ }
+ Outline {
+ node: "path".into(),
+ points,
+ closed,
+ }
+ })
+ .collect())
+}
+
+fn even(points: &[P], closed: bool) -> Vec<P> {
+ let mut ring = points.to_vec();
+ if closed && !ring.is_empty() {
+ ring.push(ring[0]);
+ }
+ let mut out = resample(&ring, STEP);
+ if closed && out.len() > 2 && len(sub(out[0], out[out.len() - 1])) < STEP * 0.5 {
+ out.pop();
+ }
+ out
+}
+
+fn tangents(points: &[P], closed: bool) -> Vec<P> {
+ let n = points.len();
+ (0..n)
+ .map(|i| {
+ let prev = match (i, closed) {
+ (0, true) => points[n - 1],
+ (0, false) => points[0],
+ _ => points[i - 1],
+ };
+ let next = match (i + 1 == n, closed) {
+ (true, true) => points[0],
+ (true, false) => points[i],
+ _ => points[i + 1],
+ };
+ unit(sub(next, prev))
+ })
+ .collect()
+}
+
+pub fn outward(points: &[P], closed: bool) -> Vec<P> {
+ let lefts: Vec<P> = tangents(points, closed).iter().map(|t| [t[1], -t[0]]).collect();
+ if !closed || points.len() < 3 {
+ return lefts;
+ }
+ let flip = area(points) < 0.0;
+ lefts
+ .into_iter()
+ .map(|n| if flip { scale(n, -1.0) } else { n })
+ .collect()
+}
+
+pub fn offset(polygon: &[P], by: f32) -> Vec<P> {
+ if by == 0.0 || polygon.len() < 3 {
+ return polygon.to_vec();
+ }
+ let normals = outward(polygon, true);
+ polygon
+ .iter()
+ .zip(normals)
+ .map(|(p, n)| add(*p, scale(n, by)))
+ .collect()
+}
+
+pub fn shifted(polygon: &[P], by: P) -> Vec<P> {
+ polygon.iter().map(|p| add(*p, by)).collect()
+}
+
+fn turn(a: P, b: P) -> f32 {
+ let cross = a[0] * b[1] - a[1] * b[0];
+ libm::atan2f(cross, dot(a, b)).abs().to_degrees()
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct InkRules {
+ pub weight: f32,
+ pub light: P,
+ pub break_deg: f32,
+ pub gap: f32,
+ pub wobble: f32,
+ pub seed: u32,
+}
+
+impl Default for InkRules {
+ fn default() -> Self {
+ Self {
+ weight: 6.0,
+ light: [-1.0, -1.0],
+ break_deg: 60.0,
+ gap: 0.0,
+ wobble: 0.6,
+ seed: 1,
+ }
+ }
+}
+
+fn smooth(values: &[f32], closed: bool, reach: usize) -> Vec<f32> {
+ let n = values.len() as i64;
+ (0..n)
+ .map(|i| {
+ let picks: Vec<f32> = (i - reach as i64..=i + reach as i64)
+ .filter_map(|j| match closed {
+ true => Some(values[j.rem_euclid(n) as usize]),
+ false => (0..n).contains(&j).then(|| values[j as usize]),
+ })
+ .collect();
+ picks.iter().sum::<f32>() / picks.len().max(1) as f32
+ })
+ .collect()
+}
+
+pub fn ink(outlines: &[Outline], rules: &InkRules) -> Vec<Run> {
+ let light = unit(rules.light);
+ let closed_shapes: Vec<(usize, &Vec<P>)> = outlines
+ .iter()
+ .enumerate()
+ .filter(|(_, o)| o.closed && o.points.len() >= 3)
+ .map(|(i, o)| (i, &o.points))
+ .collect();
+ outlines
+ .iter()
+ .enumerate()
+ .flat_map(|(index, outline)| {
+ let points = even(&outline.points, outline.closed);
+ if points.len() < 2 {
+ return Vec::new();
+ }
+ let n = points.len();
+ let tangent = tangents(&points, outline.closed);
+ let normal = outward(&points, outline.closed);
+ let corner = |i: usize| -> bool {
+ let (a, b) = match (i, outline.closed) {
+ (0, false) => return false,
+ (i, false) if i + 1 == n => return false,
+ _ => (
+ sub(points[i], points[(i + n - 1) % n]),
+ sub(points[(i + 1) % n], points[i]),
+ ),
+ };
+ turn(a, b) > rules.break_deg
+ || turn(
+ sub(points[i], points[(i + n - 2) % n]),
+ sub(points[(i + 2) % n], points[i]),
+ ) > rules.break_deg * 1.4
+ };
+ let corners: Vec<usize> = (0..n).filter(|i| corner(*i)).fold(Vec::new(), |mut acc, i| {
+ if acc.last().is_none_or(|l| i > *l + 2) {
+ acc.push(i);
+ }
+ acc
+ });
+ let raw: Vec<f32> = (0..n)
+ .map(|i| {
+ let facing = dot(normal[i], light);
+ let lit = 0.55 + 0.45 * (1.0 - facing) / 2.0;
+ let probe = add(points[i], scale(normal[i], 1.5));
+ let inner = closed_shapes
+ .iter()
+ .any(|(j, poly)| *j != index && inside_polygon(poly, (probe[0], probe[1])));
+ let silhouette = if inner { 0.7 } else { 1.0 };
+ let bend = turn(tangent[(i + n - 1) % n], tangent[(i + 1) % n]).to_radians() / (2.0 * STEP);
+ let curve = 1.0 - 0.35 * (bend * rules.weight).min(1.0);
+ lit * silhouette * curve
+ })
+ .collect();
+ let pressure = smooth(&raw, outline.closed, 4);
+ let mut rng = Rng::new(rules.seed as u64 * 7919 + index as u64);
+ let (p1, p2) = (
+ rng.range(0.0, core::f32::consts::TAU),
+ rng.range(0.0, core::f32::consts::TAU),
+ );
+ let wobbled: Vec<[f32; 3]> = (0..n)
+ .map(|i| {
+ let s = i as f32 * STEP;
+ let w = rules.wobble * (0.6 * libm::sinf(s * 0.05 + p1) + 0.4 * libm::sinf(s * 0.13 + p2));
+ let p = add(points[i], scale(normal[i], w));
+ [
+ p[0],
+ p[1],
+ (pressure[i] * (1.0 + 0.05 * libm::sinf(s * 0.09 + p2))).clamp(0.15, 1.0),
+ ]
+ })
+ .collect();
+ let runs: Vec<Run> = match (outline.closed, corners.is_empty()) {
+ (true, true) => {
+ let start = (0..n)
+ .min_by(|a, b| wobbled[*a][2].total_cmp(&wobbled[*b][2]))
+ .unwrap_or(0);
+ let overlap = (12.0 / STEP) as usize;
+ vec![(start..=start + n + overlap).map(|i| wobbled[i % n]).collect()]
+ }
+ (true, false) => (0..corners.len())
+ .map(|k| {
+ let (a, b) = (corners[k], corners[(k + 1) % corners.len()]);
+ let end = if b <= a { b + n } else { b };
+ (a..=end).map(|i| wobbled[i % n]).collect()
+ })
+ .collect(),
+ (false, _) => {
+ let mut cuts = vec![0];
+ cuts.extend(corners.iter().copied());
+ cuts.push(n - 1);
+ cuts.windows(2).map(|w| wobbled[w[0]..=w[1]].to_vec()).collect()
+ }
+ };
+ runs.into_iter()
+ .map(|run| trim(&run, rules.gap))
+ .filter(|run| run.len() >= 2 && run_length(run) >= 3.0)
+ .collect()
+ })
+ .collect()
+}
+
+fn run_length(run: &[[f32; 3]]) -> f32 {
+ run.windows(2)
+ .map(|w| len([w[1][0] - w[0][0], w[1][1] - w[0][1]]))
+ .sum()
+}
+
+fn trim(run: &[[f32; 3]], gap: f32) -> Run {
+ if gap <= 0.0 {
+ return run.to_vec();
+ }
+ let drop = (gap / STEP).ceil() as usize;
+ match run.len() > drop * 2 + 2 {
+ true => run[drop..run.len() - drop].to_vec(),
+ false => Vec::new(),
+ }
+}
+
+pub struct LightCuts {
+ pub polygon: Vec<P>,
+ pub outside: Vec<P>,
+ pub share: f32,
+}
+
+pub fn shade(outlines: &[Outline], light: P, depth: f32, soft: usize) -> Vec<LightCuts> {
+ let l = unit(light);
+ let steps = soft.max(1);
+ outlines
+ .iter()
+ .filter(|o| o.closed && o.points.len() >= 3)
+ .flat_map(|o| {
+ (0..steps).map(move |k| {
+ let spread = match steps {
+ 1 => 1.0,
+ _ => 0.6 + 0.8 * k as f32 / (steps - 1) as f32,
+ };
+ LightCuts {
+ polygon: o.points.clone(),
+ outside: shifted(&o.points, scale(l, depth * spread)),
+ share: 1.0 / steps as f32,
+ }
+ })
+ })
+ .collect()
+}
+
+pub fn rim(outlines: &[Outline], light: P, width: f32) -> Vec<LightCuts> {
+ let l = unit(light);
+ outlines
+ .iter()
+ .filter(|o| o.closed && o.points.len() >= 3)
+ .map(|o| LightCuts {
+ polygon: o.points.clone(),
+ outside: shifted(&o.points, scale(l, -width)),
+ share: 1.0,
+ })
+ .collect()
+}
+
+fn inside_any(areas: &[Vec<P>], p: P) -> bool {
+ areas.iter().any(|a| inside_polygon(a, (p[0], p[1])))
+}
+
+fn taper_profile(k: usize, count: usize) -> f32 {
+ let t = k as f32 / (count.max(2) - 1) as f32;
+ libm::powf(libm::sinf(core::f32::consts::PI * t).max(0.0), 0.6).max(0.15)
+}
+
+fn sampled(points: &[P]) -> Run {
+ let even = resample(points, STEP);
+ let count = even.len();
+ even.iter()
+ .enumerate()
+ .map(|(k, p)| [p[0], p[1], taper_profile(k, count)])
+ .collect()
+}
+
+pub const HATCH_GAP: (f32, f32) = (0.3, 1.1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct HatchRules {
+ pub angle: f32,
+ pub along: bool,
+ pub spacing: f32,
+ pub length: (f32, f32),
+ pub jitter: f32,
+ pub gap: (f32, f32),
+ pub seed: u32,
+}
+
+fn pieces(line: &[P], rules: &HatchRules, rng: &mut Rng, keep: impl Fn(P) -> bool) -> Vec<Run> {
+ let total = klad_core::path::length(line);
+ if total < 1.0 {
+ return Vec::new();
+ }
+ let even = resample(line, STEP);
+ let mut out = Vec::new();
+ let mut at = rng.range(0.0, rules.spacing);
+ while at < total {
+ let size = rng.range(rules.length.0, rules.length.1.max(rules.length.0));
+ let (a, b) = (
+ (at / STEP) as usize,
+ (((at + size) / STEP) as usize).min(even.len() - 1),
+ );
+ let wiggle = rng.signed() * rules.jitter * rules.spacing * 0.5;
+ let piece: Vec<P> = even[a.min(even.len() - 1)..=b]
+ .iter()
+ .enumerate()
+ .map(|(k, p)| {
+ let t = if k + 1 < (b - a + 1) { k } else { k.saturating_sub(1) };
+ let dir = unit(sub(even[(a + t + 1).min(even.len() - 1)], even[a + t]));
+ add(*p, scale([-dir[1], dir[0]], wiggle))
+ })
+ .collect();
+ piece
+ .split(|p| !keep(*p))
+ .filter(|s| s.len() >= 3 && klad_core::path::length(s) >= rules.length.0 * 0.4)
+ .for_each(|s| out.push(sampled(s)));
+ at += size + rng.range(rules.spacing * rules.gap.0, rules.spacing * rules.gap.1);
+ }
+ out
+}
+
+pub fn hatch(areas: &[Vec<P>], rules: &HatchRules) -> Vec<Run> {
+ let mut rng = Rng::new(rules.seed as u64 * 104_729 + 17);
+ let keep = |p: P| inside_any(areas, p);
+ if rules.along {
+ return areas
+ .iter()
+ .flat_map(|poly| {
+ let base = area_ref(poly).abs();
+ (1..400)
+ .map(|k| offset(poly, -(k as f32) * rules.spacing))
+ .take_while(|ring| ring.len() >= 3 && area_ref(ring).abs() > rules.spacing * rules.spacing * 2.0)
+ .take_while(|ring| area_ref(ring).abs() < base * 1.01)
+ .collect::<Vec<_>>()
+ })
+ .flat_map(|ring| {
+ let mut line = ring.clone();
+ line.push(ring[0]);
+ pieces(&line, rules, &mut rng, keep)
+ })
+ .collect();
+ }
+ let a = rules.angle.to_radians();
+ let u = [libm::cosf(a), libm::sinf(a)];
+ let v = [-u[1], u[0]];
+ let all: Vec<P> = areas.iter().flatten().copied().collect();
+ if all.is_empty() {
+ return Vec::new();
+ }
+ let (vmin, vmax) = all.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| {
+ let d = dot(*p, v);
+ (lo.min(d), hi.max(d))
+ });
+ let (umin, umax) = all.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| {
+ let d = dot(*p, u);
+ (lo.min(d), hi.max(d))
+ });
+ let lines = ((vmax - vmin) / rules.spacing).floor() as usize;
+ (0..=lines)
+ .flat_map(|k| {
+ let t = vmin + rules.spacing * (k as f32 + 0.5) + rng.signed() * rules.jitter * rules.spacing * 0.3;
+ let line = vec![
+ add(scale(v, t), scale(u, umin - 2.0)),
+ add(scale(v, t), scale(u, umax + 2.0)),
+ ];
+ pieces(&line, rules, &mut rng, keep)
+ })
+ .collect()
+}
+
+fn area_ref(polygon: &[P]) -> f32 {
+ area(polygon)
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct ScatterRules {
+ pub count: Option<usize>,
+ pub spacing: f32,
+ pub size: (f32, f32),
+ pub turn: (f32, f32),
+ pub seed: u32,
+}
+
+pub fn scatter(areas: &[Vec<P>], avoid: &[Vec<P>], mark: &[Vec<P>], rules: &ScatterRules) -> Vec<Run> {
+ let mut rng = Rng::new(rules.seed as u64 * 15_485_863 + 3);
+ let all: Vec<P> = areas.iter().flatten().copied().collect();
+ if all.is_empty() || mark.is_empty() {
+ return Vec::new();
+ }
+ let (lo, hi) = all.iter().fold(([f32::MAX; 2], [f32::MIN; 2]), |(lo, hi), p| {
+ ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])])
+ });
+ let fits = |p: P| inside_any(areas, p) && !inside_any(avoid, p);
+ let spots: Vec<P> = match rules.count {
+ Some(count) => {
+ let mut found = Vec::new();
+ let mut tries = 0;
+ while found.len() < count && tries < count * 60 {
+ tries += 1;
+ let p = [rng.range(lo[0], hi[0]), rng.range(lo[1], hi[1])];
+ if fits(p) {
+ found.push(p);
+ }
+ }
+ found
+ }
+ None => {
+ let s = rules.spacing.max(1.0);
+ let (cols, rows) = (
+ ((hi[0] - lo[0]) / s).ceil() as usize,
+ ((hi[1] - lo[1]) / s).ceil() as usize,
+ );
+ (0..rows)
+ .flat_map(|r| (0..cols).map(move |c| (r, c)))
+ .map(|(r, c)| {
+ [
+ lo[0] + (c as f32 + 0.5 + rng.signed() * 0.4) * s,
+ lo[1] + (r as f32 + 0.5 + rng.signed() * 0.4) * s,
+ ]
+ })
+ .filter(|p| fits(*p))
+ .collect()
+ }
+ };
+ spots
+ .iter()
+ .flat_map(|at| {
+ let k = rng.range(rules.size.0, rules.size.1.max(rules.size.0));
+ let a = rng.range(rules.turn.0, rules.turn.1.max(rules.turn.0)).to_radians();
+ let (s, c) = (libm::sinf(a), libm::cosf(a));
+ mark.iter()
+ .map(|line| {
+ let placed: Vec<P> = line
+ .iter()
+ .map(|p| add(*at, [k * (p[0] * c - p[1] * s), k * (p[0] * s + p[1] * c)]))
+ .collect();
+ sampled(&placed)
+ })
+ .collect::<Vec<_>>()
+ })
+ .filter(|run| run.len() >= 2)
+ .collect()
+}
+
+pub fn mark_lines(d: &str) -> Result<Vec<Vec<P>>> {
+ Ok(flatten_d(d)?.into_iter().filter(|l| l.len() >= 2).collect())
+}
+
+pub struct Hand {
+ pub run: Run,
+ pub width: f32,
+ pub taper: [f32; 2],
+}
+
+fn ease(a: f32, b: f32, u: f32) -> f32 {
+ let u = u.clamp(0.0, 1.0);
+ a + (b - a) * (3.0 * u * u - 2.0 * u * u * u)
+}
+
+pub fn hand(run: &Run, rng: &mut Rng, strength: f32, bow: bool) -> Hand {
+ let attack = rng.range(0.12, 0.35);
+ let release = rng.range(0.2, 0.5);
+ let (start, peak, end) = (rng.range(0.08, 0.3), rng.range(0.82, 1.0), rng.range(0.03, 0.18));
+ let sway = rng.signed() * 0.06;
+ let arc = rng.signed() * 0.05;
+ let width = rng.range(0.65, 1.35);
+ let (tin, tout) = (rng.range(0.4, 0.8), rng.range(0.5, 0.9));
+ let k = strength.clamp(0.0, 1.0);
+ if k == 0.0 || run.len() < 2 {
+ return Hand {
+ run: run.clone(),
+ width: 1.0,
+ taper: [0.0, 0.0],
+ };
+ }
+ let mut along = vec![0.0f32];
+ run.windows(2)
+ .for_each(|w| along.push(along[along.len() - 1] + len(sub([w[1][0], w[1][1]], [w[0][0], w[0][1]]))));
+ let length = along[along.len() - 1].max(1e-3);
+ let (first, last) = (run[0], run[run.len() - 1]);
+ let chord = unit(sub([last[0], last[1]], [first[0], first[1]]));
+ let normal = [-chord[1], chord[0]];
+ let bend = if bow { arc * length * k } else { 0.0 };
+ let out = run
+ .iter()
+ .zip(&along)
+ .map(|(q, s)| {
+ let t = s / length;
+ let curve = match t {
+ t if t < attack => ease(start, peak, t / attack),
+ t if t > 1.0 - release => ease(peak, end, (t - (1.0 - release)) / release),
+ t => {
+ peak * (1.0
+ - sway * libm::sinf(core::f32::consts::PI * (t - attack) / (1.0 - attack - release).max(0.01)))
+ }
+ };
+ let lift = bend * libm::sinf(core::f32::consts::PI * t);
+ [
+ q[0] + normal[0] * lift,
+ q[1] + normal[1] * lift,
+ (q[2] * (1.0 - k + k * curve)).clamp(0.02, 1.0),
+ ]
+ })
+ .collect();
+ Hand {
+ run: out,
+ width: 1.0 + k * (width - 1.0),
+ taper: [k * length * attack * tin, k * length * release * tout],
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn circle(cx: f32, cy: f32, r: f32) -> Outline {
+ Outline {
+ node: "c".into(),
+ points: (0..64)
+ .map(|i| {
+ let a = i as f32 / 64.0 * core::f32::consts::TAU;
+ [cx + r * libm::cosf(a), cy + r * libm::sinf(a)]
+ })
+ .collect(),
+ closed: true,
+ }
+ }
+
+ fn square(x: f32, y: f32, s: f32) -> Outline {
+ Outline {
+ node: "s".into(),
+ points: vec![[x, y], [x + s, y], [x + s, y + s], [x, y + s]],
+ closed: true,
+ }
+ }
+
+ fn pressure_near(runs: &[Run], at: P) -> f32 {
+ runs.iter()
+ .flatten()
+ .min_by(|a, b| len(sub([a[0], a[1]], at)).total_cmp(&len(sub([b[0], b[1]], at))))
+ .map(|p| p[2])
+ .unwrap()
+ }
+
+ #[test]
+ fn a_square_is_inked_as_four_strokes_and_a_circle_as_one() {
+ let rules = InkRules {
+ wobble: 0.0,
+ ..InkRules::default()
+ };
+ assert_eq!(ink(&[square(0.0, 0.0, 100.0)], &rules).len(), 4);
+ let ring = ink(&[circle(200.0, 200.0, 80.0)], &rules);
+ assert_eq!(ring.len(), 1);
+ let (first, last) = (ring[0][0], ring[0][ring[0].len() - 1]);
+ assert!(
+ len([last[0] - first[0], last[1] - first[1]]) > 8.0,
+ "the ends overlap past the start"
+ );
+ assert!(
+ ring[0].iter().all(|p| p[2] >= first[2] - 0.05),
+ "a ring starts where its line is lightest"
+ );
+ let open = Outline {
+ node: "o".into(),
+ points: vec![[0.0, 0.0], [100.0, 0.0], [100.0, 100.0]],
+ closed: false,
+ };
+ assert_eq!(ink(&[open], &rules).len(), 2);
+ let gapped = ink(&[square(0.0, 0.0, 100.0)], &InkRules { gap: 6.0, ..rules });
+ assert!(gapped.iter().all(|r| run_length(r) < 92.0));
+ }
+
+ #[test]
+ fn the_side_away_from_the_light_and_the_silhouette_are_heavier() {
+ let rules = InkRules {
+ wobble: 0.0,
+ light: [-1.0, -1.0],
+ ..InkRules::default()
+ };
+ let runs = ink(&[circle(200.0, 200.0, 80.0)], &rules);
+ let lit = pressure_near(&runs, [200.0 - 56.0, 200.0 - 56.0]);
+ let dark = pressure_near(&runs, [200.0 + 56.0, 200.0 + 56.0]);
+ assert!(dark > lit + 0.2, "dark {dark} lit {lit}");
+ let both = ink(&[circle(200.0, 200.0, 100.0), circle(200.0, 200.0, 30.0)], &rules);
+ let outer = pressure_near(&both, [300.0, 200.0]);
+ let inner = pressure_near(&both, [230.0, 200.0]);
+ assert!(outer > inner * 1.25, "outer {outer} inner {inner}");
+ }
+
+ #[test]
+ fn the_wobble_repeats_with_its_seed() {
+ let rules = InkRules::default();
+ let a = ink(&[circle(100.0, 100.0, 50.0)], &rules);
+ assert_eq!(a, ink(&[circle(100.0, 100.0, 50.0)], &rules));
+ assert_ne!(a, ink(&[circle(100.0, 100.0, 50.0)], &InkRules { seed: 2, ..rules }));
+ }
+
+ #[test]
+ fn shade_lies_away_from_the_light_and_rim_towards_it() {
+ let c = circle(200.0, 200.0, 80.0);
+ [[-1.0, -1.0], [1.0, 0.0], [0.0, 1.0]].iter().for_each(|light: &P| {
+ let l = unit(*light);
+ let dark = add([200.0, 200.0], scale(l, -70.0));
+ let bright = add([200.0, 200.0], scale(l, 70.0));
+ let shaded = |p: P, cuts: &[LightCuts]| {
+ cuts.iter()
+ .any(|s| inside_polygon(&s.polygon, (p[0], p[1])) && !inside_polygon(&s.outside, (p[0], p[1])))
+ };
+ let s = shade(std::slice::from_ref(&c), *light, 20.0, 3);
+ assert_eq!(s.len(), 3);
+ assert!(shaded(dark, &s) && !shaded(bright, &s) && !shaded([200.0, 200.0], &s));
+ let r = rim(std::slice::from_ref(&c), *light, 6.0);
+ let edge = add([200.0, 200.0], scale(l, 77.0));
+ assert!(shaded(edge, &r) && !shaded(bright, &r) && !shaded(dark, &r));
+ });
+ }
+
+ #[test]
+ fn hatching_and_scatter_stay_inside_and_repeat() {
+ let area = square(0.0, 0.0, 200.0).points;
+ let rules = HatchRules {
+ angle: 30.0,
+ along: false,
+ spacing: 8.0,
+ length: (12.0, 30.0),
+ jitter: 0.3,
+ gap: HATCH_GAP,
+ seed: 4,
+ };
+ let lines = hatch(std::slice::from_ref(&area), &rules);
+ assert!(lines.len() > 40);
+ assert!(
+ lines
+ .iter()
+ .flatten()
+ .all(|p| (-1.0..=201.0).contains(&p[0]) && (-1.0..=201.0).contains(&p[1]))
+ );
+ assert_eq!(lines, hatch(std::slice::from_ref(&area), &rules));
+ let along = hatch(
+ std::slice::from_ref(&circle(100.0, 100.0, 90.0).points),
+ &HatchRules { along: true, ..rules },
+ );
+ assert!(along.len() > 20);
+ let marks = mark_lines("M0 0 L0 -18").unwrap();
+ let rules = ScatterRules {
+ count: Some(30),
+ spacing: 14.0,
+ size: (0.7, 1.2),
+ turn: (-15.0, 15.0),
+ seed: 9,
+ };
+ let hole = square(50.0, 50.0, 100.0).points;
+ let grass = scatter(std::slice::from_ref(&area), std::slice::from_ref(&hole), &marks, &rules);
+ assert_eq!(grass.len(), 30);
+ assert!(grass.iter().all(|r| !inside_polygon(&hole, (r[0][0], r[0][1]))));
+ let grid = scatter(
+ std::slice::from_ref(&area),
+ &[],
+ &marks,
+ &ScatterRules { count: None, ..rules },
+ );
+ assert!(grid.len() > 150);
+ }
+
+ #[test]
+ fn offsets_grow_and_shrink_polygons() {
+ let s = square(0.0, 0.0, 100.0).points;
+ assert!(area(&offset(&s, 5.0)).abs() > area(&s).abs());
+ assert!(area(&offset(&s, -5.0)).abs() < area(&s).abs());
+ let reversed: Vec<P> = s.iter().rev().copied().collect();
+ assert!(area(&offset(&reversed, 5.0)).abs() > area(&s).abs());
+ }
+
+ #[test]
+ fn a_hand_presses_in_peaks_and_lifts_off_and_repeats_with_its_seed() {
+ let run: Run = (0..60).map(|i| [i as f32 * 2.0, 10.0, 1.0]).collect();
+ let a = hand(&run, &mut Rng::new(9), 1.0, true);
+ let b = hand(&run, &mut Rng::new(9), 1.0, true);
+ assert_eq!(a.run, b.run);
+ let peak = a.run.iter().map(|q| q[2]).fold(0.0f32, f32::max);
+ assert!(peak >= 0.8);
+ assert!(a.run[0][2] < peak * 0.5 && a.run[a.run.len() - 1][2] < peak * 0.4);
+ assert!(a.taper[0] > 0.0 && a.taper[1] > a.taper[0] * 0.3);
+ let widths: Vec<f32> = (0..20)
+ .map(|s| hand(&run, &mut Rng::new(s), 1.0, false).width)
+ .collect();
+ assert!(widths.iter().cloned().fold(0.0f32, f32::max) - widths.iter().cloned().fold(9.0f32, f32::min) > 0.3);
+ let straight = hand(&run, &mut Rng::new(3), 1.0, false);
+ assert!(straight.run.iter().all(|q| (q[1] - 10.0).abs() < 1e-4));
+ let none = hand(&run, &mut Rng::new(3), 0.0, true);
+ assert_eq!(none.run, run);
+ assert_eq!((none.width, none.taper), (1.0, [0.0, 0.0]));
+ }
+}
diff --git a/crates/render/src/sheet.rs b/crates/render/src/sheet.rs
new file mode 100644
index 0000000..13ccd2c
--- /dev/null
+++ b/crates/render/src/sheet.rs
@@ -0,0 +1,296 @@
+use crate::overlay::{draw_text, text_width};
+use crate::{Frame, f16_info, read_rgba8};
+use anyhow::{Result, anyhow, bail};
+use klad_core::doc::{Document, Layer};
+use klad_core::timing::{Cell, cells, sheet_layers};
+use skia_safe::{
+ AlphaType, Color4f, ColorSpace, ColorType, Data, ImageInfo, Paint, PaintStyle, Rect, images, surfaces,
+};
+
+const MARGIN: f32 = 16.0;
+const GAP: f32 = 12.0;
+const TITLE_PX: f32 = 2.0;
+const LINE: f32 = 10.0;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Spot {
+ pub from: u32,
+ pub to: u32,
+ pub hold: bool,
+ pub tokens: Vec<String>,
+}
+
+impl Spot {
+ pub fn title(&self) -> String {
+ let range = match self.from == self.to {
+ true => self.from.to_string(),
+ false => format!("{}-{}", self.from, self.to),
+ };
+ match self.hold {
+ true => format!("{range} hold"),
+ false => range,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Plan {
+ pub layers: Vec<String>,
+ pub spots: Vec<Spot>,
+}
+
+fn token(cell: &Cell) -> String {
+ match cell {
+ Cell::Drawing { cel, start: true } => cel.clone(),
+ Cell::Drawing { cel, start: false } => format!("|{cel}"),
+ Cell::Link {
+ cel,
+ source,
+ start: true,
+ } => format!("{cel}>{source}"),
+ Cell::Link { cel, source, .. } => format!("|{cel}>{source}"),
+ Cell::Blank => ".".into(),
+ }
+}
+
+pub fn range(doc: &Document, spec: &str) -> Result<(u32, u32)> {
+ let last = doc.timeline.frames.saturating_sub(1);
+ if spec == "all" {
+ return Ok((0, last));
+ }
+ if let Some(clip) = doc.timeline.clips.iter().find(|c| c.name == spec) {
+ return Ok((clip.from, clip.to.min(last)));
+ }
+ let parsed: Option<(u32, u32)> = match spec.split_once('-') {
+ Some((a, b)) => a.trim().parse().ok().zip(b.trim().parse().ok()),
+ None => spec.trim().parse().ok().map(|f| (f, f)),
+ };
+ let Some((from, to)) = parsed else {
+ let clips: Vec<&str> = doc.timeline.clips.iter().map(|c| c.name.as_str()).collect();
+ bail!(
+ "--sheet takes all, a range like 0-11 or a clip name{}",
+ match clips.is_empty() {
+ true => " (this document has no clips)".to_string(),
+ false => format!(" ({})", clips.join(", ")),
+ }
+ );
+ };
+ if from > to || to > last {
+ bail!("frames {from}-{to} are not inside the timeline (0-{last})");
+ }
+ Ok((from, to))
+}
+
+fn shown(layers: &[&Layer], frame: u32) -> Vec<Option<String>> {
+ layers
+ .iter()
+ .map(|l| l.content_at(frame).map(|c| c.id.clone()))
+ .collect()
+}
+
+pub fn plan(doc: &Document, from: u32, to: u32, drawings: bool) -> Plan {
+ let layers: Vec<&Layer> = sheet_layers(doc).into_iter().filter(|l| !l.cels().is_empty()).collect();
+ let grid: Vec<Vec<Cell>> = layers.iter().map(|l| cells(l, to + 1)).collect();
+ let holds = |f: u32| f > 0 && shown(&layers, f) == shown(&layers, f - 1);
+ let tokens = |f: u32| grid.iter().map(|c| token(&c[f as usize])).collect::<Vec<_>>();
+ let spots = match drawings {
+ false => (from..=to)
+ .map(|f| Spot {
+ from: f,
+ to: f,
+ hold: holds(f),
+ tokens: tokens(f),
+ })
+ .collect(),
+ true => (from..=to).fold(Vec::<Spot>::new(), |mut out, f| {
+ match out.last_mut() {
+ Some(spot) if holds(f) => spot.to = f,
+ _ => out.push(Spot {
+ from: f,
+ to: f,
+ hold: false,
+ tokens: tokens(f),
+ }),
+ }
+ out
+ }),
+ };
+ Plan {
+ layers: layers.iter().map(|l| format!("{} {}", l.id, l.name)).collect(),
+ spots,
+ }
+}
+
+fn wrap(tokens: &[String], chars: usize) -> Vec<String> {
+ tokens.iter().fold(Vec::<String>::new(), |mut lines, t| {
+ match lines.last_mut() {
+ Some(line) if line.chars().count() + 2 + t.chars().count() <= chars => {
+ line.push_str(" ");
+ line.push_str(t);
+ }
+ _ => lines.push(t.clone()),
+ }
+ lines
+ })
+}
+
+fn paint(rgb: [f32; 3]) -> Paint {
+ let mut p = Paint::new(Color4f::new(rgb[0], rgb[1], rgb[2], 1.0), &ColorSpace::new_srgb());
+ p.set_anti_alias(false);
+ p
+}
+
+pub fn columns_for(count: usize) -> usize {
+ ((count as f64).sqrt().ceil() as usize).max(1)
+}
+
+pub fn draw(plan: &Plan, images: &[&Frame], columns: usize, heading: &str) -> Result<Frame> {
+ let first = images
+ .first()
+ .ok_or_else(|| anyhow!("a sheet needs at least one frame"))?;
+ if images.len() != plan.spots.len() {
+ bail!("{} images for {} sheet cells", images.len(), plan.spots.len());
+ }
+ let (iw, ih) = (first.width as f32, first.height as f32);
+ let columns = columns.clamp(1, images.len());
+ let rows = images.len().div_ceil(columns);
+ let chars = (((iw - 4.0) / 6.0).floor() as usize).max(4);
+ let lines: Vec<Vec<String>> = plan.spots.iter().map(|s| wrap(&s.tokens, chars)).collect();
+ let label = 6.0 + 7.0 * TITLE_PX + 4.0 + lines.iter().map(Vec::len).max().unwrap_or(0) as f32 * LINE;
+ let legend = [
+ format!("layers, top first: {}", plan.layers.join(", ")),
+ "cN starts a drawing |cN holds it cA>cB shows cB again (a link) . blank hold: same picture as the frame before"
+ .to_string(),
+ ];
+ let header = 7.0 * TITLE_PX + 8.0 + legend.len() as f32 * LINE + 8.0;
+ let width = (MARGIN * 2.0 + columns as f32 * iw + (columns - 1) as f32 * GAP)
+ .max(MARGIN * 2.0 + legend.iter().map(|l| text_width(l, 1.0)).fold(0.0, f32::max))
+ .ceil();
+ let height = (MARGIN * 2.0 + header + rows as f32 * (ih + label) + (rows - 1) as f32 * GAP).ceil();
+ let mut surface = surfaces::raster(&f16_info(width as u32, height as u32), None, None)
+ .ok_or_else(|| anyhow!("cannot allocate a {width}x{height} sheet"))?;
+ let canvas = surface.canvas();
+ canvas.clear(Color4f::new(0.12, 0.13, 0.15, 1.0));
+ draw_text(canvas, heading, MARGIN, MARGIN, TITLE_PX, [1.0, 1.0, 1.0]);
+ legend.iter().enumerate().for_each(|(i, line)| {
+ let y = MARGIN + 7.0 * TITLE_PX + 8.0 + i as f32 * LINE;
+ draw_text(canvas, line, MARGIN, y, 1.0, [0.7, 0.72, 0.76]);
+ });
+ let mut border = paint([0.32, 0.34, 0.38]);
+ border.set_style(PaintStyle::Stroke);
+ border.set_stroke_width(1.0);
+ images
+ .iter()
+ .zip(&plan.spots)
+ .zip(&lines)
+ .enumerate()
+ .try_for_each(|(i, ((frame, spot), lines))| {
+ let x = MARGIN + (i % columns) as f32 * (iw + GAP);
+ let y = MARGIN + header + (i / columns) as f32 * (ih + label + GAP);
+ let info = ImageInfo::new(
+ (frame.width as i32, frame.height as i32),
+ ColorType::RGBA8888,
+ AlphaType::Unpremul,
+ ColorSpace::new_srgb(),
+ );
+ let image = images::raster_from_data(&info, Data::new_copy(&frame.rgba), frame.width as usize * 4)
+ .ok_or_else(|| anyhow!("cannot wrap frame {}", spot.from))?;
+ canvas.draw_image(&image, (x, y), None);
+ canvas.draw_rect(Rect::from_xywh(x - 0.5, y - 0.5, iw + 1.0, ih + 1.0), &border);
+ let title = match spot.hold {
+ true => [0.55, 0.57, 0.6],
+ false => [1.0, 1.0, 1.0],
+ };
+ draw_text(canvas, &spot.title(), x + 2.0, y + ih + 6.0, TITLE_PX, title);
+ lines.iter().enumerate().for_each(|(k, line)| {
+ let ty = y + ih + 6.0 + 7.0 * TITLE_PX + 4.0 + k as f32 * LINE;
+ draw_text(canvas, line, x + 2.0, ty, 1.0, [0.78, 0.8, 0.84]);
+ });
+ Ok::<_, anyhow::Error>(())
+ })?;
+ read_rgba8(&surface.image_snapshot())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::{Cel, Clip};
+
+ fn doc() -> Document {
+ let mut doc = Document::new(64, 32);
+ doc.timeline.frames = 8;
+ doc.timeline.clips.push(Clip::new("run", 2, 5, true));
+ let mut ball = Layer::paint("l1", "ball", "c1");
+ *ball.cels_mut().unwrap() = vec![
+ Cel {
+ hold: Some(2),
+ ..Cel::at("c1", 0)
+ },
+ Cel {
+ hold: Some(1),
+ ..Cel::at("c2", 2)
+ },
+ Cel::at("c3", 3),
+ Cel {
+ link: Some("c1".into()),
+ ..Cel::at("c4", 6)
+ },
+ ];
+ let floor = Layer::paint("l2", "floor", "c9");
+ doc.layers = vec![floor, ball];
+ doc
+ }
+
+ #[test]
+ fn frames_get_tokens_and_hold_marks() {
+ let doc = doc();
+ let plan = plan(&doc, 0, 7, false);
+ assert_eq!(plan.layers, ["l1 ball", "l2 floor"]);
+ let row = |f: usize| (plan.spots[f].title(), plan.spots[f].tokens.join(" "));
+ assert_eq!(row(0), ("0".into(), "c1 c9".into()));
+ assert_eq!(row(1), ("1 hold".into(), "|c1 |c9".into()));
+ assert_eq!(row(2), ("2".into(), "c2 |c9".into()));
+ assert_eq!(row(4), ("4 hold".into(), "|c3 |c9".into()));
+ assert_eq!(row(6), ("6".into(), "c4>c1 |c9".into()));
+ assert_eq!(row(7), ("7 hold".into(), "|c4>c1 |c9".into()));
+ }
+
+ #[test]
+ fn drawings_merge_frames_that_look_the_same() {
+ let doc = doc();
+ let plan = plan(&doc, 0, 7, true);
+ let titles: Vec<String> = plan.spots.iter().map(Spot::title).collect();
+ assert_eq!(titles, ["0-1", "2", "3-5", "6-7"]);
+ assert_eq!(plan.spots[3].tokens, ["c4>c1", "|c9"]);
+ }
+
+ #[test]
+ fn ranges_take_all_spans_frames_and_clips() {
+ let doc = doc();
+ assert_eq!(range(&doc, "all").unwrap(), (0, 7));
+ assert_eq!(range(&doc, "2-4").unwrap(), (2, 4));
+ assert_eq!(range(&doc, "5").unwrap(), (5, 5));
+ assert_eq!(range(&doc, "run").unwrap(), (2, 5));
+ assert!(range(&doc, "3-9").is_err());
+ assert!(range(&doc, "walk").unwrap_err().to_string().contains("run"));
+ }
+
+ #[test]
+ fn a_sheet_lays_cells_out_in_a_grid() {
+ let doc = doc();
+ let plan = plan(&doc, 0, 4, false);
+ let frame = Frame {
+ width: 40,
+ height: 20,
+ rgba: [200u8, 40, 40, 255].repeat(800),
+ };
+ let images: Vec<&Frame> = plan.spots.iter().map(|_| &frame).collect();
+ let sheet = draw(&plan, &images, columns_for(images.len()), "test").unwrap();
+ assert_eq!(columns_for(5), 3);
+ let header = 7.0 * TITLE_PX + 8.0 + 2.0 * LINE + 8.0;
+ let (x, y) = (MARGIN as u32 + 41 + GAP as u32 + 5, (MARGIN + header) as u32 + 5);
+ assert_eq!(sheet.pixel(x, y), [200, 40, 40, 255]);
+ assert!(sheet.height > 2 * 20 + header as u32);
+ assert!(draw(&plan, &images[..2], 2, "x").is_err());
+ }
+}
diff --git a/crates/render/src/sprites.rs b/crates/render/src/sprites.rs
new file mode 100644
index 0000000..678ad78
--- /dev/null
+++ b/crates/render/src/sprites.rs
@@ -0,0 +1,785 @@
+use crate::export::{dither8, encode, f16_pixels};
+use crate::rgba8_info;
+use anyhow::{Result, anyhow, bail};
+use klad_core::doc::{Clip, Document};
+use klad_core::rng::{FNV_OFFSET, fnv};
+use serde_json::{Value, json};
+use skia_safe::{AlphaType, ColorSpace, ColorType, Image, ImageInfo, Pixmap};
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Animation {
+ pub name: String,
+ pub from: u32,
+ pub to: u32,
+ pub fps: u32,
+ pub looping: bool,
+ pub clip: bool,
+}
+
+pub fn animations(doc: &Document, spec: &str) -> Result<Vec<Animation>> {
+ let t = &doc.timeline;
+ let last = t.frames - 1;
+ let of_clip = |c: &Clip| Animation {
+ name: c.name.clone(),
+ from: c.from,
+ to: c.to.min(last),
+ fps: t.fps_of(c),
+ looping: c.looping,
+ clip: true,
+ };
+ let whole = |name: &str, from: u32, to: u32| Animation {
+ name: name.to_string(),
+ from,
+ to,
+ fps: t.fps,
+ looping: true,
+ clip: false,
+ };
+ if spec == "all" {
+ return Ok(match t.clips.is_empty() {
+ true => vec![whole("default", 0, last)],
+ false => t.clips.iter().map(of_clip).collect(),
+ });
+ }
+ if let Some(c) = t.clip(spec) {
+ return Ok(vec![of_clip(c)]);
+ }
+ let (from, to) = crate::sheet::range(doc, spec)?;
+ Ok(vec![whole(spec, from, to)])
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Run {
+ pub picture: usize,
+ pub frame: u32,
+ pub frames: u32,
+ pub ms: u32,
+}
+
+fn ms_at(frames: u32, fps: u32) -> u64 {
+ (frames as u64 * 2000 + fps as u64) / (2 * fps as u64)
+}
+
+pub fn runs(anim: &Animation, picture: impl Fn(u32) -> usize) -> Vec<Run> {
+ let grouped = (anim.from..=anim.to).fold(Vec::<Run>::new(), |mut out, f| {
+ let p = picture(f);
+ match out.last_mut() {
+ Some(run) if run.picture == p => run.frames += 1,
+ _ => out.push(Run {
+ picture: p,
+ frame: f,
+ frames: 1,
+ ms: 0,
+ }),
+ }
+ out
+ });
+ grouped
+ .into_iter()
+ .map(|run| {
+ let start = run.frame - anim.from;
+ Run {
+ ms: (ms_at(start + run.frames, anim.fps) - ms_at(start, anim.fps)) as u32,
+ ..run
+ }
+ })
+ .collect()
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Rect {
+ pub x: u32,
+ pub y: u32,
+ pub w: u32,
+ pub h: u32,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Data {
+ Rgba8(Vec<u8>),
+ Rgba16(Vec<half::f16>),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Pixels {
+ pub width: u32,
+ pub height: u32,
+ pub data: Data,
+}
+
+impl Pixels {
+ pub fn of(image: &Image, depth: u8) -> Result<Self> {
+ let data = match depth {
+ 8 => Data::Rgba8(dither8(image)?),
+ 16 => Data::Rgba16(f16_pixels(image, AlphaType::Unpremul)?),
+ other => bail!("--depth takes 8 or 16, not {other}"),
+ };
+ Ok(Self {
+ width: image.width() as u32,
+ height: image.height() as u32,
+ data,
+ })
+ }
+
+ pub fn blank(width: u32, height: u32, depth: u8) -> Self {
+ let n = width as usize * height as usize * 4;
+ let data = match depth {
+ 16 => Data::Rgba16(vec![half::f16::ZERO; n]),
+ _ => Data::Rgba8(vec![0; n]),
+ };
+ Self { width, height, data }
+ }
+
+ pub fn depth(&self) -> u8 {
+ match self.data {
+ Data::Rgba8(_) => 8,
+ Data::Rgba16(_) => 16,
+ }
+ }
+
+ fn bytes(&self) -> &[u8] {
+ match &self.data {
+ Data::Rgba8(d) => d,
+ Data::Rgba16(d) => bytemuck::cast_slice(d),
+ }
+ }
+
+ fn covered(&self, x: u32, y: u32) -> bool {
+ let at = (y as usize * self.width as usize + x as usize) * 4 + 3;
+ match &self.data {
+ Data::Rgba8(d) => d[at] > 0,
+ Data::Rgba16(d) => d[at].to_f32() > 0.0,
+ }
+ }
+
+ pub fn trim(&self) -> Rect {
+ let rows: Vec<u32> = (0..self.height)
+ .filter(|&y| (0..self.width).any(|x| self.covered(x, y)))
+ .collect();
+ let (Some(&top), Some(&bottom)) = (rows.first(), rows.last()) else {
+ return Rect { x: 0, y: 0, w: 1, h: 1 };
+ };
+ let columns = |y: u32| (0..self.width).filter(move |&x| self.covered(x, y));
+ let left = rows.iter().filter_map(|&y| columns(y).next()).min().unwrap_or(0);
+ let right = rows.iter().filter_map(|&y| columns(y).next_back()).max().unwrap_or(0);
+ Rect {
+ x: left,
+ y: top,
+ w: right - left + 1,
+ h: bottom - top + 1,
+ }
+ }
+
+ pub fn hash(&self) -> u64 {
+ let dims = [self.width, self.height].map(u32::to_le_bytes).concat();
+ fnv(fnv(FNV_OFFSET, &dims), self.bytes())
+ }
+
+ pub fn blit(&mut self, from: &Pixels, src: Rect, x: u32, y: u32) {
+ let (fw, tw) = (from.width as usize * 4, self.width as usize * 4);
+ let row = src.w as usize * 4;
+ (0..src.h as usize).for_each(|r| {
+ let a = (src.y as usize + r) * fw + src.x as usize * 4;
+ let b = (y as usize + r) * tw + x as usize * 4;
+ match (&mut self.data, &from.data) {
+ (Data::Rgba8(to), Data::Rgba8(d)) => to[b..b + row].copy_from_slice(&d[a..a + row]),
+ (Data::Rgba16(to), Data::Rgba16(d)) => to[b..b + row].copy_from_slice(&d[a..a + row]),
+ _ => {}
+ }
+ });
+ }
+
+ pub fn crop(&self, rect: Rect) -> Pixels {
+ let mut out = Pixels::blank(rect.w, rect.h, self.depth());
+ out.blit(self, rect, 0, 0);
+ out
+ }
+
+ pub fn png(&mut self) -> Result<Vec<u8>> {
+ let (w, h) = (self.width, self.height);
+ let pixmap = match &mut self.data {
+ Data::Rgba8(d) => Pixmap::new(&rgba8_info(w, h), d, w as usize * 4),
+ Data::Rgba16(d) => {
+ let info = ImageInfo::new(
+ (w as i32, h as i32),
+ ColorType::RGBAF16,
+ AlphaType::Unpremul,
+ ColorSpace::new_srgb(),
+ );
+ Pixmap::new(&info, bytemuck::cast_slice_mut(d), w as usize * 8)
+ }
+ }
+ .ok_or_else(|| anyhow!("bad pixmap"))?;
+ encode(&pixmap)
+ }
+}
+
+pub type Layout = (Vec<Placed>, Vec<(u32, u32)>);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Placed {
+ pub page: usize,
+ pub x: u32,
+ pub y: u32,
+}
+
+fn shelves(sizes: &[(u32, u32)], p: u32, width: u32, max: u32) -> Layout {
+ let mut pages = vec![(0u32, 0u32)];
+ let (mut x, mut y, mut row) = (p, p, 0);
+ let mut placed = Vec::with_capacity(sizes.len());
+ for &(w, h) in sizes {
+ if x + w + p > width {
+ (x, y, row) = (p, y + row + p, 0);
+ }
+ if y + h + p > max {
+ pages.push((0, 0));
+ (x, y, row) = (p, p, 0);
+ }
+ let page = pages.len() - 1;
+ placed.push(Placed { page, x, y });
+ x += w + p;
+ row = row.max(h);
+ let size = &mut pages[page];
+ *size = (size.0.max(x), size.1.max(y + h + p));
+ }
+ (placed, pages)
+}
+
+pub fn pack(sizes: &[(u32, u32)], padding: u32, max: u32) -> Result<Layout> {
+ let p = padding;
+ if let Some((i, (w, h))) = sizes
+ .iter()
+ .enumerate()
+ .find(|(_, (w, h))| w + 2 * p > max || h + 2 * p > max)
+ {
+ bail!(
+ "picture {i} is {w}x{h} after trimming and does not fit a {max} px page with {p} px padding; export at a smaller --scale or raise --max"
+ );
+ }
+ let area: u64 = sizes.iter().map(|&(w, h)| (w + p) as u64 * (h + p) as u64).sum();
+ let widest = sizes.iter().map(|s| s.0).max().unwrap_or(1) + 2 * p;
+ let base = ((area as f64).sqrt().ceil() as u32 + p).max(widest);
+ let tries: Vec<u32> = (0..=10)
+ .map(|k| (base as f64 * (1.0 + k as f64 / 10.0)).ceil() as u32)
+ .map(|w| w.min(max))
+ .collect();
+ let best = tries
+ .iter()
+ .map(|&w| shelves(sizes, p, w, max))
+ .min_by_key(|(_, pages)| {
+ let last = pages.last().copied().unwrap_or_default();
+ (pages.len(), last.0.max(last.1), last.0 as u64 * last.1 as u64)
+ })
+ .unwrap_or_default();
+ Ok(best)
+}
+
+pub struct Sheet<'a> {
+ pub stem: &'a str,
+ pub source: (u32, u32),
+ pub trims: &'a [Rect],
+ pub placed: &'a [Placed],
+ pub pages: &'a [(u32, u32)],
+ pub images: &'a [String],
+ pub animations: &'a [(Animation, Vec<Run>)],
+ pub scale: f32,
+ pub depth: u8,
+}
+
+fn rect_json(r: Rect) -> Value {
+ json!({ "x": r.x, "y": r.y, "w": r.w, "h": r.h })
+}
+
+pub fn aseprite(sheet: &Sheet) -> Value {
+ let (sw, sh) = sheet.source;
+ let mut frames: Vec<Value> = Vec::new();
+ let mut tags: Vec<Value> = Vec::new();
+ sheet.animations.iter().for_each(|(anim, runs)| {
+ let first = frames.len();
+ frames.extend(runs.iter().map(|run| {
+ let (trim, at) = (sheet.trims[run.picture], sheet.placed[run.picture]);
+ let prefix = if anim.clip { anim.name.as_str() } else { sheet.stem };
+ let mut entry = json!({
+ "filename": format!("{prefix} {}", run.frame),
+ "frame": rect_json(Rect { x: at.x, y: at.y, ..trim }),
+ "rotated": false,
+ "trimmed": trim != Rect { x: 0, y: 0, w: sw, h: sh },
+ "spriteSourceSize": rect_json(trim),
+ "sourceSize": { "w": sw, "h": sh },
+ "duration": run.ms,
+ });
+ if at.page > 0 {
+ entry["image"] = json!(sheet.images[at.page]);
+ }
+ entry
+ }));
+ if anim.clip && frames.len() > first {
+ let mut tag = json!({
+ "name": anim.name,
+ "from": first,
+ "to": frames.len() - 1,
+ "direction": "forward",
+ "color": "#000000ff",
+ });
+ if !anim.looping {
+ tag["repeat"] = json!("1");
+ }
+ tags.push(tag);
+ }
+ });
+ let scale = format!("{:.3}", sheet.scale);
+ let mut meta = json!({
+ "app": "klad",
+ "version": env!("CARGO_PKG_VERSION"),
+ "image": sheet.images[0],
+ "format": if sheet.depth == 16 { "RGBA16161616" } else { "RGBA8888" },
+ "size": { "w": sheet.pages[0].0, "h": sheet.pages[0].1 },
+ "scale": scale.trim_end_matches('0').trim_end_matches('.'),
+ "frameTags": tags,
+ "layers": [],
+ "slices": [],
+ });
+ if sheet.pages.len() > 1 {
+ meta["images"] = sheet
+ .images
+ .iter()
+ .zip(sheet.pages)
+ .map(|(image, (w, h))| json!({ "image": image, "size": { "w": w, "h": h } }))
+ .collect();
+ }
+ json!({ "frames": frames, "meta": meta })
+}
+
+fn quoted(text: &str) -> String {
+ format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
+}
+
+fn number(v: f32) -> String {
+ let text = format!("{v:.3}");
+ let text = text.trim_end_matches('0').trim_end_matches('.');
+ match text {
+ "-0" => "0".into(),
+ t => t.into(),
+ }
+}
+
+fn float(v: f32) -> String {
+ let text = number(v);
+ match text.contains('.') {
+ true => text,
+ false => format!("{text}.0"),
+ }
+}
+
+fn rect2(r: [f32; 4]) -> String {
+ format!("Rect2({})", r.map(number).join(", "))
+}
+
+pub struct Texture {
+ pub path: String,
+ pub uid: Option<String>,
+}
+
+pub struct SpriteFrames<'a> {
+ pub uid: &'a str,
+ pub textures: &'a [Texture],
+ pub source: (u32, u32),
+ pub trims: &'a [Rect],
+ pub placed: &'a [Placed],
+ pub animations: &'a [(Animation, Vec<Run>)],
+}
+
+pub fn sprite_frames(res: &SpriteFrames) -> String {
+ let (sw, sh) = res.source;
+ let mut out = format!("[gd_resource type=\"SpriteFrames\" format=3 uid={}]\n", quoted(res.uid));
+ res.textures.iter().enumerate().for_each(|(i, t)| {
+ let uid = t
+ .uid
+ .as_deref()
+ .map_or(String::new(), |u| format!(" uid={}", quoted(u)));
+ out += &format!(
+ "\n[ext_resource type=\"Texture2D\"{uid} path={} id=\"{}_sheet\"]",
+ quoted(&t.path),
+ i + 1
+ );
+ });
+ out += "\n";
+ res.trims.iter().zip(res.placed).enumerate().for_each(|(i, (trim, at))| {
+ out += &format!(
+ "\n[sub_resource type=\"AtlasTexture\" id=\"AtlasTexture_{i}\"]\natlas = ExtResource(\"{}_sheet\")\nregion = {}\n",
+ at.page + 1,
+ rect2([at.x, at.y, trim.w, trim.h].map(|v| v as f32))
+ );
+ let margin = [trim.x, trim.y, sw - trim.w, sh - trim.h];
+ if margin != [0; 4] {
+ out += &format!("margin = {}\n", rect2(margin.map(|v| v as f32)));
+ }
+ });
+ let animations: Vec<String> = res
+ .animations
+ .iter()
+ .map(|(anim, runs)| {
+ let frames: Vec<String> = runs
+ .iter()
+ .map(|run| {
+ format!(
+ "{{\n\"duration\": {},\n\"texture\": SubResource(\"AtlasTexture_{}\")\n}}",
+ float(run.frames as f32),
+ run.picture
+ )
+ })
+ .collect();
+ format!(
+ "{{\n\"frames\": [{}],\n\"loop\": {},\n\"name\": &{},\n\"speed\": {}\n}}",
+ frames.join(", "),
+ anim.looping,
+ quoted(&anim.name),
+ float(anim.fps as f32)
+ )
+ })
+ .collect();
+ out += &format!("\n[resource]\nanimations = [{}]\n", animations.join(", "));
+ out
+}
+
+pub struct Scene<'a> {
+ pub uid: &'a str,
+ pub node: &'a str,
+ pub frames_path: &'a str,
+ pub frames_uid: &'a str,
+ pub animation: &'a str,
+ pub origin: [f32; 2],
+}
+
+pub fn node_name(stem: &str) -> String {
+ let name: String = stem
+ .chars()
+ .map(|c| match c {
+ '.' | ':' | '@' | '/' | '"' | '%' => '_',
+ c => c,
+ })
+ .collect();
+ match name.trim().is_empty() {
+ true => "sprite".into(),
+ false => name,
+ }
+}
+
+pub fn scene(s: &Scene) -> String {
+ format!(
+ "[gd_scene format=3 uid={}]\n\n[ext_resource type=\"SpriteFrames\" uid={} path={} id=\"1_frames\"]\n\n[node name={} type=\"AnimatedSprite2D\"]\nsprite_frames = ExtResource(\"1_frames\")\nanimation = &{}\nautoplay = {}\ncentered = false\noffset = Vector2({}, {})\n",
+ quoted(s.uid),
+ quoted(s.frames_uid),
+ quoted(s.frames_path),
+ quoted(s.node),
+ quoted(s.animation),
+ quoted(s.animation),
+ number(-s.origin[0]),
+ number(-s.origin[1])
+ )
+}
+
+pub fn uid_text(mut id: u64) -> String {
+ id &= 0x7fff_ffff_ffff_ffff;
+ let mut digits = Vec::new();
+ loop {
+ let c = (id % 34) as u8;
+ digits.push(if c < 25 { b'a' + c } else { b'0' + c - 25 });
+ id /= 34;
+ if id == 0 {
+ break;
+ }
+ }
+ digits.reverse();
+ format!("uid://{}", String::from_utf8_lossy(&digits))
+}
+
+pub fn uid_for(seed: &str) -> String {
+ uid_text(fnv(FNV_OFFSET, seed.as_bytes()))
+}
+
+fn uid_in(text: &str) -> Option<String> {
+ let at = text.find("uid=\"uid://")? + 5;
+ let end = at + text[at..].find('"')?;
+ Some(text[at..end].to_string())
+}
+
+pub fn header_uid(text: &str) -> Option<String> {
+ uid_in(text.lines().next()?)
+}
+
+pub fn import_uid(text: &str) -> Option<String> {
+ text.lines().find(|l| l.starts_with("uid=")).and_then(uid_in)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use klad_core::doc::Clip;
+
+ fn anim(from: u32, to: u32, fps: u32) -> Animation {
+ Animation {
+ name: "run".into(),
+ from,
+ to,
+ fps,
+ looping: true,
+ clip: true,
+ }
+ }
+
+ #[test]
+ fn runs_merge_held_frames_and_their_milliseconds_add_up_to_the_clip() {
+ let pictures = [0, 0, 1, 2, 2, 2, 0, 3, 3, 3, 3, 3];
+ let run = runs(&anim(0, 11, 12), |f| pictures[f as usize]);
+ assert_eq!(
+ run.iter().map(|r| (r.picture, r.frame, r.frames)).collect::<Vec<_>>(),
+ [(0, 0, 2), (1, 2, 1), (2, 3, 3), (0, 6, 1), (3, 7, 5)]
+ );
+ assert_eq!(run.iter().map(|r| r.ms).collect::<Vec<_>>(), [167, 83, 250, 83, 417]);
+ assert_eq!(run.iter().map(|r| r.ms).sum::<u32>(), 1000);
+ let at24 = runs(&anim(2, 8, 24), |f| pictures[f as usize]);
+ assert_eq!(at24.iter().map(|r| r.ms).sum::<u32>(), 292, "7 frames at 24 fps");
+ assert_eq!(at24[0].frame, 2);
+ }
+
+ #[test]
+ fn animations_come_from_clips_or_the_whole_timeline() {
+ let mut doc = Document::new(8, 8);
+ doc.timeline.frames = 20;
+ let names = |d: &Document, spec: &str| {
+ animations(d, spec)
+ .unwrap()
+ .iter()
+ .map(|a| (a.name.clone(), a.from, a.to, a.fps, a.looping))
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(names(&doc, "all"), [("default".into(), 0, 19, 12, true)]);
+ doc.timeline.clips = vec![
+ Clip::new("idle", 0, 5, true),
+ Clip {
+ fps: Some(24),
+ ..Clip::new("jump", 6, 13, false)
+ },
+ ];
+ assert_eq!(
+ names(&doc, "all"),
+ [("idle".into(), 0, 5, 12, true), ("jump".into(), 6, 13, 24, false)]
+ );
+ assert_eq!(names(&doc, "jump"), [("jump".into(), 6, 13, 24, false)]);
+ assert_eq!(names(&doc, "2-4"), [("2-4".into(), 2, 4, 12, true)]);
+ assert!(animations(&doc, "walk").is_err());
+ }
+
+ #[test]
+ fn packing_keeps_order_and_padding_and_starts_pages_under_the_limit() {
+ let sizes = [(30, 20), (30, 20), (50, 10), (10, 40)];
+ let (placed, pages) = pack(&sizes, 2, 128).unwrap();
+ assert_eq!(pages.len(), 1);
+ let boxes: Vec<[u32; 4]> = placed
+ .iter()
+ .zip(&sizes)
+ .map(|(p, (w, h))| [p.x, p.y, p.x + w, p.y + h])
+ .collect();
+ boxes.iter().enumerate().for_each(|(i, a)| {
+ assert!(a[0] >= 2 && a[1] >= 2 && a[2] + 2 <= pages[0].0 && a[3] + 2 <= pages[0].1);
+ boxes[i + 1..].iter().for_each(|b| {
+ let apart = a[2] + 2 <= b[0] || b[2] + 2 <= a[0] || a[3] + 2 <= b[1] || b[3] + 2 <= a[1];
+ assert!(apart, "{a:?} {b:?}");
+ });
+ });
+ assert_eq!((placed[0].x, placed[0].y, placed[1].x), (2, 2, 34));
+ let (placed, pages) = pack(&[(60, 60); 5], 2, 128).unwrap();
+ assert_eq!(pages.len(), 2);
+ assert_eq!(placed.iter().map(|p| p.page).collect::<Vec<_>>(), [0, 0, 0, 0, 1]);
+ assert_eq!(pages, [(126, 126), (64, 64)]);
+ assert!(pack(&[(200, 10)], 2, 128).is_err());
+ }
+
+ #[test]
+ fn trimming_finds_the_pixels_and_empty_pictures_keep_one_pixel() {
+ let mut p = Pixels::blank(16, 8, 8);
+ assert_eq!(p.trim(), Rect { x: 0, y: 0, w: 1, h: 1 });
+ if let Data::Rgba8(d) = &mut p.data {
+ [(3, 2), (9, 5), (5, 6)]
+ .iter()
+ .for_each(|&(x, y)| d[(y * 16 + x) * 4 + 3] = 255);
+ }
+ let trim = p.trim();
+ assert_eq!(trim, Rect { x: 3, y: 2, w: 7, h: 5 });
+ let cut = p.crop(trim);
+ assert_eq!((cut.width, cut.height), (7, 5));
+ assert_ne!(cut.hash(), p.hash());
+ assert_eq!(cut.crop(cut.trim()), cut);
+ }
+
+ #[test]
+ fn aseprite_json_lists_exposures_with_durations_and_tags_index_them() {
+ let trims = [
+ Rect {
+ x: 4,
+ y: 2,
+ w: 10,
+ h: 12,
+ },
+ Rect {
+ x: 0,
+ y: 0,
+ w: 32,
+ h: 32,
+ },
+ ];
+ let placed = [Placed { page: 0, x: 2, y: 2 }, Placed { page: 1, x: 2, y: 2 }];
+ let idle = Animation {
+ looping: false,
+ ..anim(0, 3, 10)
+ };
+ let anims = vec![
+ (
+ Animation {
+ name: "idle".into(),
+ ..idle
+ },
+ vec![
+ Run {
+ picture: 0,
+ frame: 0,
+ frames: 3,
+ ms: 300,
+ },
+ Run {
+ picture: 1,
+ frame: 3,
+ frames: 1,
+ ms: 100,
+ },
+ ],
+ ),
+ (
+ anim(4, 4, 10),
+ vec![Run {
+ picture: 0,
+ frame: 4,
+ frames: 1,
+ ms: 100,
+ }],
+ ),
+ ];
+ let images = ["ball.png".to_string(), "ball-2.png".to_string()];
+ let json = aseprite(&Sheet {
+ stem: "ball",
+ source: (32, 32),
+ trims: &trims,
+ placed: &placed,
+ pages: &[(16, 18), (36, 36)],
+ images: &images,
+ animations: &anims,
+ scale: 0.5,
+ depth: 8,
+ });
+ let frames = json["frames"].as_array().unwrap();
+ assert_eq!(frames.len(), 3);
+ assert_eq!(frames[0]["filename"], "idle 0");
+ assert_eq!(frames[0]["frame"], json!({"x": 2, "y": 2, "w": 10, "h": 12}));
+ assert_eq!(frames[0]["spriteSourceSize"], json!({"x": 4, "y": 2, "w": 10, "h": 12}));
+ assert_eq!(
+ (frames[0]["trimmed"].clone(), frames[1]["trimmed"].clone()),
+ (json!(true), json!(false))
+ );
+ assert_eq!(frames[1]["image"], "ball-2.png");
+ assert_eq!(frames.iter().map(|f| f["duration"].as_u64().unwrap()).sum::<u64>(), 500);
+ let tags = json["meta"]["frameTags"].as_array().unwrap();
+ assert_eq!(
+ tags[0],
+ json!({"name":"idle","from":0,"to":1,"direction":"forward","color":"#000000ff","repeat":"1"})
+ );
+ assert_eq!((tags[1]["from"].clone(), tags[1]["to"].clone()), (json!(2), json!(2)));
+ assert_eq!(json["meta"]["scale"], "0.5");
+ assert_eq!(json["meta"]["images"].as_array().unwrap().len(), 2);
+ }
+
+ #[test]
+ fn godot_text_has_atlas_frames_durations_and_an_offset_scene() {
+ let trims = [
+ Rect {
+ x: 4,
+ y: 2,
+ w: 10,
+ h: 12,
+ },
+ Rect {
+ x: 0,
+ y: 0,
+ w: 32,
+ h: 32,
+ },
+ ];
+ let placed = [Placed { page: 0, x: 2, y: 2 }, Placed { page: 0, x: 14, y: 2 }];
+ let anims = vec![(
+ Animation {
+ name: "say \"hi\"".into(),
+ looping: false,
+ ..anim(0, 3, 12)
+ },
+ vec![
+ Run {
+ picture: 0,
+ frame: 0,
+ frames: 3,
+ ms: 250,
+ },
+ Run {
+ picture: 1,
+ frame: 3,
+ frames: 1,
+ ms: 83,
+ },
+ ],
+ )];
+ let textures = [Texture {
+ path: "ball.png".into(),
+ uid: Some("uid://abc".into()),
+ }];
+ let tres = sprite_frames(&SpriteFrames {
+ uid: "uid://frames",
+ textures: &textures,
+ source: (32, 32),
+ trims: &trims,
+ placed: &placed,
+ animations: &anims,
+ });
+ assert!(tres.starts_with("[gd_resource type=\"SpriteFrames\" format=3 uid=\"uid://frames\"]\n"));
+ assert!(tres.contains("[ext_resource type=\"Texture2D\" uid=\"uid://abc\" path=\"ball.png\" id=\"1_sheet\"]"));
+ assert!(tres.contains("region = Rect2(2, 2, 10, 12)\nmargin = Rect2(4, 2, 22, 20)\n"));
+ assert!(!tres.contains("margin = Rect2(0, 0, 0, 0)"));
+ assert!(tres.contains("\"duration\": 3.0,\n\"texture\": SubResource(\"AtlasTexture_0\")"));
+ assert!(tres.contains("\"loop\": false,\n\"name\": &\"say \\\"hi\\\"\",\n\"speed\": 12.0\n}]"));
+ assert_eq!(header_uid(&tres).as_deref(), Some("uid://frames"));
+ let tscn = scene(&Scene {
+ uid: "uid://scene",
+ node: &node_name("ball.v2"),
+ frames_path: "ball.tres",
+ frames_uid: "uid://frames",
+ animation: "idle",
+ origin: [16.0, 30.5],
+ });
+ assert!(tscn.contains("[node name=\"ball_v2\" type=\"AnimatedSprite2D\"]"));
+ assert!(tscn.contains("offset = Vector2(-16, -30.5)\n"));
+ assert_eq!(header_uid(&tscn).as_deref(), Some("uid://scene"));
+ let import = "[remap]\n\nimporter=\"texture\"\ntype=\"CompressedTexture2D\"\nuid=\"uid://c6xh0mqe8vbs6\"\n";
+ assert_eq!(import_uid(import).as_deref(), Some("uid://c6xh0mqe8vbs6"));
+ }
+
+ #[test]
+ fn uids_use_godots_alphabet_and_differ_by_path() {
+ let a = uid_for("/game/art/ball.tres");
+ let b = uid_for("/game/art/ball.tscn");
+ assert_ne!(a, b);
+ assert_eq!(a, uid_for("/game/art/ball.tres"));
+ assert!(a.starts_with("uid://"));
+ assert!(a[6..].chars().all(|c| matches!(c, 'a'..='y' | '0'..='8')), "{a}");
+ assert_eq!(uid_text(0), "uid://a");
+ assert_eq!(uid_text(34), "uid://ba");
+ assert_eq!(uid_text(33), "uid://8");
+ }
+}
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
new file mode 100644
index 0000000..2662668
--- /dev/null
+++ b/crates/render/src/text.rs
@@ -0,0 +1,120 @@
+use crate::assets;
+use anyhow::{Result, anyhow};
+use klad_core::generators::{Align, Text};
+use skia_safe::{Path, PathBuilder, Point};
+use skrifa::instance::{LocationRef, Size};
+use skrifa::outline::{DrawSettings, OutlinePen};
+use skrifa::raw::TableProvider;
+use skrifa::raw::tables::kern::SubtableKind;
+use skrifa::{FontRef, GlyphId, MetadataProvider};
+
+struct Outline<'a> {
+ path: &'a mut PathBuilder,
+ x: f32,
+ y: f32,
+ scale: f32,
+}
+
+impl Outline<'_> {
+ fn at(&self, x: f32, y: f32) -> Point {
+ Point::new(self.x + x * self.scale, self.y - y * self.scale)
+ }
+}
+
+impl OutlinePen for Outline<'_> {
+ fn move_to(&mut self, x: f32, y: f32) {
+ let p = self.at(x, y);
+ self.path.move_to(p);
+ }
+
+ fn line_to(&mut self, x: f32, y: f32) {
+ let p = self.at(x, y);
+ self.path.line_to(p);
+ }
+
+ fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
+ let (a, b) = (self.at(x1, y1), self.at(x, y));
+ self.path.quad_to(a, b);
+ }
+
+ fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
+ let (a, b, c) = (self.at(x1, y1), self.at(x2, y2), self.at(x, y));
+ self.path.cubic_to(a, b, c);
+ }
+
+ fn close(&mut self) {
+ self.path.close();
+ }
+}
+
+pub fn parse(bytes: &[u8]) -> Result<FontRef<'_>> {
+ FontRef::from_index(bytes, 0).map_err(|e| anyhow!("{e}"))
+}
+
+fn kerning(font: &FontRef, left: GlyphId, right: GlyphId) -> f32 {
+ font.kern()
+ .ok()
+ .and_then(|table| {
+ table
+ .subtables()
+ .filter_map(|s| s.ok())
+ .filter(|s| s.is_horizontal() && !s.is_variable())
+ .find_map(|s| match s.kind().ok()? {
+ SubtableKind::Format0(t) => t.kerning(left, right),
+ SubtableKind::Format2(t) => t.kerning(left, right),
+ SubtableKind::Format3(t) => t.kerning(left, right),
+ SubtableKind::Format1(_) => None,
+ })
+ })
+ .unwrap_or(0) as f32
+}
+
+pub fn text_path(t: &Text) -> Result<Path> {
+ let bytes = assets::font(&t.font)?;
+ let font = parse(&bytes).map_err(|e| anyhow!("the font {} cannot be read: {e}", t.font))?;
+ let metrics = font.metrics(Size::unscaled(), LocationRef::default());
+ let advances = font.glyph_metrics(Size::unscaled(), LocationRef::default());
+ let charmap = font.charmap();
+ let outlines = font.outline_glyphs();
+ let scale = t.size / metrics.units_per_em as f32;
+ let ascent = metrics.ascent * scale;
+ let mut path = PathBuilder::new();
+ t.text.split('\n').enumerate().for_each(|(row, line)| {
+ let glyphs: Vec<GlyphId> = line
+ .chars()
+ .map(|c| charmap.map(c).unwrap_or(GlyphId::NOTDEF))
+ .collect();
+ let steps: Vec<f32> = glyphs
+ .iter()
+ .enumerate()
+ .map(|(i, g)| {
+ let advance = advances.advance_width(*g).unwrap_or(0.0);
+ let kern = glyphs.get(i + 1).map_or(0.0, |next| kerning(&font, *g, *next));
+ (advance + kern) * scale + if i + 1 < glyphs.len() { t.tracking } else { 0.0 }
+ })
+ .collect();
+ let width: f32 = steps.iter().sum();
+ let left = match t.align {
+ Align::Left => t.x,
+ Align::Center => t.x - width / 2.0,
+ Align::Right => t.x - width,
+ };
+ let baseline = t.y + ascent + row as f32 * t.size * t.leading;
+ glyphs.iter().zip(&steps).fold(left, |pen, (g, step)| {
+ let mut outline = Outline {
+ path: &mut path,
+ x: pen,
+ y: baseline,
+ scale,
+ };
+ if let Some(glyph) = outlines.get(*g) {
+ let _ = glyph.draw(
+ DrawSettings::unhinted(Size::unscaled(), LocationRef::default()),
+ &mut outline,
+ );
+ }
+ pen + step
+ });
+ });
+ Ok(path.detach())
+}
diff --git a/crates/render/src/vector.rs b/crates/render/src/vector.rs
new file mode 100644
index 0000000..d51fb40
--- /dev/null
+++ b/crates/render/src/vector.rs
@@ -0,0 +1,712 @@
+use anyhow::{Context, Result, anyhow};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Cap, Join, Node, Paint, Shape, StrokeStyle, Transform};
+use klad_core::look::Rays;
+use skia_safe::gradient::{Colors, Gradient, Interpolation, shaders};
+use skia_safe::{
+ Canvas, Color4f, ColorSpace, Data, FilterMode, IRect, Matrix, MipmapMode, PaintCap, PaintJoin, PaintStyle, Path,
+ PathEffect, RRect, Rect, SamplingOptions, TileMode, canvas::SaveLayerRec, image_filters, images,
+};
+
+use rayon::prelude::*;
+
+const SHARP_SIGMA: f32 = 6.0;
+const MAX_FACTOR: i32 = 32;
+
+fn color(hex: &str) -> Result<Color4f> {
+ let [r, g, b, a] = parse_hex(hex)?;
+ Ok(Color4f::new(r, g, b, a))
+}
+
+pub(crate) fn shader_paint(paint: &Paint) -> Result<Option<skia_safe::Paint>> {
+ let mut out = skia_safe::Paint::default();
+ out.set_anti_alias(true);
+ match paint {
+ Paint::Solid(hex) if hex == "none" => return Ok(None),
+ Paint::Solid(hex) => {
+ out.set_color4f(color(hex)?, &ColorSpace::new_srgb());
+ }
+ Paint::Linear { linear } => {
+ let (colors, stops) = stops(&linear.stops)?;
+ let gradient = Gradient::new(
+ Colors::new(&colors, Some(&stops), TileMode::Clamp, ColorSpace::new_srgb()),
+ Interpolation::default(),
+ );
+ let shader = shaders::linear_gradient(
+ ((linear.from[0], linear.from[1]), (linear.to[0], linear.to[1])),
+ &gradient,
+ None,
+ )
+ .ok_or_else(|| {
+ anyhow!(
+ "cannot build a linear gradient from {:?} to {:?}",
+ linear.from,
+ linear.to
+ )
+ })?;
+ out.set_shader(shader);
+ }
+ Paint::Radial { radial } => {
+ let (colors, stops) = stops(&radial.stops)?;
+ let gradient = Gradient::new(
+ Colors::new(&colors, Some(&stops), TileMode::Clamp, ColorSpace::new_srgb()),
+ Interpolation::default(),
+ );
+ let shader =
+ shaders::radial_gradient(((radial.center[0], radial.center[1]), radial.radius), &gradient, None)
+ .ok_or_else(|| anyhow!("cannot build a radial gradient of radius {}", radial.radius))?;
+ out.set_shader(shader);
+ }
+ }
+ Ok(Some(out))
+}
+
+fn stops(stops: &[klad_core::doc::Stop]) -> Result<(Vec<Color4f>, Vec<f32>)> {
+ let colors = stops.iter().map(|s| color(&s.1)).collect::<Result<Vec<_>>>()?;
+ Ok((colors, stops.iter().map(|s| s.0).collect()))
+}
+
+fn stroke_paint(stroke: &StrokeStyle) -> Result<Option<skia_safe::Paint>> {
+ let Some(mut paint) = shader_paint(&stroke.paint)? else {
+ return Ok(None);
+ };
+ paint.set_style(PaintStyle::Stroke);
+ paint.set_stroke_width(stroke.width);
+ paint.set_stroke_cap(match stroke.cap {
+ Cap::Butt => PaintCap::Butt,
+ Cap::Round => PaintCap::Round,
+ Cap::Square => PaintCap::Square,
+ });
+ paint.set_stroke_join(match stroke.join {
+ Join::Miter => PaintJoin::Miter,
+ Join::Round => PaintJoin::Round,
+ Join::Bevel => PaintJoin::Bevel,
+ });
+ if !stroke.dash.is_empty() {
+ let intervals: Vec<f32> = if stroke.dash.len() % 2 == 1 {
+ stroke.dash.iter().chain(&stroke.dash).copied().collect()
+ } else {
+ stroke.dash.clone()
+ };
+ paint.set_path_effect(PathEffect::dash(&intervals, 0.0));
+ }
+ Ok(Some(paint))
+}
+
+pub fn shape_path(shape: &Shape) -> Result<Option<Path>> {
+ Ok(match shape {
+ Shape::Rect { x, y, w, h, radius } => {
+ let rect = Rect::from_xywh(*x, *y, *w, *h);
+ Some(if *radius > 0.0 {
+ Path::rrect(RRect::new_rect_xy(rect, *radius, *radius), None)
+ } else {
+ Path::rect(rect, None)
+ })
+ }
+ Shape::Ellipse { cx, cy, rx, ry } => {
+ Some(Path::oval(Rect::from_ltrb(cx - rx, cy - ry, cx + rx, cy + ry), None))
+ }
+ Shape::Path { d } => Some(Path::from_svg(d).ok_or_else(|| anyhow!("bad path data {d:?}"))?),
+ Shape::Group { .. } | Shape::Scatter(_) | Shape::Repeat(_) | Shape::Mirror(_) => None,
+ Shape::Image(p) => Some(Path::rect(Rect::from_xywh(p.x, p.y, p.w, p.h), None)),
+ Shape::Text(t) => Some(crate::text::text_path(t)?),
+ Shape::Rays(rays) => {
+ let mut builder = skia_safe::PathBuilder::new();
+ rays.beams().iter().for_each(|beam| {
+ builder.add_polygon(&beam.quad.map(|p| skia_safe::Point::new(p[0], p[1])), true);
+ });
+ Some(builder.detach())
+ }
+ })
+}
+
+const RAY_STOPS: usize = 12;
+
+fn draw_rays(canvas: &Canvas, node: &Node, rays: &Rays) -> Result<()> {
+ let c = match &node.fill {
+ Some(Paint::Solid(hex)) if hex != "none" => parse_hex(hex)?,
+ _ => [1.0, 0.97, 0.86, 1.0],
+ };
+ let falloff = rays.falloff.max(0.05);
+ let stops: Vec<f32> = (0..=RAY_STOPS).map(|i| i as f32 / RAY_STOPS as f32).collect();
+ rays.beams().iter().try_for_each(|beam| {
+ let colors: Vec<Color4f> = stops
+ .iter()
+ .map(|t| Color4f::new(c[0], c[1], c[2], c[3] * beam.strength * libm::powf(1.0 - t, falloff)))
+ .collect();
+ let gradient = Gradient::new(
+ Colors::new(&colors, Some(&stops), TileMode::Clamp, ColorSpace::new_srgb()),
+ Interpolation::default(),
+ );
+ let shader = shaders::radial_gradient(((rays.x, rays.y), beam.length.max(1.0)), &gradient, None)
+ .ok_or_else(|| anyhow!("cannot shade a ray of length {}", beam.length))?;
+ let mut paint = skia_safe::Paint::default();
+ paint.set_anti_alias(true);
+ paint.set_shader(shader);
+ let path = Path::polygon(&beam.quad.map(|p| skia_safe::Point::new(p[0], p[1])), true, None, None);
+ canvas.draw_path(&path, &paint);
+ Ok(())
+ })
+}
+
+fn union(a: Option<Rect>, b: Option<Rect>) -> Option<Rect> {
+ match (a, b) {
+ (Some(a), Some(b)) => Some(Rect::from_ltrb(
+ a.left.min(b.left),
+ a.top.min(b.top),
+ a.right.max(b.right),
+ a.bottom.max(b.bottom),
+ )),
+ (a, b) => a.or(b),
+ }
+}
+
+pub fn local_bounds(node: &Node) -> Result<Option<Rect>> {
+ let own = shape_bounds(node)?;
+ match &node.clip {
+ Some(clip) => {
+ let Some(path) = Path::from_svg(clip) else {
+ return Err(anyhow!("bad clip path {clip:?}"));
+ };
+ let c = path.compute_tight_bounds();
+ Ok(own.and_then(|r| {
+ let mut r = r;
+ r.intersect(c).then_some(r)
+ }))
+ }
+ None => Ok(own),
+ }
+}
+
+pub fn instances(shape: &Shape) -> Vec<Matrix> {
+ let list = match shape {
+ Shape::Scatter(s) => s.instances(),
+ Shape::Repeat(r) => r.instances(),
+ Shape::Mirror(m) => m.instances(),
+ _ => vec![klad_core::generators::IDENTITY],
+ };
+ list.iter()
+ .map(|a| Matrix::new_all(a[0], a[2], a[4], a[1], a[3], a[5], 0.0, 0.0, 1.0))
+ .collect()
+}
+
+fn shape_bounds(node: &Node) -> Result<Option<Rect>> {
+ match &node.shape {
+ shape if shape.generates() || matches!(shape, Shape::Group { .. }) => {
+ instances(shape).iter().try_fold(None, |acc, m| {
+ shape
+ .children()
+ .iter()
+ .try_fold(acc, |acc, child| Ok(union(acc, node_bounds(child, m)?)))
+ })
+ }
+ shape => Ok(shape_path(shape)?.map(|p| {
+ let rect = p.compute_tight_bounds();
+ let pad = node.stroke.as_ref().map_or(0.0, |s| s.width / 2.0) + node.blur * 2.0;
+ rect.with_outset((pad, pad))
+ })),
+ }
+}
+
+pub fn node_matrix(node: &Node) -> Result<Matrix> {
+ let Transform {
+ x,
+ y,
+ rotate,
+ sx,
+ sy,
+ pivot,
+ } = node.transform;
+ if node.transform.is_identity() {
+ return Ok(Matrix::new_identity());
+ }
+ let [px, py] = match pivot {
+ Some(p) => p,
+ None => local_bounds(node)?.map_or([0.0, 0.0], |r| [r.center_x(), r.center_y()]),
+ };
+ let mut m = Matrix::translate((x + px, y + py));
+ m.pre_rotate(rotate, None);
+ m.pre_scale((sx, sy), None);
+ m.pre_translate((-px, -py));
+ Ok(m)
+}
+
+pub fn node_bounds(node: &Node, parent: &Matrix) -> Result<Option<Rect>> {
+ let matrix = Matrix::concat(parent, &node_matrix(node)?);
+ Ok(local_bounds(node)?.map(|r| matrix.map_rect(r).0))
+}
+
+pub fn nodes_bounds(nodes: &[Node]) -> Result<Option<Rect>> {
+ nodes
+ .iter()
+ .filter(|n| n.visible)
+ .try_fold(None, |acc, n| Ok(union(acc, node_bounds(n, &Matrix::new_identity())?)))
+}
+
+pub fn draw_nodes(canvas: &Canvas, nodes: &[Node]) -> Result<()> {
+ nodes
+ .iter()
+ .filter(|n| n.visible)
+ .try_for_each(|n| draw_node(canvas, n))
+}
+
+fn draw_node(canvas: &Canvas, node: &Node) -> Result<()> {
+ let context = || format!("node {}", node.id);
+ let matrix = node_matrix(node).with_context(context)?;
+ let depth = canvas.save();
+ canvas.concat(&matrix);
+ let bounds = local_bounds(node)
+ .with_context(context)?
+ .map(|r| r.with_outset((node.blur * 3.0 + 1.0, node.blur * 3.0 + 1.0)));
+ let drawn = match bounds.and_then(|b| downsampling(canvas, node, b)) {
+ Some(plan) => draw_downsampled(canvas, node, bounds, plan),
+ None => {
+ if node.blur > 0.0 || node.opacity < 1.0 {
+ blurred_layer(canvas, node, bounds, node.opacity);
+ }
+ draw_content(canvas, node)
+ }
+ };
+ canvas.restore_to_count(depth);
+ drawn.with_context(context)
+}
+
+fn blurred_layer(canvas: &Canvas, node: &Node, bounds: Option<Rect>, opacity: f32) {
+ let mut paint = skia_safe::Paint::default();
+ paint.set_alpha_f(opacity);
+ if node.blur > 0.0 {
+ paint.set_image_filter(image_filters::blur((node.blur, node.blur), TileMode::Decal, None, None));
+ }
+ let rec = SaveLayerRec::default().paint(&paint);
+ match &bounds {
+ Some(b) => canvas.save_layer(&rec.bounds(b)),
+ None => canvas.save_layer(&rec),
+ };
+}
+
+fn draw_content(canvas: &Canvas, node: &Node) -> Result<()> {
+ if let Some(clip) = &node.clip {
+ let path = Path::from_svg(clip).ok_or_else(|| anyhow!("bad clip path {clip:?}"))?;
+ canvas.clip_path(&path, skia_safe::ClipOp::Intersect, true);
+ }
+ match &node.shape {
+ Shape::Group { children } => draw_nodes(canvas, children),
+ Shape::Rays(rays) => draw_rays(canvas, node, rays),
+ Shape::Image(p) => {
+ let image = crate::assets::image(&p.src)?;
+ canvas.draw_image_rect_with_sampling_options(
+ &image,
+ None,
+ Rect::from_xywh(p.x, p.y, p.w, p.h),
+ SamplingOptions::new(FilterMode::Linear, MipmapMode::Linear),
+ &skia_safe::Paint::default(),
+ );
+ Ok(())
+ }
+ shape if shape.generates() => instances(shape).iter().try_for_each(|m| {
+ let depth = canvas.save();
+ canvas.concat(m);
+ let drawn = draw_nodes(canvas, shape.children());
+ canvas.restore_to_count(depth);
+ drawn
+ }),
+ shape => {
+ let Some(path) = shape_path(shape)? else {
+ return Ok(());
+ };
+ let fill = node.fill.clone().unwrap_or(Paint::Solid("#000000".into()));
+ if let Some(paint) = shader_paint(&fill)? {
+ canvas.draw_path(&path, &paint);
+ }
+ if let Some(paint) = node.stroke.as_ref().map(stroke_paint).transpose()?.flatten() {
+ canvas.draw_path(&path, &paint);
+ }
+ Ok(())
+ }
+ }
+}
+
+struct Downsample {
+ area: IRect,
+ factor: i32,
+ reach: f32,
+}
+
+fn downsampling(canvas: &Canvas, node: &Node, bounds: Rect) -> Option<Downsample> {
+ let ctm = canvas.local_to_device_as_3x3();
+ let (low, high) = (ctm.min_scale(), ctm.max_scale());
+ if node.blur <= 0.0 || ctm.has_perspective() || low <= 0.0 || high > low * 1.001 {
+ return None;
+ }
+ let reach = node.blur * high;
+ let ratio = (reach / SHARP_SIGMA) as u32;
+ if ratio < 2 {
+ return None;
+ }
+ let factor = (1i32 << ratio.ilog2()).min(MAX_FACTOR);
+ let spread = (reach * 3.0).ceil() as i32 + factor;
+ let clip = canvas.device_clip_bounds()?.with_outset((spread, spread));
+ let (mapped, _) = ctm.map_rect(bounds);
+ let snap_down = |v: f32| (v.floor() as i32).div_euclid(factor) * factor;
+ let snap_up = |v: f32| -(((-v).floor() as i32).div_euclid(factor) * factor);
+ let area = IRect::from_ltrb(
+ snap_down(mapped.left).max(snap_down(clip.left as f32)),
+ snap_down(mapped.top).max(snap_down(clip.top as f32)),
+ snap_up(mapped.right).min(snap_up(clip.right as f32)),
+ snap_up(mapped.bottom).min(snap_up(clip.bottom as f32)),
+ );
+ (!area.is_empty()).then_some(Downsample { area, factor, reach })
+}
+
+fn draw_downsampled(canvas: &Canvas, node: &Node, bounds: Option<Rect>, plan: Downsample) -> Result<()> {
+ let Downsample { area, factor, reach } = plan;
+ let (width, height) = ((area.width() / factor) as usize, (area.height() / factor) as usize);
+ let info = crate::f16_info(width as u32, height as u32);
+ let Some(mut surface) = canvas.new_surface(&info, None) else {
+ blurred_layer(canvas, node, bounds, node.opacity);
+ return draw_content(canvas, node);
+ };
+ let small = surface.canvas();
+ small.clear(Color4f::new(0.0, 0.0, 0.0, 0.0));
+ let scale = 1.0 / factor as f32;
+ small.scale((scale, scale));
+ small.translate((-area.left as f32, -area.top as f32));
+ small.concat(&canvas.local_to_device_as_3x3());
+ draw_content(small, node)?;
+ let mut pixels = vec![half::f16::ZERO; width * height * 4];
+ if !surface.read_pixels(&info, bytemuck::cast_slice_mut(&mut pixels), width * 8, (0, 0)) {
+ return Err(anyhow!("cannot read the downsampled layer"));
+ }
+ let k = factor as f32;
+ let sigma = (reach * reach - k * k / 4.0).max(1.0).sqrt() / k;
+ let blurred = gaussian_blur(
+ &pixels.iter().map(|v| v.to_f32()).collect::<Vec<_>>(),
+ width,
+ height,
+ sigma,
+ );
+ let packed: Vec<half::f16> = blurred.iter().map(|v| half::f16::from_f32(*v)).collect();
+ let image = images::raster_from_data(&info, Data::new_copy(bytemuck::cast_slice(&packed)), width * 8)
+ .ok_or_else(|| anyhow!("cannot wrap the blurred layer"))?;
+ let placement = Matrix::translate((area.left as f32, area.top as f32)) * Matrix::scale((k, k));
+ let shader = image
+ .to_shader(
+ (TileMode::Decal, TileMode::Decal),
+ SamplingOptions::new(FilterMode::Linear, MipmapMode::None),
+ &placement,
+ )
+ .ok_or_else(|| anyhow!("cannot sample the blurred layer"))?;
+ let mut paint = skia_safe::Paint::default();
+ paint.set_shader(shader);
+ paint.set_alpha_f(node.opacity);
+ canvas.save();
+ canvas.reset_matrix();
+ canvas.draw_rect(Rect::from(area), &paint);
+ canvas.restore();
+ Ok(())
+}
+
+fn gaussian_blur(pixels: &[f32], width: usize, height: usize, sigma: f32) -> Vec<f32> {
+ let radius = (sigma * 3.0).ceil() as isize;
+ let weights: Vec<f32> = (-radius..=radius)
+ .map(|i| libm::expf(-((i * i) as f32) / (2.0 * sigma * sigma)))
+ .collect();
+ let total: f32 = weights.iter().sum();
+ let kernel: Vec<f32> = weights.iter().map(|w| w / total).collect();
+ let (quads, _) = pixels.as_chunks::<4>();
+ let rows = blur_rows_transposed(quads, width, &kernel);
+ blur_rows_transposed(&rows, height, &kernel)
+ .into_iter()
+ .flatten()
+ .collect()
+}
+
+fn blur_rows_transposed(src: &[[f32; 4]], width: usize, kernel: &[f32]) -> Vec<[f32; 4]> {
+ let reach = kernel.len() / 2;
+ let rows: Vec<Vec<[f32; 4]>> = src
+ .par_chunks_exact(width)
+ .map(|row| {
+ (0..width)
+ .map(|x| {
+ let lo = x.saturating_sub(reach);
+ let hi = (x + reach).min(width - 1);
+ let taps = &kernel[lo + reach - x..=hi + reach - x];
+ row[lo..=hi].iter().zip(taps).fold([0.0f32; 4], |a, (p, w)| {
+ [a[0] + p[0] * w, a[1] + p[1] * w, a[2] + p[2] * w, a[3] + p[3] * w]
+ })
+ })
+ .collect()
+ })
+ .collect();
+ (0..width).flat_map(|x| rows.iter().map(move |row| row[x])).collect()
+}
+
+pub fn pivot_pins(doc: &klad_core::doc::Document, id: &str) -> Result<Vec<klad_core::ops::Op>> {
+ let Some(klad_core::doc::Loc::Node(layer, cel, path)) = doc.locate(id) else {
+ return Ok(Vec::new());
+ };
+ let mut list: &[Node] = &doc.layer_at(&layer).cels()[cel].nodes;
+ let mut out = Vec::new();
+ for &i in &path {
+ let node = &list[i];
+ if !node.transform.is_identity()
+ && node.transform.pivot.is_none()
+ && let Some(r) = local_bounds(node)?
+ {
+ out.push(klad_core::ops::Op::Set {
+ id: node.id.clone(),
+ props: serde_json::Map::from_iter([(
+ "transform.pivot".to_string(),
+ serde_json::json!([r.center_x(), r.center_y()]),
+ )]),
+ });
+ }
+ list = node.children();
+ }
+ Ok(out)
+}
+
+pub fn pinned(doc: &klad_core::doc::Document, ops: &[klad_core::ops::Op]) -> Result<Vec<klad_core::ops::Op>> {
+ ops.iter().try_fold(Vec::new(), |mut out, op| {
+ if let klad_core::ops::Op::Path { id, .. } = op {
+ out.extend(pivot_pins(doc, id)?);
+ }
+ out.push(op.clone());
+ Ok(out)
+ })
+}
+
+pub fn to_box(rect: Rect) -> [f32; 4] {
+ [rect.left, rect.top, rect.width(), rect.height()]
+}
+
+pub fn node_box(node: &Node) -> Result<Option<[f32; 4]>> {
+ Ok(node_bounds(node, &Matrix::new_identity())?.map(to_box))
+}
+
+pub fn nodes_box(nodes: &[Node]) -> Result<Option<[f32; 4]>> {
+ Ok(nodes_bounds(nodes)?.map(to_box))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use skia_safe::surfaces;
+
+ fn pixels(surface: &mut skia_safe::Surface) -> Vec<f32> {
+ let info = surface.image_info();
+ let mut out = vec![half::f16::ZERO; (info.width() * info.height() * 4) as usize];
+ assert!(surface.read_pixels(
+ &info,
+ bytemuck::cast_slice_mut(&mut out),
+ info.width() as usize * 8,
+ (0, 0)
+ ));
+ out.iter().map(|v| v.to_f32()).collect()
+ }
+
+ fn render(nodes: &[Node], size: i32, origin: (f32, f32)) -> Vec<f32> {
+ let mut surface = surfaces::raster(&crate::f16_info(size as u32, size as u32), None, None).unwrap();
+ surface.canvas().translate((-origin.0, -origin.1));
+ draw_nodes(surface.canvas(), nodes).unwrap();
+ pixels(&mut surface)
+ }
+
+ fn exact(node: &Node, size: i32) -> Vec<f32> {
+ let info = crate::f16_info(size as u32, size as u32);
+ let mut layer = surfaces::raster(&info, None, None).unwrap();
+ let canvas = layer.canvas();
+ canvas.concat(&node_matrix(node).unwrap());
+ let reach = node.blur * canvas.local_to_device_as_3x3().max_scale();
+ draw_content(canvas, node).unwrap();
+ let blurred = gaussian_blur(&pixels(&mut layer), size as usize, size as usize, reach);
+ blurred
+ .iter()
+ .map(|v| half::f16::from_f32(v * node.opacity).to_f32())
+ .collect()
+ }
+
+ fn skia(node: &Node, size: i32) -> Vec<f32> {
+ let mut surface = surfaces::raster(&crate::f16_info(size as u32, size as u32), None, None).unwrap();
+ let canvas = surface.canvas();
+ canvas.concat(&node_matrix(node).unwrap());
+ let bounds = local_bounds(node)
+ .unwrap()
+ .map(|r| r.with_outset((node.blur * 3.0 + 1.0, node.blur * 3.0 + 1.0)));
+ blurred_layer(canvas, node, bounds, node.opacity);
+ draw_content(canvas, node).unwrap();
+ canvas.restore_to_count(1);
+ pixels(&mut surface)
+ }
+
+ fn mist() -> Vec<Node> {
+ let mut band = Node::new(
+ "band",
+ Shape::Ellipse {
+ cx: 256.0,
+ cy: 250.0,
+ rx: 220.0,
+ ry: 40.0,
+ },
+ );
+ band.fill = Some(Paint::Solid("#c8d4e6".into()));
+ band.blur = 42.0;
+ band.opacity = 0.8;
+ let mut tilted = Node::new(
+ "tilted",
+ Shape::Rect {
+ x: 150.0,
+ y: 120.0,
+ w: 200.0,
+ h: 60.0,
+ radius: 0.0,
+ },
+ );
+ tilted.fill = Some(Paint::Solid("#40306a".into()));
+ tilted.blur = 12.0;
+ tilted.transform.rotate = 25.0;
+ tilted.transform.sx = 1.5;
+ tilted.transform.sy = 1.5;
+ vec![band, tilted]
+ }
+
+ fn worst(a: &[f32], b: &[f32]) -> (usize, f32) {
+ a.iter()
+ .zip(b)
+ .map(|(x, y)| (x - y).abs())
+ .enumerate()
+ .fold((0, 0.0f32), |acc, (i, d)| if d > acc.1 { (i, d) } else { acc })
+ }
+
+ fn erf(x: f64) -> f64 {
+ let t = 1.0 / (1.0 + 0.5 * x.abs());
+ let poly = -1.26551223
+ + t * (1.00002368
+ + t * (0.37409196
+ + t * (0.09678418
+ + t * (-0.18628806
+ + t * (0.27886807
+ + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))));
+ let y = 1.0 - t * (-x * x + poly).exp();
+ if x >= 0.0 { y } else { -y }
+ }
+
+ #[test]
+ fn path_edits_pin_the_pivots_that_would_move() {
+ use klad_core::doc::{Document, Layer};
+ use klad_core::ops::{apply_all, parse_lines};
+ let mut doc = Document::new(400, 400);
+ doc.layers.push(Layer::vector("v", "v", "c1", Vec::new()));
+ let (doc, _) = apply_all(
+ &doc,
+ &parse_lines(
+ r#"{"op":"add","node":{"id":"g","type":"group","transform":{"rotate":30},"children":[{"id":"p","type":"path","d":"M100 100 L200 100 L150 200 Z","transform":{"sx":2}}]},"in":"v"}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let before = crate::overlay::node_world_box(&doc, "p").unwrap().unwrap();
+ let edit = parse_lines(r#"{"op":"path","id":"p","move":2,"to":[150,300]}"#).unwrap();
+ let ops = pinned(&doc, &edit).unwrap();
+ assert_eq!(ops.len(), 3);
+ let (moved, _) = apply_all(&doc, &ops).unwrap();
+ let (unpinned, _) = apply_all(&doc, &edit).unwrap();
+ let top = |d: &klad_core::doc::Document| crate::overlay::node_world_box(d, "p").unwrap().unwrap()[1];
+ assert!((top(&moved) - before[1]).abs() > 1.0 || (top(&unpinned) - before[1]).abs() > 1.0);
+ let corner = |d: &klad_core::doc::Document| {
+ let (node, parent) = crate::overlay::node_world(d, "p").unwrap().unwrap();
+ Matrix::concat(&parent, &node_matrix(node).unwrap()).map_point((100.0, 100.0))
+ };
+ let (a, b) = (corner(&doc), corner(&moved));
+ assert!((a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01, "{a:?} {b:?}");
+ let drifted = corner(&unpinned);
+ assert!((a.x - drifted.x).abs() + (a.y - drifted.y).abs() > 1.0);
+ }
+
+ #[test]
+ fn big_blurs_match_an_exact_gaussian() {
+ mist().into_iter().for_each(|node| {
+ let truth = exact(&node, 512);
+ let fast = render(std::slice::from_ref(&node), 512, (0.0, 0.0));
+ let (at, error) = worst(&truth, &fast);
+ assert!(
+ error < 1.5 / 255.0,
+ "{} off by {:.2}/255 at ({}, {})",
+ node.id,
+ error * 255.0,
+ at / 4 % 512,
+ at / 4 / 512
+ );
+ });
+ }
+
+ #[test]
+ fn big_blurs_follow_the_exact_edge_profile_closer_than_skia() {
+ [12.0f32, 20.0, 30.0, 45.0].iter().for_each(|&sigma| {
+ let mut wall = Node::new(
+ "wall",
+ Shape::Rect {
+ x: 100.0,
+ y: -2000.0,
+ w: 312.0,
+ h: 5000.0,
+ radius: 0.0,
+ },
+ );
+ wall.fill = Some(Paint::Solid("#ffffff".into()));
+ wall.blur = sigma;
+ let spread = sigma as f64 * std::f64::consts::SQRT_2;
+ let score = |v: &[f32]| {
+ (0..512usize)
+ .map(|x| {
+ let c = x as f64 + 0.5;
+ let truth = 0.5 * (erf((c - 100.0) / spread) - erf((c - 412.0) / spread));
+ (v[(256 * 512 + x) * 4 + 3] as f64 - truth).abs() * 255.0
+ })
+ .fold(0.0f64, f64::max)
+ };
+ let fast = score(&render(std::slice::from_ref(&wall), 512, (0.0, 0.0)));
+ let reference = score(&skia(&wall, 512));
+ assert!(
+ fast < 1.0 && fast < reference,
+ "sigma {sigma}: {fast:.2}/255 off, Skia {reference:.2}/255"
+ );
+ });
+ }
+
+ #[test]
+ fn stretched_blurs_keep_the_skia_path() {
+ let mut node = mist().remove(1);
+ node.transform.sy = 0.6;
+ let mut surface = surfaces::raster(&crate::f16_info(64, 64), None, None).unwrap();
+ surface.canvas().concat(&node_matrix(&node).unwrap());
+ assert!(downsampling(surface.canvas(), &node, Rect::from_xywh(0.0, 0.0, 10.0, 10.0)).is_none());
+ let fast = render(std::slice::from_ref(&node), 512, (0.0, 0.0));
+ assert_eq!(worst(&fast, &skia(&node, 512)).1, 0.0);
+ }
+
+ #[test]
+ fn big_blurs_line_up_across_tiles() {
+ let nodes = mist();
+ let whole = render(&nodes, 512, (0.0, 0.0));
+ [(0usize, 0usize), (256, 0), (0, 256), (256, 256)]
+ .iter()
+ .for_each(|&(ox, oy)| {
+ let tile = render(&nodes, 256, (ox as f32, oy as f32));
+ let crop: Vec<f32> = (0..256usize)
+ .flat_map(|y| {
+ let start = ((y + oy) * 512 + ox) * 4;
+ whole[start..start + 256 * 4].to_vec()
+ })
+ .collect();
+ let (at, error) = worst(&tile, &crop);
+ assert!(
+ error < 1.0 / 255.0,
+ "tile at ({ox},{oy}) off by {:.2}/255 at ({}, {})",
+ error * 255.0,
+ at / 4 % 256,
+ at / 4 / 256
+ );
+ });
+ }
+}
diff --git a/deny.toml b/deny.toml
new file mode 100644
index 0000000..ae5d41f
--- /dev/null
+++ b/deny.toml
@@ -0,0 +1,50 @@
+[graph]
+targets = [
+ "aarch64-apple-darwin",
+ "x86_64-apple-darwin",
+ "x86_64-unknown-linux-gnu",
+ "aarch64-unknown-linux-gnu",
+ "x86_64-pc-windows-msvc",
+]
+all-features = false
+
+[advisories]
+unmaintained = "all"
+yanked = "deny"
+ignore = [
+ { id = "RUSTSEC-2026-0370", reason = "zvariant: Linux accessibility through eframe (accesskit_unix); waits on eframe moving to zbus 6" },
+ { id = "RUSTSEC-2026-0371", reason = "zbus_names: as zvariant" },
+ { id = "RUSTSEC-2026-0372", reason = "zvariant_derive: as zvariant" },
+ { crate = "[email protected]", reason = "yanked; reached only through accesskit_unix and zbus 5 on Linux, waits on eframe" },
+]
+
+[licenses]
+allow = [
+ "MIT",
+ "Apache-2.0",
+ "Apache-2.0 WITH LLVM-exception",
+ "BSD-2-Clause",
+ "BSD-3-Clause",
+ "ISC",
+ "Zlib",
+ "BSL-1.0",
+ "Unicode-3.0",
+ "CC0-1.0",
+ "0BSD",
+ "Unlicense",
+ "OFL-1.1",
+ "Ubuntu-font-1.0",
+]
+confidence-threshold = 0.9
+
+[licenses.private]
+ignore = true
+
+[bans]
+multiple-versions = "warn"
+wildcards = "deny"
+allow-wildcard-paths = true
+
+[sources]
+unknown-registry = "deny"
+unknown-git = "deny"
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
new file mode 100644
index 0000000..de59169
--- /dev/null
+++ b/docs/DESIGN.md
@@ -0,0 +1,491 @@
+_Last updated: 2026-11-04 15:05_
+
+# klad: design
+
+A 2D art application built for agents first and humans second, for professional game assets in any style.
+
+An agent drives it through a CLI and sees results as PNG renders. A person with a pen opens the same file in a native editor to edit, add detail and animate. Both work on one document on disk at the same time.
+
+## Principles
+
+1. **Everything is addressable.** Layers, cels, vector nodes and individual paint strokes have ids. An agent never has to describe something by its pixels.
+2. **One set of pixels.** The CPU produces every pixel, in the CLI and in the editor, from the same code. What the agent renders is what the human sees.
+3. **Non-destructive by default.** Paint layers keep their strokes, vector layers keep their geometry, filters and adjustments keep their settings. Baking to plain pixels is an explicit choice.
+4. **Time is in the model from the start.** Every layer's content lives in cels on a timeline. A still image is a one-frame document.
+5. **Edit and see in one call.** Every mutating CLI command can render and return the PNG path.
+6. **Professional output.** 16-bit float layers, colour management, proper blend modes, exports a game engine can use as they are.
+
+## Architecture
+
+```
+crates/
+ core document model, ids, timeline, stroke format, bundle IO, op log
+ brush tile store, brush engine, stroke replay, checkpoints
+ render compositing, vector rendering, filters, overlays (Skia, CPU raster)
+ cli the `klad` binary
+ app the editor (macOS first), behind the `editor` feature
+```
+
+One binary, `klad`. `klad open [bundle]` launches the editor, on the bundle or, without one, on the start window (new, open, recent). The Linux build (agent container) has no editor; the macOS build has both.
+
+### Stack
+
+| Part | Choice | Why |
+|---|---|---|
+| Language | Rust stable | Native threads and memory for large canvases, fast CLI start, one codebase for CLI and editor |
+| Vector, text, filters, compositing | Skia via `skia-safe`, CPU raster only | Mature 2D engine (paths, booleans, gradients, image filters, SkSL shaders, text shaping). Same build on macOS and Linux |
+| Brush engine | Our own, dab based, on tiles | Full control over quality and determinism. Krita and MyPaint are the reference designs |
+| Editor window and GPU display | `winit` + `wgpu` (Metal), through `eframe` | The GPU only shows CPU-made tiles: pan, zoom, rotate, overlays |
+| Editor panels | `egui` | Fast to build, proven in pro tools (Rerun) |
+| Pen input (macOS) | `NSEvent` local monitor through `objc2-app-kit` | `winit` only reports trackpad pressure; the monitor gives tablet pressure, tilt and the eraser end at full rate |
+| Compression | `zstd` | Stroke files and cache tiles |
+
+klad is source-available, not open source: the PolyForm Internal Use License 1.0.0 with a personal-use permission, copyright Indicode BV (`LICENSE`). Every dependency is permissive: MIT, Apache-2.0, BSD-2/3, ISC, Zlib, BSL-1.0, Unicode-3.0, CC0-1.0, and for the fonts the editor shows its interface in, OFL-1.1 and the Ubuntu Font Licence. No GPL, LGPL or MPL unless dual licensed with one of these (two crates are, and are taken as `self_cell` under Apache-2.0 and `r-efi` under MIT). `deny.toml` holds the list, RustSec advisories, yanked versions and crates.io as the only source; `just audit` checks it with `cargo deny` and that `THIRD-PARTY-NOTICES.md` is current (`just notices` makes it with `cargo about`, plus the parts Cargo does not see: Skia's built-in libraries and the fonts, from `licenses/bundled/`). `klad licences` and the editor's About window show the same text.
+
+### Dependencies
+
+Direct dependencies, checked 2026-11-04 (all on their latest release; `cargo audit` found no vulnerabilities):
+
+| Crate | Used in | For | Licence |
+|---|---|---|---|
+| `skia-safe` 0.157 | render | paths, gradients, filters, compositing, PNG and JPEG codecs; links a prebuilt Skia m157 | MIT (Skia BSD-3) |
+| `skrifa` 0.44 | render | font outlines, metrics and kerning for text nodes (replaced the unmaintained `ttf-parser`, RUSTSEC-2026-0192) | MIT OR Apache-2.0 |
+| `zune-jpeg` | render | JPEG decoding for picture layers | MIT OR Apache-2.0 OR Zlib |
+| `png` | brush, render, app | PNG for brush pictures, picture layers and thumbnails | MIT OR Apache-2.0 |
+| `zstd` | core, brush, cli, app | stroke files, cache tiles, history | BSD-3 |
+| `half` | core, brush, render, app | f16 tiles | MIT OR Apache-2.0 |
+| `libm` | core, brush, render, cli | deterministic transcendental math | MIT |
+| `rayon` | brush, render, cli, app | parallel tiles and rows | MIT OR Apache-2.0 |
+| `serde`, `serde_json` | all | the bundle's JSON, ops, settings | MIT OR Apache-2.0 |
+| `bytemuck` | brush, render, app | pixel buffers as bytes | Zlib OR Apache-2.0 OR MIT |
+| `anyhow` | all | errors with context | MIT OR Apache-2.0 |
+| `clap` | cli | the `klad` command line | MIT OR Apache-2.0 |
+| `notify` | cli, app | watching a bundle for the other side's edits | CC0-1.0 |
+| `libc` | cli | default SIGPIPE handling, so piping `klad` into `head` ends quietly | MIT OR Apache-2.0 |
+| `eframe`, `egui`, `egui-wgpu` 0.37 | app | the editor's window, GPU display and panels | MIT OR Apache-2.0 (egui's fonts: OFL-1.1, Ubuntu Font Licence) |
+| `pollster` | app | blocking on wgpu setup | Apache-2.0 OR MIT |
+| `objc2`, `objc2-app-kit`, `objc2-foundation`, `block2` | app, macOS | the pen through NSEvent, the open panel | MIT |
+| `egui_kittest` (dev) | app tests | headless UI tests | MIT OR Apache-2.0 |
+
+Accepted warnings: `zvariant`, `zvariant_derive` and `zbus_names` (unmaintained) and `async-executor` 1.14.0 (yanked) come only through eframe's Linux accessibility (`accesskit_unix`) and wait on eframe moving to zbus 6.
+
+### Determinism
+
+The CLI render and the editor must agree. Rules for `core`, `brush` and `render`:
+
+- Transcendental math (`pow`, `exp`, `sin`, `cos`, `atan2`) goes through the `libm` crate, never the platform libm.
+- One seeded RNG type (`core::rng`), seeded per stroke. No wall clock in rendering.
+- No `HashMap` iteration order affecting output. Tiles live in a fixed grid.
+- Parallel work is split into independent units (tiles, image rows), each computed the same way regardless of thread count.
+- `klad hash` prints a hash of rendered pixels; the parity check compares macOS and Linux.
+
+## The document bundle
+
+```
+art.draw/
+ doc.json canonical document (pretty JSON, stable key order)
+ strokes/<layer>/<cel>.strokes stroke and fill records per cel (binary, zstd)
+ brushes/<id>.json every brush the document uses, embedded on first use
+ assets/ imported images (PNG)
+ .gitignore ignores .cache/
+ .cache/ rebuildable: pixel tiles, checkpoints, renders, op log
+```
+
+Committed: everything except `.cache/`. A fresh clone rebuilds the cache by replaying strokes and fills.
+
+### doc.json (format `draw-anything/8`)
+
+```json
+{
+ "format": "draw-anything/7",
+ "rev": 42,
+ "canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },
+ "timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],
+ "clips": [{ "name": "run", "from": 0, "to": 11, "loop": true, "fps": 24 }, { "name": "jump", "from": 12, "to": 23 }] },
+ "export": { "godot": "../game/art/hero" },
+ "palette": [{ "color": "#1b1b1b", "name": "ink" }, { "color": "#f0c8a0", "name": "skin" }, { "color": "#5b6ee1" }],
+ "layers": [
+ { "id": "l3", "name": "lines", "kind": "paint", "opacity": 1, "blend": "normal", "visible": true,
+ "cels": [
+ { "id": "c1", "frame": 0, "hold": 2 },
+ { "id": "c2", "frame": 2, "hold": 2 },
+ { "id": "c3", "frame": 4, "hold": 2, "link": "c1" },
+ { "id": "c9", "frame": 6, "hold": 1, "tween": { "from": "c2", "to": "c10", "t": 0.5, "made": "3f0c9e21a4b6d870" }, "parts": { "leaf": [14, 15] } },
+ { "id": "c10", "frame": 7 }
+ ] },
+ { "id": "l5", "name": "shade", "kind": "paint", "blend": "multiply", "clip": true, "lockAlpha": true,
+ "cels": [{ "id": "c6", "frame": 0 }],
+ "mask": { "id": "l7", "name": "mask", "kind": "paint", "cels": [{ "id": "c8", "frame": 0 }] } },
+ { "id": "g1", "name": "fx", "kind": "group", "opacity": 0.8, "blend": "screen", "visible": true,
+ "children": [] },
+ { "id": "l4", "name": "shapes", "kind": "vector", "opacity": 1, "blend": "normal", "visible": true,
+ "cels": [{ "id": "c4", "frame": 0, "nodes": [
+ { "id": "n5", "name": "sky", "type": "rect", "x": 0, "y": 0, "w": 2048, "h": 900,
+ "fill": { "linear": { "from": [0, 0], "to": [0, 900], "stops": [[0, "#121d31"], [1, "#4a6a8c"]] } } },
+ { "id": "n6", "type": "group", "transform": { "rotate": -8, "x": -120 }, "children": [
+ { "id": "n7", "type": "path", "d": "M380 560 L560 560 L530 600 L410 600 Z", "fill": "#2b1d14",
+ "stroke": { "paint": "#000000", "width": 3 } } ] }
+ ] }] }
+ ],
+ "nextId": 7
+}
+```
+
+- Layers are listed bottom to top. `ls` prints them top first, like a layers panel.
+- Ids are unique across the document (letters, digits, `-`, `_`): new ones are `l`, `c` and `n` plus a counter.
+- A **cel** is a layer's content from `frame` on. `hold` limits it to that many frames; without `hold` it lasts until the next cel. Drawing on twos is `hold: 2`. `link` reuses another cel's content; links cannot chain. Paint cels keep their strokes in `strokes/<layer>/<cel>.strokes`. In animation terms a cel that is not a link is a **drawing**, the frames it shows on are its **exposure**, and frames no cel covers are **blank**. The timeline (`frames`) always covers every cel's first frame: an op that puts a cel past the end makes the timeline longer, and a stroke, fill or shape added at a frame past the end starts a cel there instead of landing in the last open exposure.
+- An **in-between** is a drawing made by `inbetween` from two keys: its cel keeps `tween` (format 6) with the keys' drawing ids (`from`, `to`), its position `t` between them (0 to 1, after spacing), how its marks were paired when not by id (`match`: `order` or `near`, and forced `pairs` as `[first key id, second key id]`) and `made`, a hash of the marks as they were made. `inbetween --redo` remakes in-betweens from their keys and refuses one whose marks no longer hash to `made` (drawn on or edited since) unless forced. A link cannot be an in-between; `set <cel> tween=null` makes it an ordinary drawing. `unpaired` (format 7) keeps how marks in one key only were shown (`pop`, `pop 0.3`, `fade`, `draw-on`), so a redo shows them the same way.
+- A cel's **parts** (format 7) name groups of its marks: `"parts": {"leaf": [14, 15], "near leg": [9]}`. A mark is in one part at most. They live in the cel record, not in the stroke file, so naming parts never rewrites strokes; ids that no longer exist are ignored. `dup`, `unlink`, `copy` and in-betweens keep them (an in-between gets the first key's parts, as it keeps its ids). Format 6 documents open as format 7 without parts.
+- A **clip** is a named frame range, both ends included: an animation such as `idle`, `run` or `attack`. It loops or plays once (`loop`), and may have its own `fps` (format 5); without one it plays at the timeline's. Names are unique and clips may overlap. Clips are kept in order of their first frame. Exports turn each clip into an engine animation. Frame ops on every layer move and stretch clips (an insert inside a clip lengthens it, a remove shortens it, a clip left with no frames goes); frame ops on listed layers leave them alone; a shorter timeline trims clips and refuses to cut one off entirely.
+- The **origin** (`timeline.origin`, format 5) is the canvas point an engine export puts on the node's position, the centre of the canvas when absent.
+- **`export.godot`** (format 5) is the folder Godot exports go to, relative to the folder holding the bundle, so the CLI and the editor's "export to Godot" button write to the same place.
+- The **palette** is the document's colours, each with an optional unique name (not starting with `#`). Wherever an op or a CLI flag takes a colour for a stroke or a fill it also takes a palette name; the stroke or fill stores the colour itself, so renaming or recolouring a swatch never changes what is drawn.
+- **Nodes** (vector cels): `rect` (x, y, w, h, radius), `ellipse` (cx, cy, rx, ry), `path` (SVG `d`), `group` (children). Each takes `fill`, `stroke`, `transform`, `opacity`, `blur` (Gaussian sigma in px, softens the whole node; when the blur reaches 12 device px or more the node is drawn 2 to 32 times smaller on a power-of-two grid aligned in device space, blurred there with an exact Gaussian in Rust and scaled back up, which is about 3 times faster than Skia's CPU blur and closer to a true Gaussian; non-uniformly scaled nodes keep Skia's blur), `clip` (an SVG path in the node's own coordinates that clips it and its children), `visible`, `name`.
+- **Paint** is `"#rrggbb"`, `"#rrggbbaa"`, `"none"`, `{ "linear": { "from", "to", "stops" } }` or `{ "radial": { "center", "radius", "stops" } }`, in the node's own coordinates. As in SVG, a missing fill is black and a missing stroke is none. Strokes default to width 1 with round caps and joins; `dash` takes SVG-style intervals.
+- **Transform** is `x`, `y`, `rotate` (degrees), `sx`, `sy`, `pivot`; it applies translate, then rotate and scale about the pivot, which defaults to the centre of the node's bounds.
+- **Masks.** `mask` is a paint layer kept under the layer it masks, with its own id, cels and stroke files (`strokes/<mask id>/<cel>.strokes`). Its alpha hides the layer: strokes and fills on the mask hide, the eraser shows the layer again, and an empty mask (or a frame without a mask cel) hides nothing. `visible: false` turns the mask off. A mask keeps opacity 1 and blend normal and has no mask or clip of its own. Paint, vector and group layers can have one. Internally a mask's layer path ends in `MASK`, so `locate`, `layer_at` and the history treat it as a layer.
+- **Clipping.** `clip: true` shows a layer only where its base, the nearest layer below it in the same list without `clip`, has alpha. The base and the clipped layers above it draw as one group: each clipped layer blends onto the base with its own blend and opacity (masked by the base's alpha), then the group composites onto what is below with the base's blend and opacity, as in Photoshop with "blend clipped layers as group". A hidden base hides its clipped layers; the lowest layer of a list draws unclipped.
+- **Lock alpha.** `lockAlpha: true` on a paint layer makes new strokes and fills land only where the layer already has alpha: they composite source-atop and leave alpha unchanged. The flag is recorded on each stroke and fill (stroke format 5), so turning it off later never changes what was drawn. An eraser stroke on a lock-alpha layer changes nothing (the editor refuses it).
+- `rev` increments on every write. Older formats are migrated on open (format, files, then the old files are removed); `/0` bundles from M0 upgrade this way. Format 2 (M2) changed no keys: it marks a bundle that embeds its brushes. `/1` bundles become `/2` by embedding the M1 version of every brush their strokes use (`crates/core/brushes/m1/`), so they render exactly as before. Format 3 (M2 batch 2) adds `palette` and marks a bundle whose paint cels may hold fills (stroke file version 4); `/2` bundles only change the format string, in memory until the next write. Format 4 (M2 batch 4) adds `mask`, `clip` and `lockAlpha`, and marks a bundle whose stroke files may be version 5; `/3` bundles only change the format string. Format 5 (M3 batch 3) adds a clip's `fps`, `timeline.origin` and `export.godot`; `/4` bundles only change the format string. Format 6 (M3 batch 4) adds a cel's `tween`; `/5` bundles only change the format string. History snapshots in older formats are migrated when undone.
+
+### Edits
+
+All edits are ops, applied as one transaction that either fully applies or changes nothing, and validated before anything is written. The CLI commands and `klad apply` (JSON lines) produce the same ops:
+
+| Op | JSON line |
+|---|---|
+| add a layer | `{"op":"add","layer":{"kind":"vector","name":"sky"},"above":"l2"}` |
+| add a node | `{"op":"add","node":{"type":"rect","x":0,"y":0,"w":10,"h":10},"in":"l4","frame":0}` |
+| add a cel | `{"op":"add","cel":{"frame":4,"hold":2,"link":"c1"},"in":"l3"}` |
+| set properties | `{"op":"set","id":"n5","fill":"#ff0000","transform.rotate":15,"stroke":null}` |
+| remove | `{"op":"rm","ids":["n5","l3"]}` |
+| move | `{"op":"mv","id":"l3","below":"l4"}` (or `in`, `index`) |
+| paint a stroke | `{"op":"stroke","layer":"l3","brush":"ink","size":8,"color":"ink","path":"M0 0 L90 40","taper":[12,30]}` |
+| fill | `{"op":"fill","layer":"l2","at":[820,640],"ref":"lines","gap":4,"color":"skin"}` or `"polygon":[[x,y],...]` |
+| palette | `{"op":"palette","add":"#f0c8a0","name":"skin"}`, `{"op":"palette","rm":"skin"}`, `{"op":"palette","set":[...]}` |
+| edit a stroke or fill | `{"op":"set","id":"c4:s12","color":"skin","size":6,"brush":"pencil"}`, `{"op":"rm","ids":["c4:s12"]}` |
+| move, turn, scale marks | `{"op":"transform","ids":["c4:s3","c4:s5"],"x":40,"y":-10,"rotate":15,"sx":1.2,"sy":1.2,"pivot":[512,400]}` |
+| path points | `{"op":"path","id":"n7","move":3,"to":[412,230]}`; also `"move":[3,4],"by":[dx,dy]`, `"handle":3,"out":[x,y]`, `"insert":3,"t":0.5`, `"add":[x,y]`, `"rm":[4,5]`, `"corner":2`, `"smooth":6`, `"simplify":1.5` |
+| add a mask | `{"op":"add","mask":{"name":"mask"},"in":"l5"}` (`"hide":true` starts it with a fill that hides the whole layer); rm the mask id to remove it |
+| lasso | `{"op":"lasso","layer":"l3","polygon":[[x,y],...],"cut":true,"x":40,"y":-10,"rotate":15,"sx":-1,"pivot":[..]}` or `"rm":true` |
+| timeline | `{"op":"timeline","fps":12,"frames":24}`, `{"op":"timeline","origin":[512,700]}` (`null` for the centre) |
+| clips | `{"op":"clip","add":"run","from":0,"to":11,"loop":true,"fps":24}`, `{"op":"clip","set":"run","name":"sprint","to":15,"loop":false,"fps":null}` (`null` fps: the document's), `{"op":"clip","rm":"run"}` |
+| export folder | `{"op":"export","godot":"../game/art/hero"}` (`null` forgets it) |
+| frames | `{"op":"frames","insert":4,"count":2}`, `{"op":"frames","remove":4,"count":2,"layers":["l3"]}` |
+| drawings | `{"op":"cel","new":"l3","frame":5}`, `{"op":"cel","dup":"c4","frame":6,"insert":true}`, `{"op":"cel","link":"c4","frame":8,"hold":2}`, `{"op":"cel","unlink":"c9"}`, `{"op":"cel","move":"c5","frame":12}` (keeps its length; the exposure it lands in is cut there and drawings it lands on are pushed along to its end); `"id"` names the new cel |
+| duplicate a layer | `{"op":"duplicate","layer":"l3"}`: its cels, stroke files, links, in-between marks and mask copied with new ids, named "<name> copy", right above it |
+| copy marks | `{"op":"copy","ids":["c1:s3","c1:s4"],"frame":4}`, `"to":"c9"`, `"layer":"shade"` with `frame`; `x`, `y`, `rotate`, `sx`, `sy`, `scale`, `pivot` as in transform; `"cut":[[x,y],...]` |
+| retime | `{"op":"retime","from":0,"to":11,"on":2}`, `"fit":16`, `"reverse":true`, `"pingpong":true`; `"layers":["l3"]` |
+| in-betweens | `{"op":"inbetween","layers":["lines","colour"],"from":0,"to":6,"count":2,"spacing":"in-out","match":"near","pair":[[3,7]],"unpaired":"fade"}`, `{"op":"inbetween","layers":["lines"],"from":9,"loop":true}`, `{"op":"inbetween","redo":true,"keepDrawn":true}` or `"force":true` (computed by the CLI; alone in its batch) |
+| parts | `{"op":"part","ids":["c4:s14","c4:s15"],"name":"leaf"}` (`"name":""` takes them out of their part); `stroke`, `fill`, `ink`, `hatch` and `scatter` take `"part":"leaf"` for the marks they add |
+| ink from shapes | `{"op":"ink","layer":"l3","from":["n5","n6"],"weight":6,"light":[-1,-1],"break":60,"gap":0,"wobble":0.6,"seed":1}` or `"path":"M..."` (computed by the CLI into strokes) |
+| shade and rim | `{"op":"light","from":["n5"],"light":[-1,-1],"shade":"l5","rim":"l6","depth":14,"soft":3,"rimWidth":4,"shadeColor":"#5a4a6a","rimColor":"#fff1cc"}` (computed into lasso fills with a cut) |
+| hatching | `{"op":"hatch","layer":"l5","in":["n5"],"angle":30,"spacing":6,"length":[12,30],"jitter":0.3,"weight":2}` or `"along":true` (computed into strokes) |
+| scatter | `{"op":"scatter","layer":"l3","in":["n5"],"avoid":["n9"],"mark":"M0 0 L0 -18","count":40,"size":[0.7,1.2],"turn":[-15,15]}` (computed into strokes) |
+| fill a shape | `{"op":"fill","layer":"l2","shape":"n5","color":"skin","expand":2}` (computed into a lasso fill per closed outline); any fill may take `"outside":[[x,y],...]`, a cut that keeps what lies outside that polygon |
+| fills like a drawing | `{"op":"fill","layer":"colour","like":"c4","frames":"0-11"}` (computed by the CLI; alone in its batch) |
+
+Unknown keys are errors that list the valid ones, so a typo never passes silently. Structure (`id`, `kind`, `type`, `cels`, `children`, `nodes`, `mask`) changes only through add, rm and mv; a mask cannot be moved, and nothing goes above or below it. A fill op needs pixels to compute its coverage, so the CLI computes it before the transaction, in op order: strokes and fills earlier in the same batch, and stroke edits, are part of what a fill sees.
+
+**Frames and drawings.** `frames` insert puts `count` frames at a frame: what showed there now also shows on the inserted frames (the exposure covering it lengthens, a blank stays blank) and every later cel moves back. `frames` remove takes `count` frames out: exposures over them get shorter, later cels move forward, and a drawing left with no frames goes. Both work on every layer (then clips move with them and the timeline grows or shrinks) or on the listed layers and everything inside them (an insert lengthens the timeline only as far as their drawings need: a last drawing without a hold keeps its length, one with a hold must still fit; a remove leaves the length); a layer's mask always moves with it. Removing a drawing that links point to, by `rm` or by removing its frames, hands it to the first link: that link becomes the drawing (its strokes or nodes) and the other links point to it, so links never break. `cel` places a cel at `frame` on a layer: `new` a blank drawing, `dup` a new drawing with a copy of another's strokes and fills (mark ids kept, so a stroke in the copy is the same address in the new cel) or of its nodes (new node ids), `link` a link to another cel's drawing (a link to a link points to its source). Inside an exposure the new cel takes over the rest of it; on a blank frame it lasts until the next cel, or `hold` frames (`dup` and `link` default to their source's hold); `dup` and `link` default to the frame right after their source's exposure. With `insert` the layer's cels from that frame on move back by the new cel's length first (the timeline grows as for a listed-layer insert), which only works at the start or end of an exposure. `unlink` turns a link into a drawing of its own with a copy of its source. Copies of strokes are made when the batch is written, from the source as it is at that point of the batch.
+
+**Copies.** `copy` copies strokes and fills (from one or more cels) into one drawing: `to` a cel, or the drawing a layer shows at `frame` (the marks' own layer unless `layer`; an empty frame or one past the end starts a drawing there; a frame showing a link names its source, which the editor resolves itself). The copies take the next ids of the target, keep their order (sources in the order given, marks in their source's order) and land on top; the op reports each `from` and `to` address. A move, turn, scale or flip applies to the copies together, about `pivot` or the middle of their bounds. `cut` adds a cut keeping the inside of a polygon to every copy, so only the parts inside are seen. Copies see the batch as it is at that point, like `dup`.
+
+**Retiming.** `retime` takes frames `from` to `to` (both included) on every layer, or on the listed layers with their masks and children. The range is cut into pieces where any of those layers changes what it shows, so layers stay in step; each piece is one picture. `on n` gives every piece n frames; `fit n` makes the range n frames, each piece starting at its old position scaled (rounded, at least one frame each, order kept; fewer frames than pieces is refused); `reverse` plays the pieces backwards; `pingpong` adds them again backwards without repeating the ends (a b c d c b). Every affected layer is rebuilt from what it shows frame by frame: runs of the same drawing merge, a drawing's first run keeps the cel (and its hold style), later runs become links to it. Everything after the range moves by the change in length. On every layer, clips move and stretch with it (an end inside the range is scaled with the range) and the timeline grows or shrinks; on listed layers clips stay and the timeline only grows, as for a frame insert.
+
+**In-betweens.** `inbetween` makes drawings between two keys on paint layers: the drawings shown at `from` and at `to` (where the second key's exposure starts; a link there names its source, so a loop's last in-betweens lead back to its first drawing). By default a cel goes on every frame between them; with `count` n they go on frames spread evenly between the keys, each held until the next, and the first key's exposure ends at the first one. Positions follow `spacing`: `even` (i/(n+1)), `in` (squared: bunched near the first key), `out` (bunched near the second), `in-out` (smoothstep), or the positions themselves. Cels already between the keys must be in-betweens of the same keys (they are replaced) unless forced. A layer that shows the same drawing at both keys is left alone. The CLI computes the marks, then the op adds the cels and their marks as one history step.
+- Pairing: by id (default: a key duplicated from the other keeps its ids), by `order` (strokes, lasso fills and flood fills each in order) or `near` (greedy on the mean distance between 16 points along each, trying a stroke backwards too). `pair` forces pairs first. A stroke never pairs with a fill, nor a lasso fill with a flood fill; unpaired marks are left out and listed.
+- Each stroke pair is resampled by arc length to the longer one's sample count; pressure, tilt and time ride along. The best-fit rotation and scale from the first key's points to the second's (a similarity, least squares) is followed along its arc: about its fixed point, the angle and the log of the scale moving with t, and what the fit leaves is added on top in proportion. So a swinging stroke turns about the point it swings around and keeps its length.
+- Strokes ride on the lines they touch: a stroke end that touches another stroke in both keys (within half that stroke's size plus 2 px, plus a quarter of its own) joins them in a tree rooted at the longest stroke of each connected group, and a child moves in its parent's frame: the parent's motion at t, then the child's own turn relative to the parent along its arc. A hand bending at the wrist stays on the turning arm. The touching end is then moved onto the other line at the interpolated contact (its place along that line and its offset, both interpolated), pulling the nearest third of the stroke (up to 48 px) with it, so closed shapes stay closed. On a closed line, the second key's contact is the one nearest along the line to the first key's, and a contact that jumps more than half the line is not kept.
+- Size, opacity, flow, taper and colour interpolate; brush, seed, lock alpha and cuts come from the first key (cuts move with the stroke); in-between marks keep the first key's ids and are marked agent.
+- Lasso fills interpolate their polygons the same way. Flood fills are recomputed in each in-between: the seed is carried by the lines it sits next to (the nearest point on the nearest paired stroke of the reference, its place along that stroke and its offset across, found in each key, placed on the in-between strokes and blended by t), moved onto the nearest open pixel when it lands on a line, and the fill is computed with its own settings against the in-between's reference. Layers whose fills reference another in-betweened layer go after it, `all` last. A fill that lands on a line, covers nothing, or comes out over 1.6 times (plus 64 px) or under 0.4 times what the keys' areas say is left out and listed.
+
+**Fills like another drawing.** A `fill` with `like` carries every flood fill of one drawing to the layer's other drawings on `frames` (all, a range or a clip): for each target, the reference at the frame where it first shows is cut into regions as the fill would see them (its colour, tolerance and gap); each region near the old fill is compared with the old coverage shifted onto the region's centre (overlap over union, falling off with the distance moved), regions open to the canvas edge only when the old fill touched it; the seed goes to the best region's pixel nearest the shifted old seed and the fill is computed there. A target that already has a fill with that id has it replaced in place, otherwise the fill goes on top with that id (or the next free one). Fills that find no region, cover nothing or come out over 2.5 times (plus 256 px) the old one are listed. One history step for all targets.
+
+**Parts, arcs and hand work in in-betweens (M4.5 batch 2).** Pairing for in-betweens goes forced pairs first (`--pair`), then part by part for every part name both keys have (within a part and a kind of mark, in drawing order when the counts match, by nearest shape when they do not), then the `match` rule for the rest, so keys drawn separately pair whatever their ids. `--loop` takes the loop's first drawing as the second key (the clip holding `--from`, else frame 0; `--to` defaults to the loop's end), so a cycle closes without a temporary link. Marks in one key only follow `unpaired`: left out (the default, listed), `pop` at the middle or at `t`, `fade` (opacity over the in-betweens), `draw-on` (drawn along their length; one-key marks of the first key draw off); they are carried with the lines around them (`tween::carry`: every point anchored along the nearest paired line and placed on that line in the in-between), and flood fills among them are still left out. `--redo --keep-drawn` splits an in-between's marks by author: it remakes the agent's from the keys and keeps the hand-drawn ones on top, carried from the old in-between's lines to the new ones (aligned by mark id; a hand mark in a part follows the lines of that part), with new ids and their parts; `made` stays the hash of the agent's marks, so a plain `--redo` still refuses it. Arcs (`cli/src/arcs.rs`) track a mark through the drawings that show its id, a part's centre in each drawing of a layer (the first paint layer that has the part, or `layer:part`), or a point carried by the stroke nearest to it at the first frame; each frame gives a centre and a lowest point (the middle of the samples within 1 px of the lowest y). `--ground` reports the lowest point under the line, and slides: consecutive changed positions both on the line (within `--slack`) whose horizontal move differs from `-travel` per frame (a cycle drawn in place should move a planted foot back by the travel); with two tracks, frames where their left-right order flips are swaps. `--overlay arcs` draws each track as a line with a dot and a tick across the path per frame, numbered, the current frame ringed; `--overlay parts` boxes and names each part.
+
+**Drawing from shapes.** `ink`, `light`, `hatch`, `scatter` and `fill` with `shape` read the outlines of vector shapes (rects, ellipses, paths; a group means each shape in it), flattened every 2 px and taken to canvas coordinates through the node's transforms (`klad_render::shapes`), and are turned by the CLI into ordinary strokes and fills before the transaction (`cli/src/shapes.rs`), so they replay like any mark; shapes added earlier in the same batch are seen. Ink resamples each outline, splits it at corners sharper than `break` degrees (open paths at their ends too), and gives each sample a pressure from three rules multiplied together and smoothed: the outward normal against the light (0.55 facing it to 1 facing away), the silhouette (0.7 where the outline lies inside another closed outline of the call), the curvature (down to 0.65 on tight curves); a seeded two-sine wobble moves points along the normal. A closed outline without corners is one stroke that starts at its lightest point and overlaps its start by 12 px. `light` makes lasso fills of each closed outline with a cut that keeps the outside of the same outline moved towards the light by `depth` (in `soft` steps from 0.6 to 1.4 times the depth, each at a share of the opacity) for the shade, and moved away from the light by `rimWidth` for the rim. `hatch` cuts parallel lines (or inward offsets of the outline with `along`) into pieces of the given lengths, jittered and clipped to the area; `scatter` places a mark at jittered grid points or `count` random points inside the area and outside `avoid`, scaled and turned by seeded amounts. All of it is deterministic (libm, the seeded RNG). Lasso fills skip the CLI's catch-up of earlier marks (only flood fills need to see them), so 160 fills from one `light` of 40 shapes take about 260 ms.
+
+**Stroke addresses.** Strokes and fills are addressed as `<cel>:s<id>`, for example `c4:s12`; fills share the id counter with strokes. `set` on a stroke takes `color`, `size`, `opacity`, `flow`, `brush` and `taper`, on a fill `color` and `opacity`; colours may be palette names. `transform` applies translate, then rotate (degrees, clockwise) and scale about `pivot`, by default the middle of the marks' bounds; stroke samples move at their stored 1/16 px precision, sizes and tapers scale by the square root of the area scale, tilt turns with the stroke, and fills move by whole pixels (their coverage shifts exactly) or are resampled bilinearly when turned or scaled. Marks keep their ids and their place in the order. Ids in several cels need an explicit pivot.
+
+**Lasso.** A `lasso` op works on the strokes and fills of one paint cel inside a polygon. A stroke is inside when every sample it keeps (see cuts) is inside the polygon, a fill when every pixel it covers is; marks with some of each cross the edge. Without `cut` the op moves, turns, scales, flips (negative `sx` or `sy`) or removes (`"rm":true`) the marks inside. With `cut`, every crossing mark is first split in two: the original gains a cut that keeps the outside of the polygon and stays where it is, and a copy with a new id, placed right after it, gains a cut that keeps the inside and moves with the rest. So nothing outside the lasso changes, and the moved parts stay strokes (recolour them, thin them, move them again). The op is one history step and reports the ids it moved.
+
+**Cuts.** A stroke or fill may carry cuts: polygons with a side to keep (`inside` or `outside`). When the mark is painted, its coverage is multiplied by each cut's coverage of the polygon (4x4 supersampled, even-odd) or one minus it; tiles a cut leaves untouched are skipped. Cuts move, turn and scale with their mark. A split stroke drawn in place shows a faint seam only where the lasso edge crosses its antialiased edge, the same as a raster cut and paste. A cut is not a layer mask: it belongs to the mark and replays with it.
+
+**Path points.** A path, rect or ellipse reads as subpaths of anchors, each with an in and an out handle (absolute, in the shape's own coordinates; a handle on its anchor means none). Every SVG command parses into this form (quadratics become cubics exactly, arcs become cubics of at most 90 degrees) and is written back as `M`, `L`, `C` and `Z` with two decimals. A rect or ellipse becomes a path that looks the same on its first point edit. Anchors are numbered across subpaths. Smooth means both handles present and in line; moving one handle of a smooth point turns the other to stay in line unless `free`. `insert` splits a segment at `t` without changing its curve, `add` finds the nearest segment, `rm` joins the neighbours, `corner` drops the handles, `smooth` sets them along the line between the neighbours at a third of each distance, and `simplify` refits each run between sharp corners (over about 50 degrees) as least-squares cubics (Schneider) within the tolerance, keeping straight runs straight. Before a path op, the CLI and editor pin `transform.pivot` on the shape and every group above it whose transform is not identity and has no pivot, so a point edit never moves the rest of the shape.
+
+### Layer kinds
+
+| Kind | Content | Mostly made by |
+|---|---|---|
+| `paint` | strokes, replayed to f16 tiles | human pen, agent scripted strokes |
+| `vector` | shapes, paths, text, generators | agent |
+| `pixel` | palette-indexed grid, no anti-aliasing | agent and human |
+| `adjust` | one adjustment: `hsl`, `levels`, `curves`, `balance`, `gradient-map`, `fill` (M5) | either |
+| `group` | children, blend mode, opacity, mask, clipping | either |
+
+Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.
+
+- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
+- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
+- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
+- **Rays (M5).** A vector node `{"type": "rays", "x", "y", "angle", "spread", "count", "length", "start", "falloff", "noise", "seed"}` draws soft beams from an origin (a gap `start` px wide), each a quad with a radial falloff and its own length and strength from the seed; the node's `fill` colours them and its `blur` softens them. Rays come from the agent (`klad add rays`); in the editor a selected rays node shows its settings in the inspector.
+- **Depth and atmosphere (M5).** A layer at the top of the stack (a plane, usually a group) may have a `depth` (0 is near; validation refuses it deeper in the tree). The document's `atmosphere` (`color`, an optional `top` colour blended down over the canvas height, `density`, `blur`, `desaturate`) turns each plane's depth into two effects after its own (`Document::effects_of`): a `haze` towards the fog of `1 - e^(-density x depth)` with `desaturate x depth` of its colour taken out, and a blur of `blur x depth` px. `haze` is an ordinary effect too. The depths are kept for M6's Parallax2D export; in the editor a depth field sits in each plane's row and inspector, the inspector holds the atmosphere, and holding D shows the planes (each flattened alone, in the background) sliding by `offset x 0.08 / (1 + depth)` with the pointer.
+- **References (M5).** Any layer can be `reference: true`: the editor shows it, renders, hashes and exports leave it out unless asked (`--references`), and fills never see it.
+- **Pictures (M5).** A picture is a vector node `{"type": "image", "src", "x", "y", "w", "h"}`, so V moves and scales it and the inspector fades it. Importing (`klad add layer image src=photo.jpg`, dropping a PNG or JPEG on the editor, or "import a picture") decodes PNG with `png` or JPEG with `zune-jpeg`, re-encodes it as PNG and stores it as `images/<content hash>.png`, so the same file twice is stored once and every machine draws the same pixels; it lands on a new vector layer, fitted inside the canvas. The renderer finds pictures and fonts in the folders of every bundle the process opened (`klad_render::assets`).
+- **Generators (M5).** `scatter` (copies of its children over a region, `count`, `seed`, `size` and `turn` ranges, `avoid`: SVG paths no copy's centre may fall in), `repeat` (`count` copies, each `step` further, turning `turn` degrees and growing `scale` about `pivot`, or a grid `columns` wide with `row` between rows) and `mirror` (its children and their reflection across a line through `x, y` at `angle`) are nodes whose children are drawn once per instance (`generators.rs`); they stay settings, the inspector edits them, and "repeat it", "scatter it", "mirror it" put a selected shape inside one; "take the shapes out" removes one and keeps its shapes where its first copy was. Their children keep their ids, so V can still pick inside.
+- **Text (M5).** `{"type": "text", "text", "font", "x", "y", "size", "tracking", "leading", "align"}` with the node's fill and outline. The font is a file in the bundle's `fonts/` folder (`klad font` adds one; choice 3); the outlines come from the file through `ttf-parser` (advances, kerning, tracking, lines split on new lines, `x` the left, centre or right of each line, `y` the top of the first line) and are drawn as one path, never by the system's font engine, so the Mac and the container draw the same pixels. A missing font is refused with its name. A light layer is no kind of its own: a paint layer set to `add` with a soft glow (a shortcut button for it only confused the layers pane).
+
+## Strokes
+
+### Recording
+
+Pen samples are quantised the moment they arrive, and the brush draws from the quantised values, so a replay matches what was drawn exactly. Before quantising, the editor passes each sample through:
+
+1. **The pen's calibration curve**: lightest and heaviest raw pressure and a gamma, kept per pen device in the user's settings (`~/Library/Application Support/draw-anything/settings.json`, `$KLAD_SETTINGS` overrides). A touching pen never records below one pressure step, so 0 keeps meaning "no reading".
+2. **The brush's pressure smoothing**: an exponential average with a time constant in ms.
+3. **The brush's stabiliser**: the position is the average of the raw positions of the last N ms. At pen up the window drains, so the line catches up to where the pen lifted.
+
+Stored pressure is therefore device independent and replays need none of these settings. Mouse and trackpad samples that carry no pressure (a tap-drag) record 1; a stroke whose pressure is 0 on every sample draws as if pressure were 1.
+
+| Channel | Stored as |
+|---|---|
+| x, y | 1/16 px, zigzag varint delta |
+| pressure | 12 bit, zigzag varint delta |
+| tilt x, y | 8 bit each (-1..1), delta |
+| time | ms since previous sample, varint |
+
+A stroke header holds the stroke id, brush id, colour, base size, opacity, flow, seed, author, the channel mask and, when set, the taper (in and out lengths in px; stroke format 3, M2), then (stroke format 5, M2 batch 4) the lock alpha bit in the channel mask and, when the mark has cuts, the cuts. Fills carry the same two in the high bits of their source byte; a stroke or fill without them encodes byte for byte as in format 4. Samples are stored per channel (all x deltas, then all y deltas, ...) so zstd compresses them well. One file per cel. Since stroke format 4 (M2 batch 2) every record starts with a kind byte, stroke or fill, and strokes and fills share one id counter per cel; files of versions 1 to 3 hold strokes only and still load.
+
+### Size budget
+
+Estimate before M0: about 0.5 KB per stroke, so 10,000 strokes is about 5 MB. A fully painted 4096x4096 f16 layer is 128 MB uncompressed. Strokes are the small part; pixels live in the gitignored cache. M0 measures the real numbers.
+
+### Fills
+
+A fill is a record in a paint cel, in order with the strokes: id, colour, opacity, author, how it was made, and the coverage it produced (a crop box and 8-bit alpha, run-length coded, then zstd with the rest of the file). Replay paints the stored coverage like a stroke buffer at full flow, so a fill never depends on other layers or on the fill code: CLI and editor, macOS and Linux get the same pixels.
+
+- **Flood fill** (`at`): pixels count as inside when every premultiplied channel is within `tolerance` (0 to 1, default 0.1) of the seed pixel in the **reference**: `this` layer as it was just before the fill (its earlier marks), a named layer (paint, vector or group, drawn alone at full opacity, even when hidden) or `all` (everything visible over the background). Four-connected.
+- **Gap closing** (`gap`, px): the lines are grown by `(gap + 1) / 2`, so openings up to `gap` px wide close and the open space splits into free regions; the fill takes the seed's region (a click near a line starts from the nearest free region). The pixels the growth took from the open space go to whichever region reaches them first along paths that stay off the lines (chamfer distance, ties to this fill), so the fill reaches into corners and sharp points, two fills that meet in a gap meet on a line across it, and a fill never escapes through a gap it closed. Islands of free space with no pixel 2 px clear of the grown lines do not count as regions.
+- **Expand** (`expand`, px, default 2): the result grows that far into line pixels only, under the line's anti-aliased edge, so no paper shows between line and colour.
+- **Lasso fill** (`polygon`): the polygon's area with 4x4 supersampled edges, nonzero winding.
+- **Gaps**: `klad gaps` cuts a fill layer's reference into closed regions (as a flood fill with the layer's gap would, one pixel further from the lines) and lists those no fill of the layer covers: pockets a fill missed, or drawings not coloured yet. Regions open to the canvas edge are the outside and do not count; smaller than `--min` px (12) are ignored. The reference, gap and tolerance default to the layer's flood fills on those frames.
+- **Refill**: `klad refill` recomputes the coverage of every flood fill in a cel (or one, `--id`) from its stored seed and settings against the current reference, keeping its place in the order.
+- Speed (container): a 2048x2048 flood fill takes about 30 ms, 55 to 65 ms with gap closing; a whole `klad fill` on a 2048 canvas, loading the reference from cached tiles, 80 to 110 ms. Fills are deterministic on any thread count.
+
+### Replay and checkpoints
+
+A layer cel's pixels are its strokes and fills replayed in order. Each replay records every mark's footprint (the tiles it touched) and its key (id and a hash of its encoded record), and keeps a checkpoint every 128 marks: the tiles as they were at that point, shared with the previous checkpoint where they did not change. Checkpoints are capped at 128 MB per cel by thinning out every other one.
+
+When the marks change (an edit, a removal, an undo, an insert), the old and new lists are matched by key. Marks that kept their key and their order stay; the others are removed or changed. Replay starts from the last checkpoint before the first difference and only redraws the dirty tiles: those the removed and changed marks touched, plus the tiles a changed mark touches on its way. A tile a changed mark reaches that a later unchanged mark also touches is first restored from the checkpoint and caught up; a tile no later mark touches is already right. Unchanged marks are redrawn only where their footprint meets the dirty tiles, and only inside them (dabs outside are placed but not painted). The result is bit for bit a full replay; later checkpoints are remapped to the new positions and refreshed where tiles changed. If unchanged marks changed order, the cel replays in full.
+
+The editor keeps this record per paint cel. The CLI keeps the final tiles in `.cache/tiles/<cel>.raster` and the keys and footprints in `<cel>.marks`, so the first render after an edit updates the cached tiles the same way (without checkpoints). "Bake" turns a cel into plain pixels stored as compressed tiles and drops its strokes (later).
+
+## Brush engine
+
+- **Dabs.** A stroke's samples are interpolated along arc length and a dab is placed every `spacing x size` (the size at that point, taper included).
+- **Tip.** Procedural round (hardness), `chalk`, or a picture (`{"image": {"image": "<name>"}}`): six library pictures drawn in code (`bristle-flat`, `bristle-round`, `sponge`, `leaf`, `grass`, `splatter`) or a PNG the bundle carries in `brushes/images/<name>.png` (dark is paint, or its alpha when it has one), with roundness, rotation (fixed, follow direction, or tilt) and seeded jitter.
+- **Dual tip (M5).** A second tip stamped `count` times per dab at seeded offsets within `scatter` main radii, at `size` of the main tip and a seeded turn; the dab keeps the main tip's coverage only where the second one has paint (the most of its stamps).
+- **Texture (M5).** The grain is paper noise or a picture, at a `scale`, with a `contrast`, and `pressure` fills it in on a hard press; it stays fixed on the canvas.
+- **Colour dynamics (M5).** Per dab and per stroke hue, saturation and value jitter (seeded: the per-stroke offsets from the stroke's seed on a stream of their own, the per-dab ones drawn after the dab's other jitter, so brushes without colour dynamics replay exactly as before); colour from pressure (from the stroke's second colour at a light press to its colour at a full one) or along the stroke (to the second colour over `along` px). Strokes carry an optional second colour (stroke format 6, a flag bit, so strokes without it encode as before).
+- **Dynamics.** Size, flow and opacity each multiply curves of pressure, tilt (0 upright to 1 flat) and speed (0 to 1 at 5 px/ms). A curve is `min + (max - min) x input^gamma`.
+- **Taper.** Per stroke, by length and independent of pressure: the size eases (smoothstep) from 0 at the ends to full over the first `in` and last `out` px. Live painting can only taper the start; at pen up a tapered stroke is drawn once more with its length known, which is also what every replay does.
+- **Grain.** A canvas-space texture modulates dab alpha (paper tooth).
+- **Stroke buffer.** Dabs build up in an f32 coverage buffer towards a cap, the brush opacity times its opacity curve (flow vs opacity, as in Photoshop: one stroke never darkens itself past the cap, overlapping strokes do). The stroke then composites into the layer at the stroke's opacity with the brush's blend (normal, erase).
+- **Wet paint, smudge and blend (M5).** A brush's `paint` is `wet` (wetness, pickup, dilution), `smudge` (strength) or `blend` (strength). They read only the drawing they paint into (its pixels before the stroke, and the stroke's own work so far), never other layers. The stroke buffer gains a colour layer: per-dab colour (colour dynamics and wet pickup, weighted by the coverage each dab adds) or, for smudge and blend, the replaced pixels (smudge takes each pixel from where the dab was before, blend averages a ring around it at 0.3 of the radius); landing a stroke lays its per-pixel colour over the layer or moves the layer's pixels towards the replaced ones. Replay is in stroke order, so a reading stroke sees what was under it; a tile-local update rebuilds the drawing when a reading stroke comes after the first changed mark (a test checks an edit under a smudge against a full replay). Live painting reads the active drawing too, so what is drawn is what replays.
+- **Reshaping (M5).** A stroke's `path` can be set (`set`, `klad reshape`, A in the editor): every sample keeps its pressure, tilt and timing and moves to the same fraction of the new path's length as it had of the old one. The editor and `klad strokes --json` fit a few points to a stroke (`pathedit::fit_polyline`, the simplification `klad path` uses, at 0.12 of the stroke's size between 1 and 6 px); A edits those points and writes the bent path as one `set`.
+
+### Brushes as data
+
+A brush is JSON. The library is built in (`crates/core/brushes/library/`: `ink` inking pen, `pencil`, `marker`, `airbrush`, `soft`, `chalk`, `eraser`, and since M5 the painting set: `flat-bristle`, `round-bristle`, `sponge`, `fog`, `leaves`, `grass`, `splatter`, `wet`, `smudge`, `blender`, `dry-brush`, `two-tone`). The brush window (F5, `editor/brushwin.rs`) edits every setting with a live sample, draws with the edits at once (as a variant id, like the quick tuning), and saves a named brush into the bundle; pictures for tips and textures come in by path or by dropping a PNG on it. The brush fingerprint covers the bundle's pictures when it has any. A bundle embeds every brush its strokes use in `brushes/<id>.json` the first time a stroke with it is written, and from then on that file defines the id for that document, so changing the library never changes an existing render. Lookups go bundle first, then library.
+
+```json
+{
+ "format": "draw-anything-brush/1",
+ "name": "Every key, with example values",
+ "tip": { "round": { "hardness": 0.92 } },
+ "spacing": 0.04,
+ "roundness": 1,
+ "angle": { "fixed": 0 },
+ "flow": 1,
+ "opacity": 1,
+ "dynamics": {
+ "size": { "pressure": { "min": 0.06, "gamma": 1.5 } },
+ "flow": { "tilt": { "min": 1, "max": 0.6 } },
+ "opacity": { "speed": { "min": 1, "max": 0.8 } }
+ },
+ "jitter": { "size": 0, "angle": 0, "scatter": 0 },
+ "grain": { "paper": { "seed": 11, "feature": 2 }, "strength": 0.55 },
+ "blend": "normal",
+ "taper": [10, 24],
+ "stabilizer": 24,
+ "smoothing": 12
+}
+```
+
+- `tip` is `{"round": {"hardness"}}` or `{"chalk": {"seed"}}`; `angle` is `{"fixed": radians}`, `"follow"` or `"tilt"`; jitter angles are radians. Everything but `name`, `tip` and `spacing` has a default and is left out when it is the default.
+- `taper`, `stabilizer` (ms) and `smoothing` (ms) are defaults for new strokes and for recording; the stroke stores its own taper, so they never change a replay.
+- The editor's brush panel changes size, opacity and flow per stroke. Changing hardness or the size curve makes a variant: the same id when the bundle has no such brush yet, otherwise `<id>-<6 hex of its content>`, embedded with the first stroke.
+
+## Pixels and compositing
+
+- Tiles are 256x256, RGBA f16, premultiplied, sRGB encoded. Blending happens in sRGB space by default (what artists expect from Photoshop); a linear document setting comes later. A raster holds its tiles behind shared pointers and copies a tile only when it is written while shared (copy on write), so cloning a raster is cheap: background threads compose frames from the editor's drawings without copying them.
+- Layers are composited by Skia on F16 raster surfaces. A mask is applied by drawing the mask's cel with destination-out over the layer's content in an isolated layer. A clip group is an isolated layer holding the base's content; each clipped layer is drawn in its own isolated layer, cut to the base with destination-in (the base drawn again), and blended onto the group.
+- A layer with effects, or a clip group with an adjustment in it, is drawn into its own buffer covering the visible area plus the effects' reach (the tile path draws every raster tile that buffer touches), read back as f32, run through the effects and drawn back. Adjustments read and rewrite the pixels of the surface they are composed on, which is only allowed where nothing is isolated above it (a context flag says so); a group holding one gets a buffer of its own.
+- The editor caches the composite of everything below and above the active layer, so a dab only recomposites three images in the dirty region. When a layer above blends through (a blend other than normal, an adjustment, a glow that is not normal), the layers above are composed live over the cached below and the active layer instead of cached. While painting, dirty tiles widen by the reach of the effects on the active layer and the groups around it (other edits widen by the largest reach in the document), and every live preview tile in reach is handed to the compositor, so a glow on the layer being painted grows across tile edges as you paint.
+- **Planes on disk (M5).** The two cached composites are kept per frame and active layer in `.cache/planes` (1 GB budget, oldest out first), keyed by the frame's layer structure, the active layer, the onion plan and the pixel-cache key of every drawing in it, with the layers' thumbnails. A lean (heavy) scene that finds them loads only the active drawing's pixels (and its onion ghosts) and the other drawings' strokes and edit records from the pixel cache. Preparing frames writes them too, and the ruler's blue line counts a frame with planes and the active drawing cached as drawable.
+- Frame keys read a stroke file only when its size, time or inode changed (writes are atomic renames, so a rewrite always gets a new inode); an edit no longer clears them.
+- **Onion skin** (M3) is computed in `klad-render` (`onion`), one piece of code for the CLI, the editor's canvas and its frame cache. For a layer at a frame it lists the drawings before and after the current one: counted in drawings (the exposures before and after, each drawing once at its nearest distance, the current drawing and links to it skipped) or in frames (the drawings shown 1, 2, ... frames away). Opacity is `opacity x falloff^(distance - 1)` (defaults 0.5 and 0.6, 2 before and 2 after); those before are tinted red and those after green (`rgb x 0.25 + tint x alpha x 0.75`) unless the tint is off. In a looping range the count wraps around inside the range, so the last drawing of a cycle shows the first. The ghosts of a layer are composed (furthest first, f32 per pixel, on tiles in parallel, deterministic) into one raster, which the compositor draws right under that layer, outside its opacity, blend and mask; the ghosts of a clip group's layers go under the whole group. Hidden layers show none.
+- **Sheets** (M3): `klad render --sheet` lays frames out in a grid (columns about square, `--columns`), each cell the frame at `--cell` px on its longest side with its frame number, a `hold` mark when it looks exactly like the frame before, and per layer (top first, listed in the heading) the cel it shows: `c5` starts a drawing, `|c5` holds it, `c9>c1` a link, `.` blank. `--drawings` merges frames that look the same into one cell titled with their range. A clip's sheet is headed with the clip's name and its fps. Frames that look the same are composed once; drawings load in batches under 768 MB, so long sheets of big canvases stay in memory.
+- Export (`klad export`) renders the image, or one layer or group alone, at a frame, at a scale from 1/16 to 8, on transparency unless `--background`. Vector nodes are drawn at the export scale; paint rasters are resampled as whole images (Mitchell cubic up, mipmapped down). 8-bit PNGs are ordered-dithered (8x8 Bayer) from the f16 pixels, colour and alpha, so gradients do not band; values within an eighth of a level of an 8-bit value are written as that value, so flat colours stay flat. `--depth 16` writes 16-bit PNG. Working renders (`klad render`, `klad hash`) stay undithered so their hashes hold.
+
+## The agent interface: `klad` CLI
+
+Stateless: read the bundle, apply, write atomically, optionally render. Output is short text by default, `--json` for structure.
+
+| Command | Purpose |
+|---|---|
+| `klad new <bundle> [--width --height --layers --background --fps --frames --sketch]` | create (`--sketch` adds a vector layer named sketch on top); the editor's New makes bundles with the same code |
+| `klad ls <bundle> [--frame n] [--json]` | compact tree, top first: ids, kinds, names, contents, bounds, flags |
+| `klad show <bundle> <id>` | one layer, cel, node, stroke or fill (`<cel>:s<id>`) in full, with bounds |
+| `klad add / set / rm / mv` | single edits, all take `--render`, `--scale`, `--json` |
+| `klad apply <bundle> [--file]` | many edits from JSON lines, one transaction, one write, one render |
+| `klad stroke <bundle> <layer> --brush ink --path "M..." --pressure 0.2,1,0.1 [--taper 12,30] [--frame n]` | the agent paints: SVG path (several subpaths make several strokes) or `--points`; `--taper` defaults to the brush's; also a `stroke` op in `apply` |
+| `klad brushes [<bundle>] [--show id] [--json]` | the library and the brushes a bundle embeds, with where each comes from |
+| `klad strokes <bundle> <layer> [--frame n] [--json]` | stroke and fill list: address (`<cel>:s<id>`), author (human or agent), brush, samples, rate, pressure, tilt, bounds; fills with seed, reference, gap and pixels; JSON includes points and the order |
+| `klad transform <bundle> <cel>:s<id>... [--move dx,dy] [--rotate deg] [--scale k] [--sx --sy] [--flip h\|v] [--pivot x,y]` | move, turn, scale and flip strokes and fills; also a `transform` op. `transform` and `lasso` previews use the default size (their `--scale` scales the marks) |
+| `klad lasso <bundle> <layer> --polygon 'x,y ...' [--cut] [--move dx,dy] [--rotate deg] [--scale k] [--sx --sy] [--flip h\|v] [--pivot x,y] [--rm]` | without a move or `--rm` it lists the marks inside and crossing; otherwise one `lasso` op |
+| `klad add <bundle> mask --in <layer> [hide=true]` | give a layer a mask (prints its id); paint it with `klad stroke <bundle> <mask id>` |
+| `klad path <bundle> <node> [--move i x,y] [--nudge i,j dx,dy] [--handle i in\|out x,y] [--insert i,t] [--add x,y] [--rm i,j] [--corner i] [--smooth i] [--simplify px] [--convert]` | list the points of a path, rect or ellipse, or edit them; also a `path` op |
+| `klad fill <bundle> <layer> --at x,y [--ref this\|all\|<layer>] [--gap 4] [--tolerance 0.1] [--expand 2] [--color c]` | flood fill inside the lines; `--polygon 'x,y x,y ...'` for a lasso fill; also a `fill` op |
+| `klad refill <bundle> <layer> [--id n]` | recompute flood fills after the lines changed |
+| `klad palette <bundle> [--add '#..' --name n] [--rm key]` | the document palette; also a `palette` op |
+| `klad frames <bundle> [--from n --to n] [--json]` | the exposure sheet: a row per frame, a column per layer (top first), the cel id where a drawing starts (`c5*` for an in-between), `\|` while it shows, `c5->c1` for a link, `.` for blank, clips on the right |
+| `klad frame <bundle> insert\|remove <n> [--count c] [--layers l3,l5]` | insert or remove frames; a `frames` op |
+| `klad cel <bundle> new <layer> \| dup <cel> \| link <cel> \| unlink <cel> \| move <cel> [--frame n] [--hold h] [--insert]` | make, link and move drawings on the timeline; a `cel` op |
+| `klad duplicate <bundle> <layer>` | a copy of a layer with its drawings, links and mask, above it; a `duplicate` op |
+| `klad copy <bundle> <cel>:s<id>... --to <cel> \| --frame n [--layer l] [--move dx,dy] [--rotate] [--scale] [--sx --sy] [--flip h\|v] [--pivot] [--cut 'x,y ...']` | copy marks into another drawing; prints `c1:s3 -> c9:s12` for each; a `copy` op |
+| `klad retime <bundle> <from>-<to> --on n \| --fit n \| --reverse \| --pingpong [--layers]` | retime a range; a `retime` op |
+| `klad inbetween <bundle> --layers l3,l5 --from a --to b [--count n] [--spacing even\|in\|out\|in-out\|0.2,0.5] [--match id\|order\|near] [--pair s3=s7] [--unpaired leave\|pop\|fade\|draw-on] [--at t] [--force]`, `--from a --loop`, `klad inbetween <bundle> --redo [--layers] [--from --to] [--keep-drawn \| --force] [--only c12,c14] [--keep-cels c12] [--force-cels c14]` | make or remake in-betweens; lists pairs (by part first), touching ends kept, unpaired marks, fills left out and the time per frame |
+| `klad part <bundle> <cel>:s<id>... --name leaf` | name marks as a part (`--name ''` takes them out); `--part` on stroke, fill, ink, hatch and scatter; `klad strokes` shows each mark's part |
+| `klad arcs <bundle> --track c4:s12\|leaf\|lines:leaf\|x,y ... [--clip walk \| --from --to] [--ground y[,y]] [--travel px] [--slack 2] [--json] [--check]` | positions per frame, distance moved, lowest points; with `--ground` under the ground and slides, with two tracks swaps; `--check` fails on any of them |
+| `klad ink <bundle> <layer> --from <node>,... \| --path "M..." [--weight 6] [--light x,y] [--break 60] [--gap] [--wobble 0.6] [--taper in,out] [--brush] [--color] [--hand 1]` | ink the outlines of shapes as tapered strokes with weight rules, each drawn like a hand |
+| `klad light <bundle> --from <node>,... [--light x,y] [--shade <layer>] [--rim <layer>] [--depth 14] [--soft 3] [--rim-width 4] [--lamp x,y,h]` | shade and rim fills from one light direction, or per shape away from a lamp |
+| `klad hatch <bundle> <layer> --in <node>,... [--angle 30 \| --along] [--spacing 6] [--length 12-30] [--jitter] [--weight] [--hand 1]` | short tapered strokes inside closed shapes, each drawn like a hand |
+| `klad paint <bundle> <layer> --in <node>,... [--color] [--form round\|flat\|cylinder] [--axis 90] [--facing x,y,z] [--light x,y] [--elevation 0.6] [--lamp x,y,h] [--key] [--fill] [--bounce] [--core 0.35] [--weight 14] [--brush oil] [--bold oil-load] [--decisive 1] [--hand 1]` | paints each shape as a form: a height field from its outline (round), a plane or a cylinder, lit by a key light or lamp with fill, bounce and a core; strokes follow bands of equal light, take their colour from the model and stop where the light changes; big to small, then decisive strokes in the lights |
+| `klad prepare <bundle> [--from] [--to]` | replay the painted drawings of a span of frames into the cache |
+| `klad scatter <bundle> <layer> --in <node>,... [--mark "M..."] [--count n \| --spacing 14] [--size 0.7-1.2] [--turn -15,15] [--avoid <node>,...] [--hand 1]` | copies of a small mark inside closed shapes |
+| `klad fill <bundle> <layer> --shape <node> [--expand 2]` | fill exactly a shape's area |
+| `klad fill <bundle> <layer> --like <cel> [--frames all\|a-b\|clip]` | carry a drawing's flood fills to the layer's other drawings |
+| `klad gaps <bundle> <layer> [--frame n \| --sheet all\|a-b\|clip] [--ref] [--gap] [--min 12] [--render] [--json]` | closed regions no fill covers, with bounds; a render marking them for each frame that has any |
+| `klad timeline <bundle> [--fps n] [--frames n] [--origin x,y\|centre]` | show the timeline (fps, length, origin, Godot folder, clips) or set fps, length and origin; a `timeline` op |
+| `klad clip <bundle> [--add name --from a --to b [--loop] [--fps n]] [--set name [--name new] [--from] [--to] [--loop\|--no-loop] [--fps n\|doc]] [--rm name] [--json]` | list, add, change, rename and remove clips; a `clip` op |
+| `klad render <bundle> [--frame n] [--focus id] [--scale s] [--region] [--overlay ids,bbox,grid,onion,parts,arcs] [--track ...] [--depth n]` | PNG, prints the path, and size, pixel hash and timing on stderr. `--focus` zooms to a layer, cel or node; overlays label boxes with ids. Onion: `--onion 2,2` (before, after), `--onion-by drawings\|frames`, `--onion-layers l3,lines` (default: every layer with more than one drawing), `--no-tint`, `--onion-loop 0-7` (wrap inside a loop); any of them turns the onion overlay on |
+| `klad render <bundle> --sheet all\|0-11\|<clip> [--drawings] [--cell 256] [--columns n] [--overlay onion,parts,arcs ...] [--track ...]` | many frames in one labelled grid (see Sheets); arcs span the sheet, each cell ringing its own frame |
+| `klad selection <bundle>` / `klad notes <bundle>` | what the human selected or pinned |
+| `klad log` / `undo` / `redo` / `diff [--step n]` | shared history of CLI and editor changes, before and after renders side by side |
+| `klad export <bundle> [--layer id] [--frame n] [--scale s] [--depth 8\|16] [--background] [-o out]` | PNG of the image or a layer or group |
+| `klad export <bundle> --sheet all\|<clip>\|0-11 [--scale s] [--padding 2] [--max 4096] [--depth] [--layer] [-o out.png]` | sprite sheet pages and Aseprite array JSON (see Exports) |
+| `klad export <bundle> --frames all\|<clip>\|0-11 [--scale s] [-o dir]` | numbered full-size PNGs, one per frame (`run-0000.png`, ...) |
+| `klad export <bundle> --godot [dir] [--store] [--scale s]` | the sheet, a `SpriteFrames` `.tres` and an `AnimatedSprite2D` `.tscn` (see Exports) |
+| `klad hash <bundle> [--frame n] [--all]` | pixel hash for the parity check; `--all` one line per frame |
+| `klad open [bundle]` | the editor (macOS); without a bundle, the start window: New, Open (the macOS open panel or a pasted path), Recent with thumbnails |
+
+Scripts are any language that prints edit ops as JSON lines into `klad apply`. Generators that should stay editable (scatter, repeat, symmetry) are built-in vector node kinds with parameters.
+
+`--sheet run` renders every frame of clip `run` in one grid with frame numbers, drawing ids and holds, so an agent sees a whole animation in one image.
+
+## The editor
+
+- Canvas: pan, zoom, rotate; pen pressure, tilt and eraser end; 120 Hz on Apple Silicon. The window around the canvas is a neutral grey (`theme::SURROUND`), so colours read true.
+- Layout (M4 batch 1): a tool strip on the left (the tools with their key letter, undo and redo, and at its foot settings, numbers and the command palette); a dock on the right holding panes (colour and brush, layers, inspector, notes for the agent, history), each with a title row that folds it, closes it and, dragged at its top edge, resizes the pane above; the timeline along the bottom, resizable and foldable to its toolbar; a status line under everything. Panes share the dock's height: they keep the sizes the user gave them, the last open one takes what is left, and when they do not fit they shrink towards their minimums and scroll inside (`layout::Layout::bodies`). Tab hides every panel but the status line, shift Tab the dock. Which panels are open, the dock's width, the timeline's height and each pane's size are kept in the user's settings (`layout`) and restored, clamped to the window. Pen calibration lives in the settings window (cmd ,); the performance numbers in a numbers window that can stay open over the canvas.
+- Commands (M4 batch 1): every editor action is a `Cmd` in one list (`commands.rs`): an id (`tool.brush`, `drawing.new`, kept in settings), a name in plain words, a Phosphor icon, a group, its keys or the hold that triggers it, whether a held key repeats it, and a line on what it does. Keys, the strip, panel buttons, the timeline's buttons and context menu, and the palette all run commands through `Editor::invoke`, which first asks `can_run` (a reason when it cannot, shown as a refusal) and remembers the last twelve run. A key matches only with exactly its modifiers (shift K is not K); key repeats run commands that repeat (`=`, `[`, cmd Z) and frame steps only once the frame on screen caught up. cmd K opens the palette: type to filter (name start, then a key, a word, a substring, the letters in order, the group; hyphens ignored, so "inb" finds in-between), arrows and Return run, rows grey out with the reason, recent commands first; `?` opens it too. Every control has a hover hint after 0.35 s (from its command where there is one) and is at least 24 pt high; a test walks every control of every panel and window to keep it so.
+- Tool options and selections (M4 batch 2): a bar over the canvas holds the active tool's settings (brush: picker, size, opacity, flow, and a "more" menu for hardness, lightest size, curve, taper, stabiliser and smoothing; fill: reference, gap, tolerance, grow, opacity; strokes: cut at the lasso edge, select all; points: corner, smooth, simplify, make it a path). The strip shows the eraser while the eraser brush or the pen's eraser end is on, and two colours (the current one over the second; X or a click swaps them; picking a colour from a swatch, the hex field or the eyedropper makes the old one the second). cmd alt drag sideways on the canvas sizes the brush (doubling every 120 pt), the circle staying where the drag began. H flips the view left-right (the view's mappings and the GPU matrix mirror; the document does not change); the status line's zoom takes a click for 100% and a double-click to fit, its rotation a click to turn upright. A selection bar sits under (or over) the selection's box: for strokes flips, quarter turns, recolour, thinner, thicker, opacity, copy, paste, duplicate in place, delete, deselect; for a shape flips (sx or sy negated and its rotation mirrored), quarter turns, duplicate in place (an `add` of the node without ids, above it), delete, deselect; for points corner, smooth, nudges, delete. Arrows nudge strokes, a shape or points by 1 px, 10 px with shift. Strokes select across layers (M5 batch 2 round 1): cmd or shift click on rows in the layers panel adds paint layers to the active one (marked with a blue edge); S then lassos, clicks and selects all on all of them, and the selection (one part per layer) moves, turns, scales, flips, recolours, cuts at the lasso edge, copies and deletes as one edit, each layer's marks staying on their layer. A selection on several layers drags as its outline (no GPU lift) and lands on release; copies of several layers paste back into their own layers, a copy of one layer into the active one. The strip's panels button lists the five panels and the timeline with a tick each, so a closed panel always has a way back. U draws rectangles and ellipses on a vector layer (shift for a square or circle, alt from the centre, rounded corners for rectangles; fill, outline and width shared with the pen, the fill in the first colour and the outline in the second, as for the pen's paths) as `rect` and `ellipse` nodes. Mirror painting (the brush bar's "mirror" and its axis) paints every stroke's mirror image as it is drawn, in a second stroke buffer landed after the first, and commits both as plain marks in one history step. Handles are drawn at 12 pt and hit within 12 pt (`grab`); shapes whose rotation is a quarter turn get edge handles too (`lift::stretched` scales their own axis). Pen events that arrive while a shape move or point edit is being written are held and replayed in order after it. The colour and brush pane shows the palette (swatches drag to reorder; the x in a hovered swatch's corner, or a right-click, removes it), recent colours, size presets and the brushes as tiles, each with a sample stroke drawn by `klad-brush` once per brush definition.
+- Messages and jobs (M4 batch 1): every result, refusal and error goes through `Editor::say` with a tone (info, done, refused, error). Done and refused messages show for 3.5 and 6 s as a toast next to the pointer where the user acted (jobs' messages at the bottom right), errors until dismissed, info only in the status line; the status line shows the latest message (a click opens the message log, the last 200 with times), the frame, where the next stroke goes ("draws into c12 on lines, frames 4 to 7"), running jobs with a cancel button, slow internal work (preparing a selection, drawing an edited path, loading a frame), zoom and rotation. Times that used to be status text (stroke, fill, edit, undo, sync, frame step, last play, last job) are kept by name for the numbers window. Background jobs (in-betweens, Godot export) run the same `klad` binary through one job list (`jobs.rs`); when the CLI exits with code 75 (the document changed while it computed) the job runs again, up to three times, so an edit made in the editor meanwhile is never overwritten.
+- Tools: brush, eraser, smudge, fill (inside lines, gap closing), lasso select and transform, move/rotate/scale handles, path point editing, eyedropper.
+- Stroke select (S, M2): click picks the topmost stroke or fill on the active paint layer under the pointer, a dragged loop picks every stroke whose samples are all inside it and every fill whose pixels are, shift adds or toggles. With "a lasso cuts strokes at its edge" (on by default) the loop also takes the parts of strokes and fills crossing it: the selection shows the dashed lasso and the parts that will move, and the first edit (move, recolour, delete, ...) writes one `lasso` op that splits them, after which the selection is the moved marks. The selection shows as thin lines and a box with corner handles (uniform scale), edge handles (stretch one axis; dragging past the other edge flips) and a rotate knob; dragging moves it on the GPU (the selected marks drawn alone, over the cel replayed without them) and release writes one `transform` or `lasso` op. The inspector recolours (the current colour), makes thinner or thicker, sets opacity, flips left-right or up-down and deletes, each as one history step. The selection is shared with the agent as addresses.
+- Layers (M2 batch 4): the inspector sets clip to the layer below and lock alpha, adds a mask (empty, or hiding all), turns it on and off, removes it, and "paint on the mask" makes the mask the active layer (it also has its own row under its layer). Painting on a mask hides the layer under the strokes; the eraser shows it again. While a mask is active, what it hides is tinted red ("show the mask in red", on by default), and the brush panel says whether the brush or the eraser is on. The brush and fill tools record lock alpha from the active layer.
+- Live previews and clipping: the editor composes the active layer between cached images of everything below and above it only when that is exact (the active layer and the groups around it are not clipped, masked or a clip base); otherwise each dirty tile composes the whole stack. The GPU lift of a dragged shape or of selected strokes falls back to the outline (the result appears on release) when the dragged layer is clipped, masked or a clip base, when a group around it is, when a layer above it uses overlay, or when a lock-alpha mark lies at or after the first selected mark in its cel. Clip groups above the dragged layer stay live: they compose as one plane with the base's blend.
+- Direct select (A, M2): click a path, rect or ellipse (inside groups too) to show its points; clicking the selected shape again steps down to the next shape under the pointer, and the inspector lists them all; click or shift click points, drag on empty canvas for a box; drag points or handles; alt click the outline adds a point, alt click a point toggles corner and smooth, alt drag a handle breaks it; delete removes points; the inspector has corner, smooth, delete points, simplify and "make it a path". While dragging, the edited outline is drawn live; on release the edit is one `path` op whose layer is rendered in the background, then swapped in.
+- Select and move (V, M4 test): a press picks what is under the pen and drags it at once: a stroke or fill on the active paint layer first, then a vector shape (clicking a shape again steps to the one under it), then the topmost visible, unlocked paint layer with a mark there, which becomes the active layer. A stroke picked this way is the same selection as S makes (its bar, inspector, nudges, delete, copy), so V is the one tool for "move this". A press on empty canvas lassoes strokes on the active layer. Alt drag drags a copy: the copy is made (duplicate in place, one step) when the drag first moves, and the drag moves the copy (two history steps). A, the point editor, says so when a click lands on a brush stroke: strokes are samples, not paths.
+- Pen (P, M4 test): draws vector paths on a vector layer: a click places a corner, a drag pulls out symmetric handles, a click on the first point closes the path, Return finishes it open, Esc drops it, and another tool finishes it. The path is one `add` node op into the layer at the current frame, in the current colour: closed paths are filled (unless "fill" is off) and outlined (unless "outline" is off), open ones always outlined, at the width in the options bar. On other layers it refuses and says why; the brush says so on a vector layer.
+- Colour (M2): a hue ring with a saturation and value square, hex, alpha; the document palette as swatches (click picks, right-click removes, "add colour" adds the current one with an optional name, all as ops); the last 16 colours used, kept in the user's settings. Alt-click with the brush or fill tool picks the colour of the image under the pointer, shift alt-click that of the active layer.
+- Fill tool (G, M2): click fills inside the lines of this layer, all visible layers or a chosen layer, with gap, tolerance, expand and opacity settings; drag a loop to lasso fill.
+- Inspector gradients (M2): a shape's fill switches between none, solid, linear and radial; gradients edit their geometry and stops (position, colour, add, remove).
+- Canvas mipmaps (M2): every uploaded tile brings its own mip chain (box filtered on the CPU, down to one pixel per tile), so zoomed-out views sample trilinearly instead of shimmering.
+- Frames (M3): the canvas, painting, fills (their reference at that frame), selection, lifts, notes and the shared selection all work at the current frame. Painting paints into the drawing exposed there (on a link into its source, which the timeline says), and painting on a blank frame starts a drawing there. `,` and `.` step a frame, alt `,` and alt `.` jump to the previous and next drawing on the active layer, Home and End go to the first and last frame. The scene keeps drawings loaded across frames, so going back to a frame only recomposes it; a frame with drawings not loaded yet loads in a background frame job while the last frame stays on screen (drawings a job loaded before the document changed are not kept, and load again when needed; see the frame cache below). Drawings away from the current frame drop their replay checkpoints, and beyond 1 GB the least recently shown are evicted; a drawing changed from outside while it is not shown is evicted and reloads when its frame comes back.
+- Timeline panel (M3), along the bottom: a frame ruler with the playhead, one row per layer top first (groups fold, a mask row opens under its layer with `[m+]`), each cel a block across its exposure (drawings blue or green for vector, links purple marked `->c1`), blanks empty. Click a cell to go to that frame and layer; drag on the ruler or on empty cells to scrub; drag the right end of a block to change its exposure (later cels of the layer move); drag a block by its first frame to move it. Buttons, the context menu and keys: new drawing (K), duplicate to the next frame (the copy is placed after the exposure, later cels move back), show a drawing here (a link, picked from the layer's drawings), unlink, delete, hold longer and shorter (`=` and `-`), insert a frame (I, shift for every layer) and remove one, fps and length fields, "+ paint" and "+ vector" layers. Every action is one op and one history step. A row of playback controls sits above the buttons: play, the loop range (drawn orange on the ruler), onion skin and its settings, the shift K exposure, and the dropped frames of the last play; each layer name has an onion dot at its right end.
+- Onion skin (M3): O turns it on and off; "onion settings" in the timeline sets before and after, drawings or frames, opacity, falloff and tint; the dot at the right of a layer's name in the timeline shows that layer's onion too (the active layer always shows its own while onion is on). The scene composes the onion rasters (the same `klad-render` code as `--overlay onion`) when the frame, the active layer, a marked layer, the settings or a drawing they show change, and loads the drawings they need with the frame. The active layer's onion is part of the cached image of everything below it, so painting with onion on composes exactly what it composes without; marked layers' onions are drawn inside the below and above caches. The eyedropper and fills never see the onion.
+- Frame cache and stepping (M3): the frame shown is the scene's frame (painting, the timeline and the agent channel all use it), and moving to a frame only sets it. What the canvas plane (the live, tiled GPU texture) shows catches up separately: at once when the frame's drawings are loaded and no cached picture of it exists, else 150 ms after the last step, or immediately when the pen touches the canvas. Meanwhile the frame cache shows the frame: one GPU texture per distinct picture (8-bit, premultiplied, with a CPU-made mip chain), at display resolution (the power-of-two level that the zoom needs, full size at 100% and closer), keyed by a hash of everything the picture depends on (the layer tree at that frame, the version of every drawing it shows: stroke file hashes and node hashes, the onion's ghosts when onion is on, the brushes and the level). Holds and links share a key, so they share a texture. A picture is composed by a background job that loads the drawings it is missing (kept in the scene afterwards, under the 1 GB drawing budget) and composes all tiles; at most two jobs run, plus one for the frame you just moved to. After a step the next 4 frames in that direction are composed ahead. The cache is capped at 640 MB, least recently shown first out; after every change the pictures no frame's key names any more are dropped, so an edit costs only the frames it changes. While the frame you stepped to is not on screen yet, held-key repeats are ignored (a fresh press still counts), so a held `.` shows every frame. While a mask is active with its red tint, frames are not cached.
+- Heavy documents (M4 test): nothing that grows with the document runs on the UI thread. Catching the canvas up (loading the frame's drawings, the onion, and the caches of everything below and above the active layer) is a background job (`Scene::canvas_request`, `CanvasRequest::run`, `Scene::adopt`): one runs at a time, a result for a frame, active layer, revision or onion that is no longer wanted keeps only the drawings it loaded, and the next is asked for. The editor opens with nothing loaded and waits for the first job at most 400 ms; a pen press on a frame that is not ready waits at most 60 ms, then says the frame is still loading and draws nothing; clicking a layer or changing the onion only marks the canvas stale. After a catch-up the canvas tiles are composed and uploaded 64 per frame while the frame's picture stays on screen. Background work runs in its own thread pool with one core fewer than the machine has. Only the active drawing keeps replay checkpoints. A document whose frame loads more than 512 MB of drawings is heavy: it runs one picture job at a time, no prefetch, and loads the frame you stop on through the canvas job alone. Drawings evicted from memory are freed on a background thread.
+- Caches on disk for heavy documents (M4 test, round 2): three layers of cache, all automatic and all thrown away safely (`.cache/` is never in git).
+ - Pixels per drawing (`klad_brush::cache`, `.cache/tiles`): the replayed raster (zstd) and its edit record (each mark's key and the tiles it touches), keyed by the stroke file, the brushes, the canvas size and the engine version, shared by the CLI and the editor. A hit rebuilds the drawing's replay without painting anything (`CelReplay::with_marks`); a drawing whose file changed replays only its changed marks from the record. The CLI writes it after every load, as it always did; the editor writes it after a replay of 30 ms or more, so small drawings never touch the disk. 2 GB per bundle, least recently used out first.
+ - Frame pictures (`.cache/frames`, one file per frame cache key, zstd of the 8-bit picture at its display level, mips rebuilt on load): written after a picture that took 30 ms or more to make, read instead of loading a frame's drawings. The canvas job writes the picture of the frame it prepares (in the background pool, from the rasters it already holds), so on a heavy document every frame you stop on is seen at once next time. Heavy documents ask for a picture of a frame, and prefetch, only when it is on disk. 1 GB per bundle.
+ - Lean scenes: in a heavy document, once the canvas job has made the caches below and above the active layer, the other layers' pixels on the current frame are dropped (their strokes stay, so V still picks them). A drawing counts as loaded only with its pixels, so pictures and canvas jobs reload what they need from the disk cache. Edits on the active drawing never need the others (the caches below and above stand); an edit that would (a change on another layer, a vector or onion change, a structure change, a clip that makes the stack slow) marks the canvas stale and the canvas job redoes it. The eyedropper samples what is on screen, a fill that references other layers loads them from the disk cache first, the GPU lift falls back to the outline drag, and the canvas job hands over thumbnails before the pixels go.
+ - Buffered frames and prepare (round 3, `editor/buffer.rs`): a strip along the top of the ruler shows, per frame, green when its picture is buffered (in the frame cache or on disk: it shows at once) and blue under it when its drawings are cached (every paint drawing of the frame holds its pixels in memory or a current pixel cache on disk: drawing there starts within seconds). A background survey works it out (stat of each picture file, the first 8 bytes of each drawing's cache file against the key of its stroke file, stroke files hashed again only when their size or time changed) whenever the revision, display level, onion, frame cache, held drawings or a disk write changes. "Prepare frames" (the lightning in the timeline header, or cmd K) buffers the loop range, else the clip under the playhead, else every frame, one frame at a time on a background thread (frames sharing a picture once): it loads each drawing through the pixel cache (writing it), makes the picture at the current display level and writes it, skips what is already there, keeps nothing in memory, shows its progress next to the button and in the status line, and stops after the current frame when pressed again. The skipped frames count; the summary says how many pictures and drawings were made.
+ - Container numbers on `klad stress --frames 12` at 4096 px (30 layers of 300 strokes): a frame never seen is ready to draw on after 8.5 to 10 s (the replay, now also writing the caches); after reopening, a frame seen before is on screen in 12 to 45 ms and ready to draw on in about 3 s (30 drawings from the disk cache, then the caches below and above); drawings in memory 450 to 680 MB, down from 3.3 to 6 GB; UI frames while loading median 3.4 ms, p95 8 ms, slowest 62 to 88 ms.
+- Clips (M3 batch 3): a strip above the frame numbers shows each clip as a bar (teal when it loops, amber when it plays once, with its name and its own fps), overlapping clips in lanes. Drag along empty strip to make a clip (named `clip1`, `clip2`, ..., looping, at the document's fps); click a bar to pick it; drag a bar's end to move that end. The row under the playback controls edits the picked clip, or the one under the playhead: name, loops, own fps, delete. Each change is one `clip` op and one history step. Clip edits change no pixels, so the frame cache keeps every picture.
+- Playback (M3): Return plays and stops. It plays the range marked on the ruler when there is one (shift drag on the ruler, or the "loop range" fields), else the clip under the playhead (the picked clip first when it holds the playhead) at that clip's fps, looping or once (a clip that plays once stops on its last frame; from its last frame it starts over), else the whole timeline at the document's fps. A clock started at play time picks the frame from the elapsed time (`floor(t x fps)`), so playback never drifts; a frame whose picture is not ready yet is skipped and counted, and the timeline shows the dropped frames per loop. Playback shows pictures without onion, composes the loop ahead in the background and ends on the frame on screen. A pen touch on the canvas stops it.
+- Frame by frame (M3): shift K makes a new drawing right after the current exposure, on ones, twos or threes (the "shift K exposes on" setting), and moves there: an open-ended last drawing first gets a hold that ends where the new one starts, later drawings move back when the new one needs the room, and the timeline grows at the end. Holding Q and moving the pointer sideways flips through the frames around the one where Q went down (one frame per 22 px), from the frame cache; letting go stays there. Holding W shows the previous drawing of the active layer (the whole frame where it starts; in a loop range the first drawing's previous is the range's last) and letting go comes back. While Q or W is held the pen does not paint.
+- Copy and paste (M3 batch 4): with the stroke tool (S), cmd C keeps the selected marks (with a cut lasso, every mark inside or crossing it, copied with that cut, so only the parts inside show; marks shift-added outside it whole) and puts a line of text on the system clipboard, because egui reports cmd V only when the clipboard holds something. cmd V (any tool) copies them into the active paint layer's drawing at the current frame (on a link, its source; on an empty frame, a new drawing), in place, as one history step (one or two `copy` ops in one batch), then selects the copies with S.
+- Timeline selection (M3 batch 4): shift click a cell to select from the playhead's cell (or the selection's first corner) to it, or shift drag over cells; the selection is a rectangle of frames over rows, drawn white. A click without shift or Esc clears it. Its context menu retimes it (on ones, twos or threes, fit into n frames, reverse, ping-pong, on the selected rows or on every layer) as one `retime` op, and makes in-betweens: the keys are the first row's drawing at the first selected frame and the last drawing starting inside the selection; count (or one per frame), spacing and pairing are menu fields. In-betweens, and "redo the in-betweens in the selection", run `klad inbetween` as a background process of the same binary, like "export to Godot", and the editor reloads when it ends. In-between cels show lighter, their id starred.
+- Layers (M4 batch 3): one layer row (`editor/layers.rs`) is drawn by the layers pane and by the timeline's names column: eye, lock, the kind icon, the name (double-click renames it in that row; Return keeps, Esc leaves), clip and lock alpha marks, a mask chip (click paints on the mask, alt click turns it on or off, right-click opens its row in the timeline), in the timeline the onion dot and a fold caret on groups, in the pane a 40 by 28 thumbnail of the layer at the current frame (box filtered from its tiles, alpha boosted by a square root so thin ink still shows, cached per drawing and document revision, made by a background job: a row shows its last thumbnail until the new one is ready). Dragging a row moves the layer: the top or bottom half of a row puts it above or below, the middle half of a group puts it inside (the row lights up), and a mask, a group into itself or a drop beside a mask is refused with the reason (`drop_at`); the drop is one `mv` op. The pane's buttons: new paint, vector or group layer above the active one, duplicate (the copy becomes active), put in a new group, delete; the active layer's opacity and blend sit in the pane's title row. Each is one history step.
+- Timeline layout and drags (M4 batch 3): the header is one toolbar row (fold, a frame field, transport, loop range and its fields, onion and its settings, shift K exposure, fps, length, zoom). Under it the selection toolbar (`editor/cells.rs`): new drawing, duplicate, link (the layer's drawings as thumbnails), unlink, delete, hold shorter, the hold as a field, hold longer, insert and remove a frame on this layer or every layer, copy cells, paste cells as copies or as links, retime (a menu: on ones, twos, threes, fit into n, reverse, ping-pong, every layer), in-between, redo in-betweens, new clip. What a press on the grid starts is decided where the press began (`press_at` and `drag_of`, tested): on the ruler it scrubs (shift marks the loop range), near a block's end it changes the hold, on the dot of a block's first cell it moves the block (the cursor is a hand there; since the M4 test only the dot, so a drag from the rest of that cell selects), on any other cell it selects (dragging extends over frames and rows). A hold drag or a move draws the block itself at its new length or place (the moved one faded where it was), not an outline; block labels stop before the grip lines at the block's end. A moved block is a `cel` `move` op, so drawings it lands on are pushed along; alt left and right move the drawing under the playhead by a frame. Clicking a clip's bar opens the clip window (name, loops, own fps, first and last frame as fields, delete, the Godot folder and export). Copied cells are the drawings and holds of the selected rows and frames (or the drawing under the playhead), pasted at the playhead on their own layers as `cel` `dup` or `link` ops in one batch; a drawing that was a link stays a link.
+- In-between panel (M4 batch 4, `editor/between.rs`): "in-between" (the selection toolbar, the context menu, cmd K) opens a window instead of a menu: the first selected row's two keys as thumbnails with their frames (a frame not loaded yet says so), one on every frame or a count, spacing with the chart an animator draws between keys (key ticks at the ends, a tick per in-between where the spacing puts it), pairing (id, order, nearest shape; parts both keys have are named, they pair first), marks in one key only (leave, pop, fade, draw-on), and "make the in-betweens", which runs `klad inbetween` as a job (`between::args`). When the job ends its output is parsed into rows (`between::report`): each layer's pairs, parts and touching ends; an unpaired mark is a button that goes to the other key's frame, turns on the stroke tool and waits for one stroke to be picked, then makes the in-betweens again with that pair added to `--pair` (`pair_from`); a fill left out goes to its frame. "Check what a redo would remake" lists the in-betweens of the selection (or all) with their state from their marks' hash and authors (`redo_rows`): remade, drawn on by hand (keep them on top, the default; in-between them too; leave it) or edited (in-between it again, or leave it, the default); "redo them" runs one `klad inbetween --redo --only ... --keep-cels ... --force-cels ...`, one history step.
+- History (M4 batch 4, `editor/history.rs`): the History pane lists the redo stack (as "undone" with who made the step, farthest first), a "the document is here" marker and the undo stack, latest first: who (you for the editor, the agent for the CLI), what, how long ago. Clicking a row undoes or redoes as many steps as it takes to stand right after it (`steps_to`), timed in the status line. The list is read again when the document's revision changes.
+- Notes on the canvas (M4 batch 4, `editor/pins.rs`): every open note is a pin, those of other frames dimmed with their frame, done ones on this frame checked in green. With the note tool a click on a pin opens its popover (the text to edit and save, done, remove, close); elsewhere it opens a popover for a new note at that spot ("pin it"). A right click on any pin, of this frame or a dimmed one of another, goes to its frame and selects it (an accent ring and its popover); Delete removes the selected note. The Notes pane lists the open notes (a click goes to the frame and opens the pin) and the done ones folded, each can be opened again. The editor watches `.cache/notes.json`, so the agent's `klad notes --done` shows at once.
+- Settings (M4 batch 4, `settings.rs`, `editor/prefs.rs`): the settings file carries a `version` (2; files without one, the M1 to M4 ones, load with the new fields at their defaults and are stamped 2), `keys` (command id to key labels such as `shift D`, only the changed ones), `uiScale` (0.75 to 2, egui's zoom factor, so every control grows with it) and `defaults` (brush and size for new windows, the shift K exposure, onion before, after and opacity, the grey around the canvas). The window has pen calibration, defaults, keys (search, change by pressing the key, no key, reset one or all) and layout. `commands::Bindings` holds the keys: a changed command's keys replace its first ones, a key another command already uses is refused and that command named (`taken_by`), holds (Q, W, space) keep their keys, and every key lookup (dispatch, hints, the palette, the strip's letters) goes through it.
+- Export to Godot (M3 batch 3): the clip row has a "Godot folder" field (the document's `export.godot`; a typed folder is relative to the folder holding the bundle) and an "export to Godot" button, which runs `klad export <bundle> --godot` (with the typed folder and `--store` when it differs) as a background job of the same binary, so the CLI and the editor write the same files; its summary or error is a message.
+- Agent channel: the current selection and pinned notes are written to `.cache/selection.json` and `.cache/notes.json` for `klad selection` and `klad notes`; both carry the frame.
+- Vector layers are rasterised into tiles when opened and when their nodes change; per-tile composition then only draws one tile per layer.
+
+## History
+
+Every change, from the CLI or the editor, first stores a history entry in `.cache/history/undo/<seq>/`: `meta.json` (author, summary, revision, the stroke files it touches), `patch.json.zst` (the change to `doc.json`) and `files/` (the stroke files it is about to change, zstd). The patch is a list of changes found by comparing the document before and after: object keys that differ (`{"at": "/layers/3/cels/0/nodes/17", "old": {"x": 10}, "new": {"x": 35}}`, null meaning absent) and list splices where items were added, removed or moved (`"index"`, the removed and the inserted items). Lists are compared by common prefix and suffix; when the middle has the same items by id and type, the comparison goes into each of them, so a node edit in an 18,000-node document is one small change. `undo` checks that every changed key and item is still what the step left (otherwise it stops with "the document no longer matches it" and changes nothing), applies the old values in place, restores the stroke files, writes the document as a new revision and moves the reversed patch to the redo stack; any new change clears redo. An undone or redone step keeps the author and time of the change it records (since the M4 test; before that an undo wrote the undoer, so the agent's step became the user's once undone and redone). The last 100 steps are kept. Entries from before M2 batch 3 hold a whole `doc.json` snapshot and still undo. The editor syncs only the cels a node-level patch touches.
+
+## Sync between CLI and editor
+
+The agent may run in a Linux container while the editor runs on the macOS host, sharing the folder through a bind mount.
+
+- Every change is an op appended to the op log in `.cache/`, with the author and `rev`.
+- Writers write files atomically (temp file plus rename) and bump `rev`.
+- Before a CLI edit writes, it checks that `doc.json` on disk still has the `rev` it loaded (`Bundle::ensure_unchanged`, reading only the head of the file); when another writer got there first it writes nothing, says "the document changed while this edit was being made", and exits with code 75. Edits computed before the transaction (in-betweens, fills like another drawing) are the ones with a real window; the editor's job list runs them again. `DRAW_TEST_WRITE_DELAY_MS` makes the CLI wait that long before its check, for the test that edits in the middle.
+- The editor watches the bundle. When `rev` moves past its own, it applies the new ops from the log to its in-memory document.
+- Undo and redo work on the shared log, so the human can undo an agent edit and the other way round.
+- M0 verifies file events and atomic renames across the OrbStack mount in both directions.
+
+## Exports
+
+- PNG of the image, a layer or a group at a frame, at any scale from 1/16 to 8, transparent (see Pixels and compositing).
+- **Animations** (M3 batch 3) take a spec: `all` (every clip, or the whole timeline as one animation `default` when there are no clips), a clip name, or a range `a-b`. Each frame of them is rendered as in a PNG export (scale, depth, `--layer`, `--background`); frames showing the same drawings are composed once, and pictures with identical pixels (after dithering) are kept once, so holds, links and repeats share a picture. A picture is trimmed to its pixels with alpha (an empty one keeps one transparent pixel). An animation is a list of exposures: runs of consecutive frames showing the same picture, each with its length in frames and its duration in ms at the animation's fps, rounded so that the durations add up to the animation's length (`round(end x 1000 / fps) - round(start x 1000 / fps)`).
+- **Sprite sheets** (`--sheet`): pictures in order of first appearance are packed in rows (shelves) with `--padding` px around each, at the width among a few candidates that gives the most compact last page, starting another page when the next row would pass `--max`. Pages are `<name>.png`, `<name>-2.png`, ...; a re-export removes pages it no longer needs. The JSON (`<name>.json`) is Aseprite's array layout: `frames` lists the exposures of each animation in turn (`filename` `"<clip> <frame>"`, `frame` the rect in the page, `trimmed`, `spriteSourceSize` the trim, `sourceSize`, `duration` in ms, and `image` when the page is not the first), and `meta` has `app`, `version`, `image`, `format` (`RGBA8888`, or `RGBA16161616` for 16-bit), `size`, `scale`, `frameTags` (per clip: `name`, `from` and `to` indexing `frames`, `direction` forward, `repeat` `"1"` for clips that play once) and, with several pages, `images`. Readers of Aseprite JSON take single-page sheets as they are.
+- **Numbered frames** (`--frames`): one full-size PNG per frame in order, holds repeated (`<clip>-0000.png`, ...), in a folder next to the bundle unless `-o`.
+- **Godot** (`--godot`): into the folder (given, or `export.godot`; the first folder given is kept in the document as one history step, `--store` replaces a kept one) go the sheet pages, `<name>.tres` and `<name>.tscn`. The `.tres` is a `SpriteFrames` with an `ext_resource` per page (by a path relative to the `.tres`, and the page's uid from its `.png.import` once Godot has imported it), an `AtlasTexture` per picture (`region` its rect in the page, `margin` its trim: offset and the rest of the full size, so every frame is the canvas size and lines up), and one animation per clip (or `default`) with its name, `speed` (fps), `loop` and per-frame `duration` (the exposure's length in frames). The `.tscn` holds an `AnimatedSprite2D` using it, `centered = false` and `offset` the negated origin at the export scale, autoplaying the first animation. Uids of the `.tres` and `.tscn` are read back from the files a re-export replaces (new ones come from a hash of the file's path, in Godot's alphabet), so scenes that use them keep working. A container test imports an export in headless Godot (4.6 in the container) and checks names, frame counts, durations, loops, the offset and that the old uids still load after a re-export.
+- Timings (container): the bounce sheet in about 0.25 s; a Godot export of 40 distinct frames of a 1024 canvas (4 layers, 60 strokes each) 2.3 s cold, 1.4 s warm, most of it PNG encoding of the 3080 px pages.
+- Later: `Parallax2D` scenes (M6), `Skeleton2D` rigs (M6), SVG for vector layers.
+
+## Milestones
+
+| | Goal |
+|---|---|
+| M0 | Prototype that proves the risky parts |
+| M1 | Layers with time in the model, vector layers, the agent CLI loop, editor basics, sync |
+| M2 | Drawing: brush engine with inking, pencil and fill, stroke editing, masks, blend modes |
+| M3 | Frame-by-frame animation: timeline, onion skin, playback, clips, sprite sheet and Godot export |
+| M4 | The editor, usable: docked panels, a look, tool strip, layers panel, timeline toolbar, status and progress, command palette, pen-sized targets |
+| M4.5 | The agent's hand: ink, flats, shade, rim and texture from vector shapes; arcs and spacing checks, parts, in-betweens that keep hand work |
+| M5 | Painting and the look: textured and wet brushes, adjustments, filters, light, depth fog, generators, text, image layers |
+| M6 | Rigs and scenes: cut-out parts, bones, re-posing drawings, keyframes, parallax scenes, pixel layers |
+
+
+## Risks M0 retires
+
+1. Pen pressure and tilt in a native Rust window on macOS. Fallback: read them from `NSEvent` through `objc2`.
+2. Live brush latency on the CPU at 120 Hz with large textured brushes, and replay speed. Fallback: a GPU brush engine, giving up exact parity with agent renders.
+3. A 4k canvas with 30 layers panning and zooming smoothly.
+4. CLI render time on a real document in the container.
+5. File events and atomic writes across the container mount.
+
+## Out of scope for now
+
+3D, an iPad app, a Windows or Linux editor, image-model layers, multi-human collaboration.
diff --git a/docs/images/editor.png b/docs/images/editor.png
new file mode 100644
index 0000000..a2c2df1
Binary files /dev/null and b/docs/images/editor.png differ
diff --git a/docs/images/lantern.png b/docs/images/lantern.png
new file mode 100644
index 0000000..880b015
Binary files /dev/null and b/docs/images/lantern.png differ
diff --git a/docs/images/solids.png b/docs/images/solids.png
new file mode 100644
index 0000000..3c0c699
Binary files /dev/null and b/docs/images/solids.png differ
diff --git a/docs/images/start-window.png b/docs/images/start-window.png
new file mode 100644
index 0000000..03b43fe
Binary files /dev/null and b/docs/images/start-window.png differ
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
new file mode 100644
index 0000000..2416ee5
--- /dev/null
+++ b/docs/skill/SKILL.md
@@ -0,0 +1,355 @@
+---
+name: klad
+description: Make and edit 2D art with the klad CLI (`klad`) in a `.draw` bundle that the user can open in the editor at the same time. Use for any drawing, illustration, game asset, icon, background or sprite work in klad, for reading what the user drew or asked for (strokes, selection, pinned notes), and for scripting art generators that emit `klad apply` ops.
+---
+
+# klad
+
+A `.draw` bundle is a folder: `doc.json` (layers, cels, vector nodes, palette), `strokes/<layer>/<cel>.strokes` (paint strokes and fills as data), `brushes/<id>.json` (every brush its strokes use) and `.cache/` (renders, history, notes, tiles). The `klad` CLI edits it; The user edits the same bundle in the editor (`klad open`). Both see each other's changes within a second. The user starts and opens drawings from the editor's start window (cmd N, cmd O, recent) and can copy a drawing's path from the document menu at the bottom of the tool strip to hand it to you. To start one yourself: `klad new art.draw --width 1600 --height 1200 --background '#e9e4da' --sketch` (one paint layer, `l1`, and a vector layer named sketch on top, `l3`).
+
+Working on klad itself: the repository's `CLAUDE.md`, `CONTRIBUTING.md` and `docs/DESIGN.md` are the source of truth. Build the CLI with `just build`; the binary is `target/release/klad` (under `$CARGO_TARGET_DIR` when that is set).
+
+## The loop
+
+1. Look: `klad ls art.draw` (tree, top layer first, ids and bounds) and `klad render art.draw --scale 0.5 --overlay ids,bbox`. Read the PNG it prints.
+2. Change: `klad add`, `klad set`, `klad rm`, `klad mv`, `klad stroke`, `klad fill`, `klad transform`, `klad lasso`, `klad path`, `klad palette`, or many at once with `klad apply` (JSON lines, one transaction).
+3. Check: add `--render` (preview, longest side 1024) and `--overlay ids,bbox` to the edit, or `klad diff` (before and after, side by side), or `klad render --focus <id>` for a close-up.
+4. Undo freely: `klad undo`, `klad redo`, `klad log`. History is shared with the editor.
+
+Keep renders small unless detail matters: `--scale 0.5` or `--focus <id>` costs far fewer tokens than full size.
+
+## What the user wants
+
+- `klad notes art.draw`: notes the user pinned on the canvas, each with a `--region` render command. Do the work, then `klad notes art.draw --done <id>`; the editor shows the pin as done at once and lists it under done in the Notes pane, so mark a note done only when it is.
+- `klad selection art.draw`: the layer, shapes, path and strokes the user selected in the editor (strokes as `<cel>:s<id>`), with bounds and a `--focus` command.
+- `klad strokes art.draw <layer> --json`: the user's strokes with points and pressure, to trace their shapes (a ridge line and tree positions from a pen sketch, for example).
+
+## Vector nodes
+
+Layers: `paint` (strokes), `vector` (nodes), `group` (children). Add a vector layer, then nodes into it:
+
+```
+klad add art.draw layer vector name=sky
+klad add art.draw rect --in l1 x=0 y=0 w=2048 h=900 'fill={"linear":{"from":[0,0],"to":[0,900],"stops":[[0,"#20304f"],[1,"#d98b5f"]]}}'
+klad set art.draw n3 transform.rotate=-8 opacity=0.8 blur=4
+```
+
+- Types: `rect` (x, y, w, h, radius), `ellipse` (cx, cy, rx, ry), `path` (SVG `d`), `group` (children).
+- Every node: `fill`, `stroke` (`paint`, `width`, `cap`, `join`, `dash`), `transform` (`x`, `y`, `rotate`, `sx`, `sy`, `pivot`), `opacity`, `blur` (soft edges, glows, haze, shadows), `clip` (SVG path that clips the node and its children), `visible`, `name`.
+- Paint: `"#rrggbb"`, `"#rrggbbaa"`, `"none"`, `{"linear":{"from","to","stops"}}`, `{"radial":{"center","radius","stops"}}`.
+- As in SVG, a node without `fill` is black; use `fill=none` for outlines only.
+- Unknown keys fail with the list of valid ones. Structure (`id`, `type`, `kind`, `children`, `cels`, `nodes`) only changes through add, rm and mv.
+- Ids are case sensitive; overlays print them exactly.
+
+## Painting
+
+```
+klad stroke art.draw l4 --brush ink --size 14 --color '#1b1b1b' --path 'M100 400 C 300 200 500 600 700 400' --pressure 0.1,1,0.05
+klad stroke art.draw l4 --brush ink --size 5 --taper 8,20 --path 'M100 100 L140 220'
+```
+
+- `klad brushes art.draw` lists the brushes: the ones the bundle embeds and the library (`ink` inking pen, `pencil`, `marker`, `airbrush`, `soft`, `chalk`, `eraser`, and for painting `flat-bristle`, `round-bristle`, `sponge`, `fog`, `leaves`, `grass`, `splatter`, `wet`, `smudge`, `blender`, `dry-brush`, `two-tone`); the tip column says `+dual`, `+texture`, `+colour`, `+wet`, `+smudge` or `+blend`. `--show <id>` prints one as JSON. A bundle keeps every brush it uses, so `ink` in an older bundle can be the older ink; `--brush` takes any id from that list.
+- Painting brushes: `wet` picks up the colour under it and mixes it in, `smudge` pulls paint along, `blender` softens what it crosses; all three read only the layer they paint on (paint the colours to mix on one layer). `leaves`, `grass` and `splatter` scatter their picture tips with jittered colour; `two-tone` paints `--second` at a light press and `--color` at a full one. `--second '#e0a040'` (`"second"` in `apply`) is the second colour for brushes with colour dynamics.
+- New brushes: write the JSON (copy one from `--show`; keys `tip` (`round`, `chalk` or `{"image":{"image":"name"}}`), `dual`, `grain` (`paper` or `image`, `strength`, `scale`, `contrast`, `pressure`), `color` (`hue`, `saturation`, `value`, `strokeHue`, ..., `pressure`, `along`), `paint` (`wet`, `smudge`, `blend`)) and `klad brushes art.draw --set my-oil brush.json` (`-` reads stdin). Pictures for tips and textures: `klad brushes art.draw --picture bark bark.png` (dark is paint, or the alpha). Ids and pictures are fixed once in the bundle, since strokes keep their brush.
+- `--taper in,out` thins the first and last px of the line to a point whatever the pressure; without it the brush's taper applies (`ink` is `10,24`), `--taper 0,0` gives round ends. Short hatching wants about `8,20`, long contours `30,80`.
+- `--pressure` spreads values evenly along the stroke; several subpaths in `--path` make several strokes. `--points 'x,y,p x,y,p'` gives explicit samples.
+- In `apply`: `{"op":"stroke","layer":"l4","brush":"ink","size":14,"color":"#1b1b1b","path":"M...","pressure":[0.1,1,0.05],"taper":[12,30]}`.
+- Agent strokes are marked `agent` in `klad strokes`; the user's are `human`.
+
+## Editing strokes and fills
+
+Every stroke and fill has an address `<cel>:s<id>` (fills share the id counter with strokes). `klad strokes art.draw <layer>` lists them with the cel id on top.
+
+```
+klad set art.draw c4:s12 color=#c84a3a size=6 brush=pencil
+klad set art.draw c4:s7 color=skin opacity=0.8
+klad rm art.draw c4:s12 c4:s13
+klad transform art.draw c4:s3 c4:s5 --move 40,-10 --rotate 15 --scale 1.2
+klad show art.draw c4:s12
+klad render art.draw --focus c4:s12
+```
+
+- Strokes take `color`, `size`, `opacity`, `flow`, `brush`, `taper` (`[in,out]` or `null`) and `path`; fills take `color` and `opacity`. The stroke keeps its path, pressure and seed, so a recoloured stroke is the same mark in a new colour.
+- Bending a stroke: `klad strokes --json` gives each stroke a fitted `path` (a few points); edit it and `klad reshape art.draw c4:s12 --path 'M...'` (or `set` with `path`). Every sample keeps its pressure, tilt and timing at the same fraction of the length, so the line keeps its weight and taper. The user does the same with A in the editor.
+- `transform` moves, rotates (degrees, clockwise) and scales about `--pivot` (default: the middle of the marks' bounds). Stroke sizes and tapers scale with them; fills move by whole pixels and are resampled when turned or scaled. Ids in several cels need a `--pivot`.
+- In `apply`: `{"op":"set","id":"c4:s12","color":"#c84a3a"}`, `{"op":"rm","ids":["c4:s12"]}`, `{"op":"transform","ids":["c4:s3","c4:s5"],"x":40,"y":-10,"rotate":15,"sx":1.2,"sy":1.2}`.
+- Edits redraw only the tiles the marks touch, from the nearest checkpoint, so they are cheap on large cels.
+
+## Lasso
+
+```
+klad lasso art.draw l4 --polygon '600,600 1400,560 1450,1300 640,1380'
+klad lasso art.draw l4 --polygon '600,600 1400,560 1450,1300 640,1380' --cut --move 40,-25
+klad lasso art.draw l4 --polygon '...' --cut --rotate 12 --scale 1.1
+klad lasso art.draw l4 --polygon '...' --flip h
+klad lasso art.draw l4 --polygon '...' --cut --rm
+```
+
+- Without a move, turn, scale, flip or `--rm` it lists the strokes and fills inside the polygon and those crossing its edge.
+- Without `--cut` only whole marks move (strokes whose points are all inside, fills whose pixels are). With `--cut` each mark crossing the edge is split: the outside part stays put, the inside part becomes a new mark that moves with the rest, so nothing outside the lasso changes. The output names the moved marks (`lasso on l4 moved c2:s10 ...`); they stay strokes and can be edited again.
+- `klad transform` takes `--flip h` or `--flip v` too. In `transform` and `lasso`, `--scale` scales the marks; their previews use the default size.
+- In `apply`: `{"op":"lasso","layer":"l4","polygon":[[600,600],[1400,560],[1450,1300]],"cut":true,"x":40,"y":-25}` (also `rotate`, `sx`, `sy`, `scale`, `pivot`, or `"rm":true`).
+
+## Masks, clipping and lock alpha
+
+```
+klad set art.draw l5 clip=true blend=multiply
+klad set art.draw l3 lockAlpha=true
+klad add art.draw mask --in l5
+klad stroke art.draw l9 --brush airbrush --size 180 --path 'M600 600 L 640 700'
+klad set art.draw l9 visible=false
+klad rm art.draw l9
+```
+
+- `clip=true` shows a layer only where the nearest unclipped layer below it (its base) has paint. Clipped layers blend onto the base with their own blend; the group takes the base's opacity and blend. This is how shading stays inside flat colour: flats on one layer, a multiply shade layer and a rim light layer above it, both clipped.
+- `klad add art.draw mask --in <layer>` gives a layer a mask and prints its id. The mask is a paint layer of its own (`klad ls` shows it under its layer): strokes and fills on it hide the layer, the eraser brings it back, an empty mask hides nothing. `hide=true` starts it hiding everything. `visible=false` on the mask turns it off; `klad rm` on its id removes it.
+- `lockAlpha=true` on a paint layer: new strokes and fills only land where the layer already has paint, which recolours line art (a big soft stroke over lines tints only the lines). It is recorded per stroke, so set it back to false when done, or the user's next pen strokes on that layer only land on existing paint. The eraser does nothing on a lock-alpha layer.
+- In `apply`: `{"op":"add","mask":{"name":"light"},"in":"l5"}`, `{"op":"set","id":"l5","clip":true}`.
+
+## Light, effects and adjustments
+
+```
+klad effect art.draw l3 glow radius=24 color=#ffd080
+klad effect art.draw l3 outline width=4 color=#101418
+klad effect art.draw l3 # lists them; --rm 1 removes the second, --clear all
+klad add art.draw layer adjust curves 'points=[[0,0],[0.5,0.3],[1,0.85]]' 'blue=[[0,0.12],[1,1]]' name=dusk
+klad add art.draw rays --in l7 x=430 y=0 angle=95 spread=40 count=9 length=600 start=120 fill=#fff0c0c0 blur=6
+klad set art.draw l5 blend=soft-light
+```
+
+- Effects are settings on a layer (or group), applied in order when it composes and always editable: `blur` (radius), `glow` (radius, strength, threshold: 0 glows from every pixel, about 0.7 only from the bright ones, as bloom; color tints it; blend: screen by default, add for hard light, normal lays it like paint), `outline` (width, color, inside=true), `shadow` (x, y, radius, color with alpha), `noise` (amount, size, seed, mono=false for coloured grain), `displace` (amount, size, seed; by=<layer> pushes with that layer's red across and green down, grey stays put; a hidden layer works as the map). In `apply` or `set`: `effects=[{"glow":{"radius":24}},{"outline":{"width":3}}]`.
+- Bloom: put everything that should bloom in a group and give the group a glow with a threshold and blend add. A light layer is a paint layer with `blend=add` and a soft glow (`'effects=[{"glow":{"radius":24,"strength":0.8}}]'`): paint light into it with `soft` or `airbrush`.
+- Blend modes: normal, multiply, screen, overlay, add, color-dodge, soft-light, hard-light, lighten, darken, color, luminosity.
+- Adjustment layers change what is under them in their group (or, with `clip=true`, only their base): `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied first; x is the input brightness, y the output), `balance` (shadows, midtones, highlights as [cyan-red, magenta-green, yellow-blue] in -1..1, keepLight), `gradient-map` (stops by brightness), `fill` (paint: a colour or gradient, drawn with the layer's blend). Their opacity, blend and mask apply. To grade a scene, put one curves layer on top; to grade one part, put the part and the adjustment in a group.
+- Rays are a vector node: an origin, a direction (`angle` in degrees, 90 is down), `spread`, `count`, `length`, a gap `start` px wide they come through, `falloff`, `noise` and `seed`. The node's `fill` colours them and `blur` softens them; a vector layer of rays on `screen` or `add` reads as light through trees.
+- `klad ls` shows `fx: glow outline` on layers with effects and the type of an adjustment layer; `klad show <layer>` lists their settings.
+
+## Depth, pictures, generators and text
+
+```
+klad set art.draw g2 depth=2.5 a plane (a layer at the top of the stack): 0 is near
+klad atmosphere art.draw color=#8fa3b8 top=#d3dde7 density=0.55 blur=1.2 desaturate=0.25
+klad add art.draw layer image src=photo.jpg reference=true
+klad add art.draw repeat --in l4 count=8 'step=[60,0]' 'children=[{"type":"rect","x":0,"y":400,"w":12,"h":80,"fill":"#3a2a1a"}]'
+klad add art.draw scatter --in l4 x=0 y=700 w=1600 h=150 count=40 seed=7 'size=[0.6,1.6]' 'turn=[-30,30]' 'children=[{"type":"ellipse","cx":0,"cy":0,"rx":20,"ry":11,"fill":"#3a4450"}]'
+klad add art.draw mirror --in l4 x=800 angle=90 'children=[{"type":"path","d":"M560 900 L560 560 L760 410 Z","fill":"#0d1117"}]'
+klad font art.draw ~/fonts/Signage.ttf
+klad add art.draw text --in l4 'text=THE CROOKED INN' font=Signage.ttf size=46 x=340 y=96 align=center tracking=4 fill=#f3d9a4
+```
+
+- Depth: give each top-level group (plane) a `depth`; with an atmosphere every plane fades towards the fog (and the `top` colour higher up), blurs and loses colour, more the deeper it is. Near planes keep depth 0. The user previews the parallax by holding D. `haze` is also an effect of its own (`klad effect art.draw l3 haze amount=0.4 color=#9aa8b8`).
+- References: `reference=true` on any layer keeps it visible in the editor but out of `klad render`, `klad hash` and `klad export` (add `--references` to see it). Pictures to trace over go there.
+- Pictures: `layer image src=<PNG or JPEG>` copies the file into the bundle (`images/<hash>.png`) and places it on a new vector layer, fitted inside the canvas; `x=`, `y=`, `w=`, `h=` place it. The node is `{"type":"image",...}`, moved and scaled like any shape.
+- Generators keep their settings: `repeat` (count, step, turn and pivot for an arc, scale, columns and row for a grid), `scatter` (region x, y, w, h, count, seed, size and turn ranges, `avoid`: SVG paths no copy lands in), `mirror` (x, y, angle of the axis). Children are drawn once per copy; for scatter draw the child around 0,0. `klad add <bundle> <shape> --in <generator id>` adds more children.
+- Text: the font must be a file in the bundle (`klad font`); a missing font is refused with its name. `text` takes new lines (`$'line one\nline two'` in bash), `x` is the left, centre or right of each line (`align`), `y` the top of the first line; `tracking` is extra px between letters, `leading` the line height as a multiple of the size; fill and `stroke` colour and outline it.
+
+## Path points
+
+```
+klad path art.draw n7
+klad path art.draw n7 --move 3 412,230
+klad path art.draw n7 --nudge 3,4,5 0,-20
+klad path art.draw n7 --handle 3 out 430,210
+klad path art.draw n7 --add 418,236
+klad path art.draw n7 --rm 4,5 --corner 2 --smooth 6
+klad path art.draw n7 --simplify 1.5
+```
+
+- Without flags it lists the points (anchors) of a path, rect or ellipse, numbered across subpaths, with handles and corner/smooth/curve. Coordinates are the shape's own (as in its `d`, before its transform). After an edit it lists them again; numbers shift after inserts and removals.
+- Any point edit turns a rect or ellipse into a path that looks the same. `--simplify <px>` refits a dense polyline (traced or generated) as a few smooth points within that distance: do it before reshaping something like a ridge line.
+- A smooth point keeps its handles in line when one moves (`"free":true` breaks it). Pivots of transformed shapes and their parent groups are pinned first, so editing points never shifts the rest of the shape.
+- In `apply`: `{"op":"path","id":"n7","move":3,"to":[412,230]}`, `"move":[3,4],"by":[0,-20]`, `"handle":3,"out":[430,210]`, `"insert":3,"t":0.5`, `"add":[418,236]`, `"rm":[4,5]`, `"corner":2`, `"smooth":6`, `"simplify":1.5`, or no key to only convert.
+
+## Colour and fills
+
+```
+klad palette art.draw --add '#f0c8a0' --name skin
+klad fill art.draw l2 --at 820,640 --ref lines --gap 4 --color skin
+klad fill art.draw l2 --polygon '100,100 400,120 260,380' --color '#20304a'
+klad refill art.draw l2
+```
+
+- The palette lives in `doc.json`. Any colour argument takes `#rrggbb`, `#rrggbbaa` or a palette name. `klad palette art.draw` lists it; `--add` with an existing `--name` changes that colour; `--rm` takes a name, a colour or an index.
+- A flood fill starts at `--at` and spreads over pixels within `--tolerance` (0 to 1, default 0.1) of the seed pixel in the reference: `this` layer (default), `all` (everything visible, background included) or a layer id or name. Put flat colour on a layer under the lines and use `--ref <lines layer>`; a fill on the line layer itself covers the inside edge of the lines.
+- `--gap` closes openings in the lines up to that many px wide (inked shapes with small gaps); `--expand` (default 2) tucks the fill under the lines so no paper shows between line and colour.
+- Fills are records next to the strokes, with their coverage stored, so they render the same later. When the lines change, `klad refill <bundle> <layer>` recomputes every flood fill of that cel (`--id` for one).
+- In `apply`: `{"op":"fill","layer":"l2","at":[820,640],"ref":"lines","gap":4,"color":"skin"}`, `{"op":"palette","add":"#f0c8a0","name":"skin"}`. Strokes and fills in one batch see each other in order, so ink then fill in one `apply`.
+
+## Drawing from shapes
+
+Describe a piece instead of programming it: block the subject in as vector shapes on a hidden sketch layer (rects, ellipses, paths, groups; give them ids so later ops can name them), then let these commands draw on paint layers. Everything they make is ordinary strokes and fills, so `klad set`, `klad transform` and the user's pen edit it afterwards.
+
+```bash
+klad add art.draw layer vector name=sketch visible=false
+echo '{"op":"add","node":{"id":"body","type":"ellipse","cx":400,"cy":420,"rx":160,"ry":120},"in":"<sketch id>","frame":0}
+{"op":"add","node":{"id":"eye","type":"ellipse","cx":450,"cy":380,"rx":18,"ry":18},"in":"<sketch id>","frame":0}' | klad apply art.draw
+klad fill art.draw flats --shape body --color skin # exactly the shape's area, grown 2 px under the ink
+klad light art.draw --from body --light -1,-1 --shade shade --rim rim --depth 20 # shade away from the light, a rim towards it
+klad ink art.draw lines --from body,eye --weight 7 --light -1,-1 # tapered strokes, weight from rules
+klad hatch art.draw shade --in body --angle 30 --spacing 8 --length 10-24 --color shadow
+klad scatter art.draw lines --in ground --mark "M0 0 Q 3 -22 8 -40" --count 20 --turn -25,25
+klad paint art.draw paint --in body --color skin --light -1,-1 --weight 12 # a round form, painted from a light model
+klad paint art.draw paint --in pillar --form cylinder --axis 90 --lamp 200,600,150 --color '#c9b8a0'
+klad prepare art.draw # buffer every drawing before the user opens it
+```
+
+- Painting a form: after the flats, `klad paint` paints each shape as a form. `--form round` (default) bulges any closed shape like a pillow, its height growing with the distance to the outline; `flat` is a plane facing `--facing x,y,z` (z toward the viewer, y down); `cylinder` is round across `--axis` degrees. The light model is a key light from `--light x,y` at `--elevation` (or `--lamp x,y,height` in canvas px: the shape nearest the lamp gets the full key light, farther ones less by inverse square, so paint a cluster in one op), cool fill from above (`--fill`, `--fill-strength`), warm bounce from below (`--bounce`, `--bounce-strength`) and a darker core just past the terminator (`--core`); `--color` is the local colour in full light, so the lit side comes out at that colour and the shadow side about four value steps under it. Strokes follow the form (along bands of equal light on round forms, along the axis on cylinders, at `--angle` on planes), take their colour from the model where they lie and stop where the light changes, so none carries the lit colour into the shadow. Passes go from twice `--weight` down to half of it (the small ones only where the form turns), then a decisive pass with `--bold` (`oil-load`) in the lights and a few quiet strokes in the shadows (`--decisive 0` skips both); `--vary` lets each stroke stray in value and temperature. Paint on a layer clipped to the flats, or lock the flats layer and paint into it: strokes then run past the outline and short strokes along it cut the edge in; on a plain layer they stay inside it and the flats show at the rim.
+- Every stroke the shape ops make is drawn like a hand (`--hand 1`, the default; `0` gives the old even strokes): its own pressure curve (a press-in, a peak, a longer lift-off), tapers that are a share of its length, a width that varies from stroke to stroke, and a slight bow on hatching and flat planes. Brushes for it: `oil` (soft edge, size and opacity from pressure) for building forms, `oil-load` (harder edge, more grain) for strokes that should stay visible.
+- `klad light` takes `--lamp x,y,height` too: each shape is shaded away from the lamp instead of one direction for all.
+- `klad prepare art.draw [--from 0 --to 23]` replays every painted drawing of those frames into the cache after a big CLI change, so the editor opens and plays it without replaying strokes. The editor still makes its frame pictures itself, quickly, from the cached drawings.
+
+- Ink rules: heavier on the side away from `--light` (the direction the light comes from, -1,-1 is top left), heavier on the silhouette than on inner lines (an outline inside another shape given in the same call), thinner on tight curves, a seeded wobble (`--wobble 0` for none). Outlines split into separate strokes at corners sharper than `--break` (60 degrees); `--gap 3` leaves inkers' gaps where lines meet. Open details (folds, cracks, ribs) go through `--path "M..."`.
+- `klad light` writes lasso fills with a cut: on the shade layer the shape minus itself moved towards the light (`--soft 3` overlapping steps soften the inner edge), on the rim layer a band along the lit edge. Clip the shade layer (multiply) and the rim layer to the flats, as in `samples/lantern/`.
+- `samples/lantern/generate.py` is the whole recipe for a prop in about 100 lines; `samples/ink-shapes/` shows the ink options side by side.
+- Details that make a prop read as made rather than blocked in (an early version of the lantern read "kind of as good, but its details are not too great"): connect what hangs (hook, links, bead, cap: every piece touches the next; a link seen face-on is a closed ring through `--path`, one seen edge-on a small filled bar); give a round form a crisp core shadow with its own `light` pass (`--soft 1`, depth about a third of its width, `shadeOpacity` 1) instead of a soft gradient; build a stone or block from two planes (a top face and a darker side as its own shape) and keep texture to the side plane; plant grass as a few tufts where things meet the ground, leaning away from the object, not a fringe along an edge; ink a shape that enters another as an open path, so its cut edge is not drawn on top.
+- The ops are `ink`, `light`, `hatch`, `paint`, `scatter` and `fill` with `shape`; shapes added earlier in the same `apply` can be used by them. `samples/lantern/` builds the inked prop, and with `PAINTED=1` the painted one (`paint` by form in place of `light` and `hatch`).
+
+## Building in 3D and painting stroke by stroke
+
+Anything with straight edges or round rims (boxes, buildings, cylinders, cups, rims of holes) is built in 3D and projected, never typed in as corners: typed corners give vanishing points at different heights and verticals of the same length near and far. `docs/skill/drawkit.py` (Python, no dependencies; `python3 docs/skill/drawkit.py --check` tests it) has a `Camera(eye, focal, centre, horizon)` with `project`, `box` (corners and faces with normals), `visible_faces`, `sphere_points`, `cylinder_points`, `extrusion_points`, `silhouette` (the hull of projected points), `shadow` and `shadow_shape` (points projected along the light onto the ground), and `stroke`, the same hand as the CLI's, for generators that place their own strokes. A level camera with the horizon on the canvas gives two-point perspective with upright verticals; moving the camera's centre on the canvas moves the subject without bending the perspective.
+
+When a piece needs more than `klad paint` gives, paint it stroke by stroke in a generator, the way `samples/solids/generate.py` does:
+- One locked paint layer per plane (each visible face of a box, a cylinder's body and its top), filled with its own middle value, then painted into; one base under several planes shows through as streaks of the wrong value.
+- Strokes that follow the form, big to small, each coloured from a light model at its own place; cut a stroke where the surface turns away from the viewer and where the light changes, and keep bow off on strokes that follow a value band.
+- Then a decisive pass: fewer, larger, visible strokes in the lights, quieter ones in the shadows, loose broad ones on backgrounds.
+- Then material detail where the light rakes and at the focus: pits with a dark side toward the light, grain in clusters, a few chips of varied size, crazing in glazes, grime toward the base.
+- Cast shadows and contact darkening as soft shapes on a `multiply` vector layer, a crisp copy near the contact and a soft one farther out, so the surface's brushwork shows through.
+- Big masses before texture: a large surface (a cave roof, a wall) gets its light as broad strokes first and quiet low-contrast forms after; small strokes laid evenly read as ripples or gravel.
+- Where one form grows out of another (a stalactite from rock), paint the parent over the join.
+- Zoom in on every object (`klad render --region x,y,w,h --scale 2`) after each pass and fix what you see before showing the user.
+
+## Studying a reference
+
+To recreate a picture (a reference study): `klad add art.draw layer image src=ref.jpg reference=true`, then size it to the canvas with `klad set art.draw <node> x=0 y=0 w=<width> h=<height>` (a picture smaller than the canvas is placed at its own size). Read the reference in quarters with `klad render art.draw --references --region x,y,w,h` (a reference under an opaque background is covered: hide the background or render the reference alone), and take coordinates from those crops. Build in planes from back to front, compare often on one sheet (a bundle holding the reference picture above the render), and fix values before details: the first passes of a cave study were too bright everywhere, not too plain.
+- Light layers and mist on `screen` go behind the planes they light from behind; above a plane they turn its forms milky.
+
+## Export
+
+```
+klad export art.draw --scale 2
+klad export art.draw --layer hero --scale 4 --depth 16 -o hero.png
+```
+
+Transparent PNG of the image or one layer or group, next to the bundle unless `-o`. 8-bit exports are dithered so gradients do not band; `--depth 16` keeps 16 bits; `--background` keeps the canvas colour. Vectors stay sharp at any scale; paint layers are resampled. Sprite sheets, numbered frames and Godot exports are under Time, Animation exports.
+
+## Scripts
+
+For anything with more than a handful of shapes, write a generator that prints ops as JSON lines and pipe it into `klad apply`. Rebuild from scratch each run (copy the source bundle, apply, render) so the script stays the source of truth. A landscape generator of about 18,000 nodes builds and renders in about 4 s this way.
+
+## Time
+
+`timeline` has `fps` and `frames`; each layer has cels (`frame`, optional `hold`, optional `link` to reuse another cel). A cel that is not a link is a drawing; the frames it shows on are its exposure (from `frame` for `hold` frames, or until the next cel). `--frame n` on `ls`, `render`, `stroke`, `fill`, `lasso` and `add` picks the frame; a stroke or fill paints into the drawing exposed there.
+
+```
+klad frames art.draw # exposure sheet: c4 = a drawing starts, | still showing, c9->c4 a link, . blank
+klad timeline art.draw --fps 12 --frames 24 # length and speed (no flags: show them, the origin, the Godot folder and the clips)
+klad cel art.draw new l3 --frame 4 # blank drawing; inside an exposure it takes over the rest of it
+klad cel art.draw dup c4 [--frame 6] [--insert] # copy (strokes keep their ids); default right after c4; --insert moves later cels back
+klad cel art.draw link c4 --frame 8 --hold 2 # show c4 again
+klad cel art.draw unlink c9 # the link becomes a drawing of its own
+klad frame art.draw insert 4 [--count 2] [--layers l3] # what showed at 4 shows longer, the rest moves back
+klad frame art.draw remove 4 [--count 2] [--layers l3]
+klad hash art.draw --all # one pixel hash per frame
+```
+
+In `apply`: `{"op":"cel","new":"lines","frame":4,"hold":2,"id":"ball4"}` (the `id` lets later ops in the same batch name it), `{"op":"cel","link":"ball0","frame":15}`, `{"op":"frames","insert":4,"count":2}`, `{"op":"timeline","frames":24}`. For an animation script: make every drawing's cel first (`cel new` with an `id`), then its strokes and fills at that frame. `samples/bounce/generate.py` is the pattern: lines, colour filled against the lines, a multiply shadow, a held floor, the rest pose as links.
+
+Strokes copied by `dup` keep their ids, so `c7:s3` in the copy is the same line as `c4:s3`: move it with `klad transform` to make the next pose. Removing a drawing that links show (`rm`, or removing its frames) gives it to the first link instead of breaking them.
+
+### Keys, in-betweens, colour and timing
+
+Animate by keys: draw the key poses with their parts named, check the keys' arcs, let `klad inbetween` make the drawings between them, colour every drawing from the first with `klad fill --like`, check with `klad gaps`, set the timing with `klad retime`, check the arcs again. `samples/creature/` (`generate.py` and `build.sh`, which writes `creature.draw`) is the pattern: an idle and a walk on six layers (shadow, far leg, colour, a clipped multiply shade, a clipped rim light, lines), parts body, sprout, leaf, second leaf, near leg and far leg, `klad arcs --check` before and after in-betweening, the loop closed with `--loop`.
+
+```
+klad copy art.draw c1:s3 c1:s4 --frame 6 [--layer shade] [--move 12,-4 --rotate 8 --pivot 512,400] [--cut 'x,y ...']
+klad inbetween art.draw --layers lines,colour,shade --from 0 --to 6 [--count 2] [--spacing in-out] [--match near] [--pair s3=s7]
+klad inbetween art.draw --layers lines,colour --from 9 --loop # the loop's last in-betweens, towards its first drawing
+klad inbetween art.draw --layers lines --from 0 --to 6 --unpaired pop|fade|draw-on [--at 0.3]
+klad inbetween art.draw --redo [--layers lines] [--keep-drawn | --force]
+klad part art.draw c4:s14 c4:s15 --name leaf # or --part leaf on stroke, fill, ink, hatch, scatter
+klad arcs art.draw --track 'lines:near leg' --track 'far:far leg' --clip walk --ground 823,811 --travel 7 --check
+klad render art.draw --frame 20 --track 'lines:near leg' --region 420,720,200,120 --scale 4 # the paths drawn
+klad render art.draw --sheet walk --drawings --overlay parts
+klad fill art.draw colour --like colour0 --frames all
+klad gaps art.draw colour --sheet all # closed regions no fill covers, with a render marking them
+klad retime art.draw 0-11 --on 2 # or --on 1, --fit 16, --reverse, --pingpong; [--layers l3]
+```
+
+- Name parts as you draw keys (`--part`, or `"part"` in ops): in-betweens pair part by part first, whatever the ids, so keys drawn separately, or redrawn, or with the user's strokes in between, still pair. Give each piece that moves on its own its own part (one per leaf, per limb): within a part marks pair in drawing order. Without parts keys pair by mark id, so make every key with the same ops in the same order, or `cel dup` a key and change the copy. `--match near` pairs drawings made separately (and turns strokes drawn backwards); `--pair` forces the odd one. Unpaired marks are left out and listed by default: read that list, or let them `--unpaired pop|fade|draw-on`.
+- Check the keys' motion before in-betweening, the way an animator flips them: `klad arcs` with a track per foot (parts), `--ground` per foot (a far foot drawn higher for depth has its own line), and `--travel` for a cycle drawn in place (a planted foot moves back by the travel per frame; on twos after retime, halve it). It reports feet under the ground, planted feet sliding, and two feet swapping sides (legs crossing); `--check` makes the build stop. The creature's first keys slid their feet with the body's tilt: feet go where the ground is, not where the hip is.
+- A stroke whose end touches another line in both keys rides on that line (a hand on an arm, a leaf on a stem) and its end stays on it, so closed shapes stay closed. Make joins actually touch in every key (within half the line's width plus 2 px); parts that only float near each other move on their own arcs and drift apart mid-way.
+- A loop's last in-betweens: `--from <last key> --loop` in-betweens towards the loop's first drawing (the clip holding the frame, else frame 0) up to the loop's end. Add the clips before in-betweening.
+- The editor's in-between panel runs the same `klad inbetween`; its redo takes a choice per in-between: `--redo --only c12,c14,c16 --keep-cels c14 --force-cels c16` (the rest of `--only` only if unchanged). Its History pane shows your steps as "agent" next to the user's, and they can undo back to any of them; a step keeps its author and time through undo and redo, so `klad log` still says whose it was.
+- In-betweens show as `c12*` in `klad frames`; `klad show c12` gives `tween` (keys, t). After changing a key, `--redo` remakes them; it refuses in-betweens someone drew on or edited. `--keep-drawn` remakes the agent's marks and keeps the user's on top, carried with the line under them (with his part, the lines of that part); `--force` in-betweens his marks with the rest. Ask him which he wants when he drew corrections; keep-drawn is the safe default. An in-between layer list goes together: list the lines and the layers that fill against them in one call so the fills are recomputed against the in-between lines.
+- Flood fills in in-betweens are recomputed from seeds carried by the lines; fills that land on a line or leak are left out and listed (`fills left out: ...`). `klad gaps --sheet all` afterwards should say "nothing left uncovered".
+- `--like` finds each fill's region in the other drawings by shape near where it was; it holds while drawings overlap from one to the next (keys of one character). It replaces a fill with the same id, so running it again is safe. Lines that fence a region into pockets (hatching or stitches closer together than the fill's gap) show up in `klad gaps`.
+- `klad retime` keeps layers in step: the range is cut where any layer changes, so a held background stretches with the character. `--pingpong` (a b c d c b) and repeated drawings become links. On every layer (no `--layers`) clips and later frames move with it.
+- `klad copy` gives the copies new ids and prints the map (`c1:s3 -> c9:s12`); copying from a key into another drawing keeps the copies unpaired with the original ids, so prefer `cel dup` when you want ids kept.
+- The in-between and `--like` ops need a batch of their own in `klad apply`.
+
+### Clips
+
+A clip is a named frame range (both ends included) that exports as one animation: `idle`, `run`, `attack`. It loops or plays once, and may have its own fps (otherwise the document's).
+
+```
+klad clip art.draw # list: frames, length in s at its fps, loops or once
+klad clip art.draw --add run --from 0 --to 11 --loop --fps 24
+klad clip art.draw --set run --to 15 --no-loop # change; --name sprint renames, --fps doc drops its own fps
+klad clip art.draw --rm run
+klad timeline art.draw --origin 512,700 # the canvas point a Godot export puts on the node (default the centre)
+```
+
+In `apply`: `{"op":"clip","add":"run","from":0,"to":11,"loop":true,"fps":24}`, `{"op":"clip","set":"run","name":"sprint","fps":null}`, `{"op":"clip","rm":"run"}`, `{"op":"timeline","origin":[512,700]}`. Frames inserted or removed on every layer move and stretch clips (an insert inside a clip lengthens it); on listed layers they leave clips alone. `klad frames` marks clips on the right (`[run` first frame, `run]` last) and lists them under the sheet. In the editor clips are bars on the strip above the frame numbers, and Return plays the clip under the playhead at its fps.
+
+### Animation exports
+
+```
+klad export art.draw --sheet all [--scale 0.5] [--padding 2] [--max 4096] [--depth 16]
+klad export art.draw --sheet run -o out/run.png
+klad export art.draw --frames run # run-0000.png ... full size, one per frame, in art-run/
+klad export art.draw --godot ../game/art/hero # first time: the folder is kept in the document
+klad export art.draw --godot # later: the kept folder (the editor's button does the same)
+```
+
+- `--sheet all` exports every clip (or the whole timeline as `default` when there are none), `--sheet <clip>` one, `--sheet 0-11` a range. The PNG holds each distinct picture once (holds, links and frames that render the same share one), trimmed to its pixels, in order of first appearance; beyond `--max` it goes to more pages (`art-sheet-2.png`, ...). The JSON is Aseprite's array layout: one entry per exposure with `duration` in ms at the clip's fps (a clip's durations add up to its length), `frame` (rect in the page), `spriteSourceSize` (the trim) and `sourceSize`, plus `frameTags` per clip (`repeat: "1"` when it plays once). Entries on later pages carry `image`.
+- `--godot <folder>` writes `art.png` (and pages), `art.tres` (a `SpriteFrames`: an `AtlasTexture` per picture with its trim as margin, one animation per clip with its name, speed, loop and per-frame durations in frames) and `art.tscn` (an `AnimatedSprite2D`, autoplaying the first clip, offset so the origin sits on the node's position). Re-exports keep the uids of the `.tres`, `.tscn` and the imported PNG, so scenes using them keep working. `--store` replaces a kept folder; the kept path (`export.godot`) is relative to the folder holding the bundle.
+- Exports print a pixel hash per page and of the JSON on stderr. The bounce (`samples/bounce/build.sh`) exports in about 0.25 s; 40 distinct 1024 frames to Godot in about 1.4 s warm, 2.3 s cold.
+
+See the motion before reading single frames:
+
+```
+klad render art.draw --sheet all # every frame in one grid: frame number, drawing ids, holds
+klad render art.draw --sheet 0-11 --drawings # one cell per drawing: frames that look the same share a cell ("4-5")
+klad render art.draw --sheet run --cell 192 # a clip by name; --cell is the longest side of a cell, --columns n
+klad render art.draw --frame 5 --overlay onion # drawings before (red) and after (green) under each layer
+klad render art.draw --frame 5 --onion 1,3 --onion-layers lines --onion-by frames --no-tint
+klad render art.draw --sheet 0-7 --overlay onion --onion-loop 0-7 # onion in every cell, wrapping inside a loop
+```
+
+Cell labels read like `klad frames`: `c5` starts a drawing, `|c5` holds it, `c9>c1` shows c1 again through a link, `.` is blank, and a grey title with `hold` means the frame looks exactly like the one before. Onion skin is under the layer it belongs to, faded with distance (counted in drawings unless `--onion-by frames`); without `--onion-layers` every layer with more than one drawing shows its own. A sheet of 24 frames of a 2048 canvas takes about 0.3 s; onion in a sheet costs more (about 0.8 s for one layer, 2 s for four). Render prints a pixel hash on its second line, handy for comparing with the Mac.
+
+## Traps
+
+- `--sheet` renders whole frames: it refuses `--focus`, `--region` and `--scale` (size the cells with `--cell`). For a close-up of one frame use `--frame n --focus <id>`.
+
+- Strokes and fills only go into paint layers; nodes only into vector layers.
+- `klad fill` and `klad stroke` take the target layer by id; `--ref` also takes a name.
+- A cel without `hold` lasts until the next cel, so a stroke or node at a later frame lands in that drawing unless the frame starts a cel (`klad cel new` first). A frame past the end of the timeline starts a cel and lengthens the timeline.
+- Painting at a frame that shows a link fails from the CLI (paint into the source cel's frame instead); the editor paints into the source.
+- `klad ls` on huge scenes lists 24 nodes per container; use `ls --json` or `show <group id>` for the rest.
+- The editor rasterises vector layers; very large vector layers take a moment to refresh after an edit.
+- `klad path` numbers points across all subpaths of the shape; re-read the list after `--add`, `--insert` or `--rm`.
+- A layer created with `lockAlpha=true` takes no paint at all until something without the lock lands on it first; paint the flats, then lock.
+- A clipped layer at the bottom of its list has no base and draws unclipped. Hiding a base hides its clipped layers.
+- `klad export --layer` on a clipped layer draws it alone, unclipped; export the group or the whole image to see the clip.
+- Animation exports draw every visible layer, so a held background (a floor) is in every picture and trimming keeps its width. Hide it, or pass `--layer <character group>`, for a sprite.
+- `--sheet` on `render` is a labelled look at the frames; `--sheet` on `export` is the game asset. They take the same specs.
+- `klad inbetween --to` is the frame where the second key starts; a frame inside its exposure is refused with the right frame named.
+- In-betweens keep the first key's mark ids, so after a loop in-between the ids are the last key's: look marks up by part (`klad strokes` shows each mark's part), not by an id from another key.
+- `klad arcs` tracks a part on the first paint layer that has it; name the layer (`far:far leg`) when parts share names across layers (body is on lines, shade and rim).
+- In-betweens of keys on a layer with other drawings between them are refused (they would be removed); `--force` replaces them.
+- A closed outline drawn as one stroke (a leaf, an eye) is fine to in-between; its own start and end meeting is not a join.
+- `ink`, `light`, `hatch` and `scatter` take shape ids, not layer ids; a group means every shape in it. `light`, `hatch`, `scatter` and `fill --shape` need closed outlines (an open path inks, but has no area).
+- `klad light` adds fills, it does not replace earlier ones: run it once per set of shapes, or undo before running it again with other settings. So do `klad paint` and `klad hatch`.
+- Gradient centres and ends are in the node's own coordinates: canvas px for a node without a transform. A radial centred on `[0,0]` under an ellipse at `cx=930` is transparent where the ellipse is; put the centre at the ellipse's centre, or draw the node around 0,0 and move it with `transform`.
+- An edit that finds the document changed under it (the user saved while `klad` was computing, most likely during `inbetween` or `fill --like`) writes nothing, says "the document changed while this edit was being made", and exits with code 75. Run the same command again; it starts from his change.
diff --git a/docs/skill/drawkit.py b/docs/skill/drawkit.py
new file mode 100644
index 0000000..ced5425
--- /dev/null
+++ b/docs/skill/drawkit.py
@@ -0,0 +1,265 @@
+import json
+import math
+import random
+import sys
+
+rnd = random.Random(7)
+
+
+def seed(n):
+ rnd.seed(n)
+
+
+def sub(a, b):
+ return tuple(x - y for x, y in zip(a, b))
+
+
+def addv(a, b):
+ return tuple(x + y for x, y in zip(a, b))
+
+
+def mul(a, k):
+ return tuple(x * k for x in a)
+
+
+def dot(a, b):
+ return sum(x * y for x, y in zip(a, b))
+
+
+def cross(a, b):
+ return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
+
+
+def norm(v):
+ d = math.sqrt(dot(v, v)) or 1.0
+ return tuple(x / d for x in v)
+
+
+def lerp(a, b, t):
+ return tuple(x + (y - x) * t for x, y in zip(a, b))
+
+
+class Camera:
+ def __init__(self, eye, focal, centre, horizon):
+ self.eye, self.focal, self.cx, self.horizon = tuple(eye), focal, centre, horizon
+
+ def project(self, p):
+ x, y, z = sub(p, self.eye)
+ z = max(z, 1e-3)
+ return (self.cx + self.focal * x / z, self.horizon - self.focal * y / z)
+
+ def to_eye(self, p):
+ return norm(sub(self.eye, p))
+
+ def faces_viewer(self, point, normal):
+ return dot(normal, self.to_eye(point)) > 0
+
+
+def hull(points):
+ pts = sorted(set((round(x, 3), round(y, 3)) for x, y in points))
+ if len(pts) < 3:
+ return pts
+
+ def half(ps):
+ out = []
+ for p in ps:
+ while len(out) >= 2 and (out[-1][0] - out[-2][0]) * (p[1] - out[-2][1]) - (out[-1][1] - out[-2][1]) * (p[0] - out[-2][0]) <= 0:
+ out.pop()
+ out.append(p)
+ return out[:-1]
+
+ return half(pts) + half(pts[::-1])
+
+
+def box(centre, size, yaw=0.0):
+ sx, sy, sz = size
+ c, s = math.cos(yaw), math.sin(yaw)
+ corners = {}
+ for ix in (-1, 1):
+ for iy in (0, 1):
+ for iz in (-1, 1):
+ lx, lz = ix * sx / 2, iz * sz / 2
+ corners[(ix, iy, iz)] = (centre[0] + lx * c - lz * s, centre[1] + iy * sy, centre[2] + lx * s + lz * c)
+ faces = {
+ "top": ([(-1, 1, -1), (1, 1, -1), (1, 1, 1), (-1, 1, 1)], (0.0, 1.0, 0.0)),
+ "bottom": ([(-1, 0, -1), (1, 0, -1), (1, 0, 1), (-1, 0, 1)], (0.0, -1.0, 0.0)),
+ "x-": ([(-1, 0, -1), (-1, 0, 1), (-1, 1, 1), (-1, 1, -1)], (-c, 0.0, -s)),
+ "x+": ([(1, 0, -1), (1, 0, 1), (1, 1, 1), (1, 1, -1)], (c, 0.0, s)),
+ "z-": ([(-1, 0, -1), (1, 0, -1), (1, 1, -1), (-1, 1, -1)], (s, 0.0, -c)),
+ "z+": ([(-1, 0, 1), (1, 0, 1), (1, 1, 1), (-1, 1, 1)], (-s, 0.0, c)),
+ }
+ return corners, {name: ([corners[k] for k in keys], n) for name, (keys, n) in faces.items()}
+
+
+def visible_faces(camera, faces):
+ out = {}
+ for name, (pts, n) in faces.items():
+ centre = mul(tuple(sum(c) for c in zip(*pts)), 1 / len(pts))
+ if camera.faces_viewer(centre, n):
+ out[name] = (pts, n)
+ return out
+
+
+def sphere_points(centre, radius, rings=24, sides=48):
+ return [addv(centre, (radius * math.sin(ph) * math.cos(th), radius * math.cos(ph), radius * math.sin(ph) * math.sin(th)))
+ for th in [2 * math.pi * i / sides for i in range(sides)] for ph in [math.pi * j / (rings - 1) for j in range(rings)]]
+
+
+def circle_points(centre, radius, n=72, y=0.0):
+ return [(centre[0] + radius * math.cos(2 * math.pi * i / n), centre[1] + y, centre[2] + radius * math.sin(2 * math.pi * i / n)) for i in range(n)]
+
+
+def cylinder_points(base, radius, height, n=72):
+ return circle_points(base, radius, n) + circle_points(base, radius, n, height)
+
+
+def extrusion_points(outline, height):
+ return [p for x, z in outline for p in ((x, 0.0, z), (x, height, z))]
+
+
+def silhouette(camera, points3):
+ return hull([camera.project(p) for p in points3])
+
+
+def shadow(points3, toward_light, ground=0.0):
+ l = norm(toward_light)
+ if l[1] <= 1e-6:
+ raise ValueError("the light must come from above the ground to cast a shadow")
+ return [(p[0] - l[0] * (p[1] - ground) / l[1], ground, p[2] - l[2] * (p[1] - ground) / l[1]) for p in points3]
+
+
+def shadow_shape(camera, points3, toward_light, ground=0.0):
+ return hull([camera.project(p) for p in points3 + shadow(points3, toward_light, ground) if p[1] <= ground + 1e-6])
+
+
+def encode(c):
+ c = max(0.0, min(1.0, c))
+ return 12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055
+
+
+def hexc(rgb, alpha=None):
+ out = "#" + "".join(f"{round(encode(c) * 255):02x}" for c in rgb)
+ return out if alpha is None else out + f"{round(max(0.0, min(1.0, alpha)) * 255):02x}"
+
+
+def path(points):
+ return "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)
+
+
+def poly(points):
+ return path(points) + " Z"
+
+
+def resample(points, n):
+ lengths = [0.0]
+ for a, b in zip(points, points[1:]):
+ lengths.append(lengths[-1] + math.dist(a, b))
+ total = lengths[-1] or 1.0
+ out = []
+ for i in range(n):
+ target = total * i / (n - 1)
+ k = max(1, next((j for j, l in enumerate(lengths) if l >= target), len(lengths) - 1))
+ a, b = points[k - 1], points[k]
+ seg = (lengths[k] - lengths[k - 1]) or 1.0
+ t = (target - lengths[k - 1]) / seg
+ out.append((a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t))
+ return out, total
+
+
+def hand(points, bow=True, strength=1.0):
+ pts, length = resample(points, 11)
+ attack, release = rnd.uniform(0.12, 0.35), rnd.uniform(0.2, 0.5)
+ start, peak, end = rnd.uniform(0.08, 0.3), rnd.uniform(0.82, 1.0), rnd.uniform(0.03, 0.18)
+ sway, arc, width = rnd.uniform(-0.06, 0.06), rnd.uniform(-0.05, 0.05), rnd.uniform(0.65, 1.35)
+ tin, tout = rnd.uniform(0.4, 0.8), rnd.uniform(0.5, 0.9)
+ (x0, y0), (x1, y1) = pts[0], pts[-1]
+ dx, dy = x1 - x0, y1 - y0
+ d = math.hypot(dx, dy) or 1.0
+ bend = arc * length * strength if bow else 0.0
+ pts = [(x - dy / d * bend * math.sin(math.pi * i / 10), y + dx / d * bend * math.sin(math.pi * i / 10)) for i, (x, y) in enumerate(pts)]
+
+ def ease(a, b, u):
+ u = max(0.0, min(1.0, u))
+ return a + (b - a) * (3 * u * u - 2 * u * u * u)
+
+ pressure = []
+ for i in range(11):
+ t = i / 10
+ if t < attack:
+ p = ease(start, peak, t / attack)
+ elif t > 1 - release:
+ p = ease(peak, end, (t - (1 - release)) / release)
+ else:
+ p = peak * (1 - sway * math.sin(math.pi * (t - attack) / max(0.01, 1 - attack - release)))
+ pressure.append(round(max(0.02, min(1.0, 1 - strength + strength * p)), 3))
+ taper = [round(strength * length * attack * tin, 1), round(strength * length * release * tout, 1)]
+ return pts, pressure, taper, 1 + strength * (width - 1)
+
+
+def stroke(layer, brush, size, rgb, points, opacity=1.0, bow=True, strength=1.0, frame=0):
+ pts, pressure, taper, width = hand(points, bow, strength)
+ op = {"op": "stroke", "layer": layer, "brush": brush, "size": round(size * width, 1), "color": hexc(rgb) if isinstance(rgb, tuple) else rgb,
+ "path": path(pts), "pressure": pressure, "taper": taper, "frame": frame}
+ if opacity < 1:
+ op["opacity"] = round(opacity, 2)
+ return op
+
+
+def vector_layer(id, name, **extra):
+ return {"op": "add", "layer": {"id": id, "kind": "vector", "name": name, **extra}}
+
+
+def paint_layer(id, name, shape=None, colour=None, **extra):
+ ops = [{"op": "add", "layer": {"id": id, "kind": "paint", "name": name, **extra}}]
+ if shape:
+ ops.append({"op": "fill", "layer": id, "shape": shape, "color": hexc(colour) if isinstance(colour, tuple) else colour})
+ ops.append({"op": "set", "id": id, "lockAlpha": True})
+ return ops
+
+
+def add(into, node):
+ return {"op": "add", "node": node, "in": into}
+
+
+def emit(ops, out=sys.stdout):
+ out.write("\n".join(json.dumps(o) for o in ops) + "\n")
+
+
+def check():
+ cam = Camera((0.0, 34.0, 0.0), 1500.0, 600.0, 170.0)
+ corners, faces = box((16.0, 0.0, 101.0), (17.0, 17.0, 17.0), math.radians(33))
+
+ def meet(a, b, c, d):
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = (cam.project(p) for p in (a, b, c, d))
+ den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
+ t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
+ return (x1 + t * (x2 - x1), y1 + t * (y2 - y1))
+
+ left = meet(corners[(-1, 0, -1)], corners[(-1, 0, 1)], corners[(1, 1, -1)], corners[(1, 1, 1)])
+ right = meet(corners[(-1, 0, -1)], corners[(1, 0, -1)], corners[(-1, 1, 1)], corners[(1, 1, 1)])
+ assert abs(left[1] - cam.horizon) < 0.5 and abs(right[1] - cam.horizon) < 0.5, (left, right)
+ near, far = cam.project(corners[(-1, 0, -1)]), cam.project(corners[(1, 0, 1)])
+ near_h = near[1] - cam.project(corners[(-1, 1, -1)])[1]
+ far_h = far[1] - cam.project(corners[(1, 1, 1)])[1]
+ assert near_h > far_h, (near_h, far_h)
+ assert set(visible_faces(cam, faces)) == {"top", "x-", "z-"}, set(visible_faces(cam, faces))
+
+ def roundness(y):
+ ring = [cam.project(p) for p in circle_points((-27.0, 0.0, 112.0), 5.0, 72, y)]
+ xs, ys = [p[0] for p in ring], [p[1] for p in ring]
+ return (max(ys) - min(ys)) / (max(xs) - min(xs))
+
+ assert roundness(0.0) > roundness(16.0) > 0.0
+ toward = (-0.47, 0.86, -0.21)
+ cast = shadow([(0.0, 10.0, 100.0)], toward)[0]
+ assert cast[1] == 0.0 and cast[0] > 0.0 and cast[2] > 100.0, cast
+ seed(3)
+ pts, pressure, taper, width = hand([(0, 0), (120, 0)], bow=False)
+ assert pressure[0] < max(pressure) * 0.5 and pressure[-1] < max(pressure) * 0.4 and taper[1] > 0 and all(abs(y) < 1e-9 for _, y in pts)
+ seed(3)
+ assert hand([(0, 0), (120, 0)], bow=False) == (pts, pressure, taper, width)
+ print("drawkit: vanishing points on one horizon, far edges shorter, rims rounder away from eye level, shadows away from the light, hands repeat: ok")
+
+
+if __name__ == "__main__" and "--check" in sys.argv:
+ check()
diff --git a/justfile b/justfile
new file mode 100644
index 0000000..6c4492d
--- /dev/null
+++ b/justfile
@@ -0,0 +1,53 @@
+target_dir := env("CARGO_TARGET_DIR", "target")
+klad := target_dir + "/release/klad"
+
+default: build
+
+build:
+ cargo build --release -p klad-cli
+
+test:
+ cargo test --workspace
+ python3 docs/skill/drawkit.py --check
+
+lint:
+ cargo fmt --all --check
+ cargo clippy --workspace --all-targets -- -D warnings
+
+samples: build
+ for s in lantern ink-shapes bounce creature solids; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; done
+
+notices:
+ bash licenses/notices.sh
+
+notices-check:
+ bash licenses/notices.sh "${TMPDIR:-/tmp}/draw-notices.md"
+ diff -q "${TMPDIR:-/tmp}/draw-notices.md" THIRD-PARTY-NOTICES.md
+
+audit: notices-check
+ cargo deny check
+
+fmt:
+ cargo fmt --all
+
+bench *args: build
+ {{klad}} bench {{args}}
+
+demo bundle="scratch/demo.draw": build
+ {{klad}} demo {{bundle}} --force
+ {{klad}} render {{bundle}}
+
+hash bundle="scratch/demo.draw": build
+ {{klad}} hash {{bundle}} --no-cache
+
+open bundle="scratch/pen.draw": build
+ {{klad}} open {{bundle}}
+
+stress bundle="scratch/stress.draw": build
+ {{klad}} stress {{bundle}}
+
+ui-pictures:
+ cargo test -p klad-app -- --ignored panel_pictures
+
+ui-time:
+ cargo test --release -p klad-app -- --ignored ui_time_per_frame --nocapture
diff --git a/licenses/about.hbs b/licenses/about.hbs
new file mode 100644
index 0000000..4cca033
--- /dev/null
+++ b/licenses/about.hbs
@@ -0,0 +1,19 @@
+# Third-party notices
+
+klad is source-available under the PolyForm Internal Use License 1.0.0 with additional permissions (see LICENSE), copyright Indicode BV. It is built on the open source work below. This file is generated by `just notices` from the Rust crates in `Cargo.lock` (cargo-about), followed by the parts Cargo does not see: the Skia library and what is built into it, and the fonts.
+
+## Rust crates
+
+{{#each licenses}}
+### {{{name}}}
+
+Used by:
+{{#each used_by}}
+- {{crate.name}} {{crate.version}}{{#if crate.repository}} ({{crate.repository}}){{/if}}
+{{/each}}
+
+```text
+{{{text}}}
+```
+
+{{/each}}
diff --git a/licenses/about.toml b/licenses/about.toml
new file mode 100644
index 0000000..bb2ab6c
--- /dev/null
+++ b/licenses/about.toml
@@ -0,0 +1,27 @@
+accepted = [
+ "MIT",
+ "Apache-2.0",
+ "Apache-2.0 WITH LLVM-exception",
+ "BSD-2-Clause",
+ "BSD-3-Clause",
+ "ISC",
+ "Zlib",
+ "BSL-1.0",
+ "Unicode-3.0",
+ "CC0-1.0",
+ "0BSD",
+ "Unlicense",
+ "OFL-1.1",
+ "Ubuntu-font-1.0",
+]
+targets = [
+ "aarch64-apple-darwin",
+ "x86_64-apple-darwin",
+ "x86_64-unknown-linux-gnu",
+ "aarch64-unknown-linux-gnu",
+ "x86_64-pc-windows-msvc",
+]
+ignore-build-dependencies = true
+ignore-dev-dependencies = true
+ignore-transitive-dependencies = false
+private = { ignore = true }
diff --git a/licenses/bundled/egui-icons.txt b/licenses/bundled/egui-icons.txt
new file mode 100644
index 0000000..96d584d
--- /dev/null
+++ b/licenses/bundled/egui-icons.txt
@@ -0,0 +1,23 @@
+egui-icons.ttf
+
+A subset of emoji-icon-font.ttf (https://github.com/jslegers/emoji-icon-font),
+containing only the five glyphs that egui exposes as `egui::special_emojis`:
+
+ U+E618 the Android logo
+ U+E61F the Windows logo
+ U+E624 the GitHub logo
+ U+E625 the word `git`
+ U+F8FF the Apple logo
+
+No platform font has these, so egui bundles them even when the rest of
+emoji-icon-font.ttf is left out (the `monochrome_emoji_fonts` feature).
+
+Regenerate with:
+
+ pip install fonttools
+ python3 -m fontTools.subset emoji-icon-font.ttf \
+ --unicodes=E618,E61F,E624,E625,F8FF \
+ --no-hinting --desubroutinize \
+ --output-file=egui-icons.ttf
+
+The license is that of emoji-icon-font.ttf: see emoji-icon-font-mit-license.txt.
diff --git a/licenses/bundled/emoji-icon-font.txt b/licenses/bundled/emoji-icon-font.txt
new file mode 100644
index 0000000..99016e1
--- /dev/null
+++ b/licenses/bundled/emoji-icon-font.txt
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2014 John Slegers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/licenses/bundled/expat.txt b/licenses/bundled/expat.txt
new file mode 100644
index 0000000..c6d184a
--- /dev/null
+++ b/licenses/bundled/expat.txt
@@ -0,0 +1,21 @@
+Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper
+Copyright (c) 2001-2025 Expat maintainers
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/licenses/bundled/hack.txt b/licenses/bundled/hack.txt
new file mode 100644
index 0000000..b0ec744
--- /dev/null
+++ b/licenses/bundled/hack.txt
@@ -0,0 +1,31 @@
+The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
+
+The work in the DejaVu project was committed to the public domain.
+
+Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
+MIT License
+
+Copyright (c) 2018 Source Foundry Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+BITSTREAM VERA LICENSE
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
+
+The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
+
+The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
diff --git a/licenses/bundled/libjpeg-turbo-ijg.txt b/licenses/bundled/libjpeg-turbo-ijg.txt
new file mode 100644
index 0000000..dbf8070
--- /dev/null
+++ b/licenses/bundled/libjpeg-turbo-ijg.txt
@@ -0,0 +1,260 @@
+libjpeg-turbo note: This file has been modified by The libjpeg-turbo Project
+to include only information relevant to libjpeg-turbo, to wordsmith certain
+sections, and to remove impolitic language that existed in the libjpeg v8
+README. It is included only for reference. Please see README.md for
+information specific to libjpeg-turbo.
+
+
+The Independent JPEG Group's JPEG software
+==========================================
+
+This distribution contains a release of the Independent JPEG Group's free JPEG
+software. You are welcome to redistribute this software and to use it for any
+purpose, subject to the conditions under LEGAL ISSUES, below.
+
+This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone,
+Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson,
+Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers,
+and other members of the Independent JPEG Group.
+
+IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee
+(also known as JPEG, together with ITU-T SG16).
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ doc/usage.txt Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ doc/*.1 Unix-style man pages for programs (same info as
+ usage.txt).
+ doc/wizard.txt Advanced usage instructions for JPEG wizards only.
+ doc/change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ doc/libjpeg.txt How to use the JPEG library in your own programs.
+ src/example.c Sample code for calling the JPEG library.
+ doc/structure.txt Overview of the JPEG library's internal structure.
+ doc/coderules.txt Coding style rules --- please read if you contribute
+ code.
+
+Please read at least usage.txt. Some information can also be found in the JPEG
+FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find
+out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image encoding, decoding,
+and transcoding. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and grayscale images. JPEG's strong suit is compressing
+photographic images or other types of images that have smooth color and
+brightness transitions between neighboring pixels. Images with sharp lines or
+other abrupt features may not compress well with JPEG, and a higher JPEG
+quality may have to be used to avoid visible compression artifacts with such
+images.
+
+JPEG is normally lossy, meaning that the output pixels are not necessarily
+identical to the input pixels. However, on photographic content and other
+"smooth" images, very good compression ratios can be obtained with no visible
+compression artifacts, and extremely high compression ratios are possible if
+you are willing to sacrifice image quality (by reducing the "quality" setting
+in the compressor.)
+
+This software implements JPEG baseline, extended-sequential, progressive, and
+lossless compression processes. Provision is made for supporting all variants
+of these processes, although some uncommon parameter settings aren't
+implemented yet. We have made no provision for supporting the hierarchical
+processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats. These
+extra functions can be compiled out of the library if not required for a
+particular application.
+
+We have also included "jpegtran", a utility for lossless transcoding between
+different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple
+applications for inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+REFERENCES
+==========
+
+We recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PDF file containing a revised version of Wallace's article is
+available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best currently available description of JPEG is the textbook "JPEG Still
+Image Data Compression Standard" by William B. Pennebaker and Joan L.
+Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.
+Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG
+standards (DIS 10918-1 and draft DIS 10918-2).
+
+The original JPEG standard is divided into two parts, Part 1 being the actual
+specification, while Part 2 covers compliance testing methods. Part 1 is
+titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details, we follow the "JFIF" conventions, revision
+1.02. JFIF version 1 has been adopted as ISO/IEC 10918-5 (05/2013) and
+Recommendation ITU-T T.871 (05/2011): Information technology - Digital
+compression and coding of continuous-tone still images: JPEG File Interchange
+Format (JFIF). It is available as a free download in PDF file format from
+https://www.iso.org/standard/54989.html and http://www.itu.int/rec/T-REC-T.871.
+A PDF file of the older JFIF 1.02 specification is available at
+http://www.w3.org/Graphics/JPEG/jfif3.pdf.
+
+The TIFF 6.0 file format specification can be obtained from
+http://mirrors.ctan.org/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation
+scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious
+problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression
+tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note
+#2 (Compression tag 7). Copies of this Note can be obtained from
+http://www.ijg.org/files/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is www.ijg.org.
+The most recent released version can always be found there in
+directory "files".
+
+The JPEG FAQ (Frequently Asked Questions) article is a source of some
+general information about JPEG. It is available at
+http://www.faqs.org/faqs/jpeg-faq.
+
+
+FILE FORMAT COMPATIBILITY
+=========================
+
+This software implements ITU T.81 | ISO/IEC 10918 with some extensions from
+ITU T.871 | ISO/IEC 10918-5 (JPEG File Interchange Format-- see REFERENCES).
+Informally, the term "JPEG image" or "JPEG file" most often refers to JFIF or
+a subset thereof, but there are other formats containing the name "JPEG" that
+are incompatible with the original JPEG standard or with JFIF (for instance,
+JPEG 2000 and JPEG XR). This software therefore does not support these
+formats. Indeed, one of the original reasons for developing this free software
+was to help force convergence on a common, interoperable format standard for
+JPEG files.
+
+JFIF is a minimal or "low end" representation. TIFF/JPEG (TIFF revision 6.0 as
+modified by TIFF Technical Note #2) can be used for "high end" applications
+that need to record a lot of additional data about an image.
+
+
+TO DO
+=====
+
+Please send bug reports, offers of help, etc. to [email protected].
diff --git a/licenses/bundled/libjpeg-turbo.md b/licenses/bundled/libjpeg-turbo.md
new file mode 100644
index 0000000..37a489b
--- /dev/null
+++ b/licenses/bundled/libjpeg-turbo.md
@@ -0,0 +1,147 @@
+libjpeg-turbo Licenses
+======================
+
+libjpeg-turbo is covered by two compatible BSD-style open source licenses:
+
+- The IJG (Independent JPEG Group) License, which is listed in
+ [README.ijg](README.ijg)
+
+ This license applies to the libjpeg API library and associated programs,
+ including any code inherited from libjpeg and any modifications to that
+ code.
+
+- The Modified (3-clause) BSD License, which is listed below
+
+ This license applies to the TurboJPEG API library and associated programs,
+ [libspng](https://libspng.org) (which is used by cjpeg and djpeg), and the
+ build/test system.
+
+ * The TurboJPEG API library wraps the libjpeg API library, so in the context
+ of the overall TurboJPEG API library, both the terms of the IJG License and
+ the terms of the Modified (3-clause) BSD License apply.
+ * cjpeg and djpeg use libspng, so in the context of those programs, both the
+ terms of the IJG License and the terms of the Modified (3-clause) BSD
+ License apply.
+
+
+Component Licenses
+==================
+
+Some of libjpeg-turbo's modules and internal dependencies are covered by less
+restrictive licenses, but in the context of libjpeg-turbo as a whole, the terms
+of the less restrictive licenses are subsumed by either the IJG License or the
+Modified BSD License. (In other words, the terms of the less restrictive
+licenses are satisfied if the terms of the IJG and Modified BSD Licenses are
+satisfied.)
+
+- The libjpeg-turbo SIMD source code and zlib are covered by the
+ [zlib License](https://spdx.org/licenses/Zlib.html), which is subsumed by the
+ IJG License in the context of the cjpeg and djpeg programs and the libjpeg
+ API library.
+
+- Some of the libspng source code is covered by the
+ [PNG Reference Library License v2](https://spdx.org/licenses/libpng-2.0.html),
+ which is subsumed by the IJG License in the context of the cjpeg and djpeg
+ programs and the TurboJPEG API library.
+
+- Most of the libspng source code is covered by the
+ [Simplified (2-clause) BSD License](https://spdx.org/licenses/BSD-2-Clause.html),
+ which is subsumed by the Modified BSD License in the context of the cjpeg and
+ djpeg programs and the TurboJPEG API library.
+
+
+Complying with the libjpeg-turbo Licenses
+=========================================
+
+This section provides a roll-up of the libjpeg-turbo licensing terms, to the
+best of our understanding. This is not a license in and of itself. It is
+intended solely for clarification.
+
+1. If you are distributing a modified version of the libjpeg-turbo source,
+ then:
+
+ 1. You cannot alter or remove any existing copyright or license notices
+ from the source.
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 1 of the Modified BSD License
+
+ 2. You must add your own copyright notice to the header of each source
+ file you modified, so others can tell that you modified that file. (If
+ there is not an existing copyright header in that file, then you can
+ simply add a notice stating that you modified the file.)
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+ 3. You must include the IJG README file, and you must not alter any of the
+ copyright or license text in that file.
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+2. If you are distributing only libjpeg-turbo binaries without the source, or
+ if you are distributing an application that statically links with
+ libjpeg-turbo, then:
+
+ 1. Your product documentation must include a message stating:
+
+ This software is based in part on the work of the Independent JPEG
+ Group.
+
+ **Origin**
+ - Clause 2 of the IJG license
+
+ 2. If your binary distribution includes or uses the TurboJPEG API or
+ associated programs, cjpeg, or djpeg, then your product documentation
+ must include the text of the Modified BSD License (see below.)
+
+ **Origin**
+ - Clause 2 of the Modified BSD License
+
+3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
+ contributors thereof in advertising, publicity, etc.
+
+ **Origin**
+ - IJG License
+ - Clause 3 of the Modified BSD License
+
+4. The authors and distributors do not warrant libjpeg-turbo to be free of
+ defects, nor do we accept any liability for undesirable consequences
+ resulting from your use of the software.
+
+ **Origin**
+ - IJG License
+ - Modified BSD License
+
+
+The Modified (3-clause) BSD License
+===================================
+
+Copyright (C) 2009-2026 D. R. Commander<br>
+Copyright (C) 2018-2023 Randy <[email protected]>
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+- Neither the name of the libjpeg-turbo Project nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/bundled/libpng.txt b/licenses/bundled/libpng.txt
new file mode 100644
index 0000000..1b765ae
--- /dev/null
+++ b/licenses/bundled/libpng.txt
@@ -0,0 +1,134 @@
+COPYRIGHT NOTICE, DISCLAIMER, and LICENSE
+=========================================
+
+PNG Reference Library License version 2
+---------------------------------------
+
+ * Copyright (c) 1995-2026 The PNG Reference Library Authors.
+ * Copyright (c) 2018-2026 Cosmin Truta.
+ * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson.
+ * Copyright (c) 1996-1997 Andreas Dilger.
+ * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+The software is supplied "as is", without warranty of any kind,
+express or implied, including, without limitation, the warranties
+of merchantability, fitness for a particular purpose, title, and
+non-infringement. In no event shall the Copyright owners, or
+anyone distributing the software, be liable for any damages or
+other liability, whether in contract, tort or otherwise, arising
+from, out of, or in connection with the software, or the use or
+other dealings in the software, even if advised of the possibility
+of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute
+this software, or portions hereof, for any purpose, without fee,
+subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you
+ use this software in a product, an acknowledgment in the product
+ documentation would be appreciated, but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and must
+ not be misrepresented as being the original software.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+
+PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35)
+-----------------------------------------------------------------------
+
+libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
+
+ Simon-Pierre Cadieux
+ Eric S. Raymond
+ Mans Rullgard
+ Cosmin Truta
+ Gilles Vollant
+ James Yu
+ Mandar Sahastrabuddhe
+ Google Inc.
+ Vadim Barkov
+
+and with the following additions to the disclaimer:
+
+ There is no warranty against interference with your enjoyment of
+ the library or against infringement. There is no warranty that our
+ efforts or the library will fulfill any of your particular purposes
+ or needs. This library is provided with all faults, and the entire
+ risk of satisfactory quality, performance, accuracy, and effort is
+ with the user.
+
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners, and
+are released under other open source licenses.
+
+libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the
+list of Contributing Authors:
+
+ Tom Lane
+ Glenn Randers-Pehrson
+ Willem van Schaik
+
+libpng versions 0.89, June 1996, through 0.96, May 1997, are
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
+
+ John Bowler
+ Kevin Bracey
+ Sam Bushell
+ Magnus Holmgren
+ Greg Roelofs
+ Tom Tanner
+
+Some files in the "scripts" directory have other copyright owners,
+but are released under this license.
+
+libpng versions 0.5, May 1995, through 0.88, January 1996, are
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+For the purposes of this copyright and license, "Contributing Authors"
+is defined as the following set of individuals:
+
+ Andreas Dilger
+ Dave Martindale
+ Guy Eric Schalnat
+ Paul Schmidt
+ Tim Wegner
+
+The PNG Reference Library is supplied "AS IS". The Contributing
+Authors and Group 42, Inc. disclaim all warranties, expressed or
+implied, including, without limitation, the warranties of
+merchantability and of fitness for any purpose. The Contributing
+Authors and Group 42, Inc. assume no liability for direct, indirect,
+incidental, special, exemplary, or consequential damages, which may
+result from the use of the PNG Reference Library, even if advised of
+the possibility of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+source code, or portions hereof, for any purpose, without fee, subject
+to the following restrictions:
+
+ 1. The origin of this source code must not be misrepresented.
+
+ 2. Altered versions must be plainly marked as such and must not
+ be misrepresented as being the original source.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+The Contributing Authors and Group 42, Inc. specifically permit,
+without fee, and encourage the use of this source code as a component
+to supporting the PNG file format in commercial products. If you use
+this source code in a product, acknowledgment is not required but would
+be appreciated.
diff --git a/licenses/bundled/phosphor.txt b/licenses/bundled/phosphor.txt
new file mode 100644
index 0000000..c04a19d
--- /dev/null
+++ b/licenses/bundled/phosphor.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020-2021 Phosphor Icons
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/licenses/bundled/skia.txt b/licenses/bundled/skia.txt
new file mode 100644
index 0000000..e32636d
--- /dev/null
+++ b/licenses/bundled/skia.txt
@@ -0,0 +1,29 @@
+Copyright (c) 2011 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/bundled/wuffs.txt b/licenses/bundled/wuffs.txt
new file mode 100644
index 0000000..279e3cc
--- /dev/null
+++ b/licenses/bundled/wuffs.txt
@@ -0,0 +1,211 @@
+This software is distributed under the terms of both the MIT license and the
+Apache License (Version 2.0).
+
+
+MIT license
+
+Copyright 2023 The Wuffs Authors
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+Apache 2 license
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/licenses/bundled/zlib.txt b/licenses/bundled/zlib.txt
new file mode 100644
index 0000000..b7a69d0
--- /dev/null
+++ b/licenses/bundled/zlib.txt
@@ -0,0 +1,22 @@
+Copyright notice:
+
+ (C) 1995-2026 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
diff --git a/licenses/notices.sh b/licenses/notices.sh
new file mode 100755
index 0000000..a4cc5eb
--- /dev/null
+++ b/licenses/notices.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+out="${1:-$here/../THIRD-PARTY-NOTICES.md}"
+crates="$(mktemp)"
+trap 'rm -f "$crates"' EXIT
+cargo about generate --config "$here/about.toml" "$here/about.hbs" -o "$crates" 2>/dev/null
+section() {
+ printf '### %s\n\n%s\n\n' "$1" "$2"
+ shift 2
+ for file in "$@"; do
+ printf '```text\n'
+ cat "$here/bundled/$file"
+ printf '\n```\n\n'
+ done
+}
+{
+ cat "$crates"
+ printf '## Built into Skia\n\n`skia-bindings` links a prebuilt Skia (m157) with these libraries compiled in. On Linux, FreeType and fontconfig come from the system and are not shipped.\n\n'
+ section "Skia" "The 2D library that draws every pixel. BSD 3-Clause." skia.txt
+ section "libpng" "PNG decoding and encoding inside Skia." libpng.txt
+ section "zlib" "Compression for PNG and PDF inside Skia." zlib.txt
+ section "libjpeg-turbo" "JPEG decoding and encoding inside Skia. IJG, BSD 3-Clause and zlib licences." libjpeg-turbo.md libjpeg-turbo-ijg.txt
+ section "Expat" "XML parsing inside Skia. MIT." expat.txt
+ section "Wuffs" "GIF decoding inside Skia. MIT and Apache-2.0." wuffs.txt
+ printf '## Fonts\n\nThe editor shows its interface in these fonts. Ubuntu Light (Ubuntu Font Licence) and Noto Emoji (SIL Open Font License) come with egui; their licence texts are above, under epaint_default_fonts.\n\n'
+ section "Phosphor icons" "The editor's icons. MIT." phosphor.txt
+ section "Hack" "egui's monospace font. MIT, with the Bitstream Vera licence for the glyphs it builds on." hack.txt
+ section "emoji-icon-font and egui-icons" "egui's icon glyphs. MIT." emoji-icon-font.txt egui-icons.txt
+} > "$out"
diff --git a/rust-toolchain.toml b/rust-toolchain.toml
new file mode 100644
index 0000000..d0ead5e
--- /dev/null
+++ b/rust-toolchain.toml
@@ -0,0 +1,3 @@
+[toolchain]
+channel = "stable"
+components = ["clippy", "rustfmt"]
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..7530651
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1 @@
+max_width = 120
diff --git a/samples/README.md b/samples/README.md
new file mode 100644
index 0000000..32da3db
--- /dev/null
+++ b/samples/README.md
@@ -0,0 +1,13 @@
+# Samples
+
+Drawings made from scratch with the `klad` CLI, each from a generator that prints ops as JSON lines into `klad apply`. They show how the pieces fit and give the tests and the parity checks something real to draw. `just samples` builds all of them (after `just build`); each `build.sh` also takes an output path, and refuses to overwrite a drawing that may hold edits unless `FORCE=1`.
+
+| Sample | Shows |
+|---|---|
+| `lantern` | A prop blocked in as shapes, then inked, filled, lit and hatched (`PAINTED=1`: painted by form instead) |
+| `ink-shapes` | The ink options side by side: weight from the light, breaks, gaps, wobble, tapers |
+| `bounce` | Frame-by-frame timing: keys, holds, a clip and the exports |
+| `creature` | A walk and an idle from keys with named parts, in-betweened, coloured from the first drawing, with arcs checked |
+| `solids` | Painting stroke by stroke: a sphere, a cube and a cylinder built in 3D with `docs/skill/drawkit.py`, lit, painted with natural strokes |
+
+The generated `.draw` bundles and pictures stay out of git.
diff --git a/samples/bounce/build.sh b/samples/bounce/build.sh
new file mode 100755
index 0000000..c29a500
--- /dev/null
+++ b/samples/bounce/build.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+klad="${KLAD:-$root/${CARGO_TARGET_DIR:-target}/release/klad}"
+out="${1:-$here/bounce.draw}"
+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then
+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2
+ exit 1
+fi
+rm -rf "$out"
+"$klad" new "$out" --width 1024 --height 768 --layers 0 --fps 12 --frames 20 --background '#f4efe6' >/dev/null
+python3 "$here/generate.py" | "$klad" apply "$out" >/dev/null
+"$klad" render "$out" --frame 7 -o "${out%.draw}.png"
+"$klad" frames "$out"
+"$klad" hash "$out" --all --no-cache
+echo "sheet and onion (the hash is on each second line):"
+"$klad" render "$out" --sheet all -o "${out%.draw}-sheet.png"
+"$klad" render "$out" --sheet all --drawings -o "${out%.draw}-drawings.png"
+"$klad" render "$out" --frame 5 --overlay onion -o "${out%.draw}-onion.png"
+echo "sprite sheets at 1x and 0.5x and a Godot export (hashes on the lines starting with hash):"
+"$klad" export "$out" --sheet all -o "${out%.draw}-sprites.png"
+"$klad" export "$out" --sheet all --scale 0.5 -o "${out%.draw}[email protected]"
+"$klad" export "$out" --godot "${out%.draw}-godot" >/dev/null
diff --git a/samples/bounce/generate.py b/samples/bounce/generate.py
new file mode 100644
index 0000000..836fa88
--- /dev/null
+++ b/samples/bounce/generate.py
@@ -0,0 +1,161 @@
+import json
+import math
+
+W, H = 1024, 768
+FLOOR = 610
+TOP = 190
+R = 74
+X = W / 2
+FRAMES = 20
+
+DRAWINGS = [
+ (0, 2, 0.0),
+ (2, 2, 0.12),
+ (4, 1, 0.36),
+ (5, 1, 0.56),
+ (6, 1, 0.8),
+ (7, 1, 1.0),
+ (8, 1, 0.82),
+ (9, 1, 0.6),
+ (10, 1, 0.42),
+ (11, 2, 0.22),
+ (13, 2, 0.06),
+]
+REST = (15, 5)
+
+
+def stretch(frame):
+ return {6: (0.86, 1.18), 7: (1.32, 0.7), 8: (0.88, 1.15), 5: (0.94, 1.07), 9: (0.94, 1.06)}.get(frame, (1.0, 1.0))
+
+
+def place(frame, depth):
+ sx, sy = stretch(frame)
+ y = TOP + (FLOOR - R * sy - TOP) * depth
+ return X, y, R * sx, R * sy
+
+
+def ellipse(cx, cy, rx, ry, steps=72, start=-math.pi / 2):
+ return [
+ (cx + rx * math.cos(start + 2 * math.pi * i / steps), cy + ry * math.sin(start + 2 * math.pi * i / steps))
+ for i in range(steps + 1)
+ ]
+
+
+def path(points):
+ return "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)
+
+
+def poly(points):
+ return [[round(x, 1), round(y, 1)] for x, y in points]
+
+
+def stripe(cx, cy, rx, ry, angle):
+ ca, sa = math.cos(angle), math.sin(angle)
+ points = []
+ for i in range(33):
+ t = -1.08 + 2.16 * i / 32
+ u, v = t, 0.28 * (1 - t * t)
+ points.append((cx + rx * (u * ca - v * sa), cy + ry * (u * sa + v * ca)))
+ return points
+
+
+def seeds(cx, cy, rx, ry, angle):
+ ca, sa = math.cos(angle), math.sin(angle)
+ near = (cx + rx * 0.55 * -sa, cy + ry * 0.55 * ca)
+ far = (cx - rx * 0.5 * -sa, cy - ry * 0.5 * ca)
+ return near, far
+
+
+def ink(frame, points, size, pressure, taper):
+ return {
+ "op": "stroke",
+ "layer": "lines",
+ "frame": frame,
+ "brush": "ink",
+ "color": "ink",
+ "size": size,
+ "path": path(points),
+ "pressure": pressure,
+ "taper": taper,
+ }
+
+
+def ops():
+ out = [
+ {"op": "palette", "add": "#1d1a22", "name": "ink"},
+ {"op": "palette", "add": "#d8543c", "name": "red"},
+ {"op": "palette", "add": "#f2e3c4", "name": "cream"},
+ {"op": "palette", "add": "#cdb58f", "name": "ground"},
+ {"op": "palette", "add": "#3a3046", "name": "shade"},
+ ]
+ first, hold0, _ = DRAWINGS[0]
+ for layer, name, extra in [
+ ("floor", "floor", {}),
+ ("shadow", "shadow", {"blend": "multiply", "opacity": 0.45}),
+ ("colour", "colour", {}),
+ ("lines", "lines", {}),
+ ]:
+ cels = [{"id": f"{layer}0", "frame": 0}] if layer == "floor" else [{"id": f"{layer}0", "frame": 0, "hold": hold0}]
+ out.append({"op": "add", "layer": {"id": layer, "kind": "paint", "name": name, "cels": cels, **extra}})
+ out.append(
+ {
+ "op": "fill",
+ "layer": "floor",
+ "polygon": poly([(0, FLOOR), (W, FLOOR), (W, H), (0, H)]),
+ "color": "ground",
+ }
+ )
+ out.append(
+ {
+ "op": "stroke",
+ "layer": "floor",
+ "brush": "ink",
+ "color": "ink",
+ "size": 5,
+ "path": f"M40 {FLOOR + 1} L{W - 40} {FLOOR - 1}",
+ "pressure": [0.5, 1, 1, 0.5],
+ "taper": [60, 60],
+ }
+ )
+ for frame, hold, depth in DRAWINGS:
+ if frame != first:
+ for layer in ("lines", "colour", "shadow"):
+ out.append({"op": "cel", "new": layer, "frame": frame, "hold": hold, "id": f"{layer}{frame}"})
+ cx, cy, rx, ry = place(frame, depth)
+ angle = 0.35 + 2 * math.pi * frame / REST[0]
+ out.append(ink(frame, ellipse(cx, cy, rx, ry), 7, [0.85, 1, 0.9, 1, 0.85], [0, 0]))
+ out.append(ink(frame, stripe(cx, cy, rx, ry, angle), 5, [0.6, 1, 0.6], [6, 6]))
+ near, far = seeds(cx, cy, rx, ry, angle)
+ for (sx, sy), colour in ((near, "red"), (far, "cream")):
+ out.append(
+ {
+ "op": "fill",
+ "layer": "colour",
+ "frame": frame,
+ "at": [round(sx, 1), round(sy, 1)],
+ "ref": "lines",
+ "gap": 4,
+ "color": colour,
+ }
+ )
+ spread = 0.45 + 0.55 * depth
+ out.append(
+ {
+ "op": "fill",
+ "layer": "shadow",
+ "frame": frame,
+ "polygon": poly(ellipse(cx, FLOOR + 6, R * 1.25 * spread, 14 * spread, 48)),
+ "color": "shade",
+ }
+ )
+ rest, rest_hold = REST
+ for layer in ("lines", "colour", "shadow"):
+ out.append({"op": "cel", "link": f"{layer}0", "frame": rest, "hold": rest_hold, "id": f"{layer}{rest}"})
+ out.append({"op": "clip", "add": "bounce", "from": 0, "to": rest - 1, "loop": True})
+ out.append({"op": "clip", "add": "rest", "from": rest, "to": rest + rest_hold - 1, "fps": 6})
+ return out
+
+
+if __name__ == "__main__":
+ for op in ops():
+ print(json.dumps(op))
diff --git a/samples/creature/build.sh b/samples/creature/build.sh
new file mode 100755
index 0000000..7314248
--- /dev/null
+++ b/samples/creature/build.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+klad="${KLAD:-$root/${CARGO_TARGET_DIR:-target}/release/klad}"
+out="${1:-$here/creature.draw}"
+if ! "$klad" arcs --help >/dev/null 2>&1; then
+ echo "$klad is older than this example (it has no klad arcs): run just build first" >&2
+ exit 1
+fi
+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then
+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2
+ exit 1
+fi
+layers=shadow,far,colour,shade,rim,lines
+rm -rf "$out"
+"$klad" new "$out" --width 1024 --height 1024 --layers 0 --fps 12 --frames 11 --background '#e9e4d8' >/dev/null
+echo "keys: idle at 0 and 2, walk at 3, 5, 7 and 9 (parts: body, sprout, leaf, second leaf, near leg, far leg)"
+python3 "$here/generate.py" | "$klad" apply "$out" >/dev/null 2>&1
+"$klad" clip "$out" --add idle --from 0 --to 2 --loop >/dev/null
+"$klad" clip "$out" --add walk --from 3 --to 10 --loop >/dev/null
+echo "colour every key from the first one:"
+"$klad" fill "$out" colour --like colour0 --frames all | grep -v '^changed\|^rev'
+"$klad" gaps "$out" colour --sheet all | tail -1
+echo "the walk keys' arcs, before in-betweening:"
+"$klad" arcs "$out" --track 'lines:near leg' --track 'far:far leg' --clip walk --ground 823,811 --travel 7 --check \
+ | grep 'under the ground\|slides\|swap'
+echo "in-betweens (paired by part):"
+for keys in "0 2" "3 5" "5 7" "7 9"; do
+ set -- $keys
+ "$klad" inbetween "$out" --layers "$layers" --from "$1" --to "$2" --spacing in-out | grep 'in-between.* in \|left out\|unpaired\|by part'
+done
+"$klad" inbetween "$out" --layers "$layers" --from 9 --loop --spacing in-out | grep 'in-between.* in \|left out\|unpaired\|by part'
+echo "timing:"
+"$klad" retime "$out" 0-2 --pingpong | head -1
+"$klad" retime "$out" 0-3 --on 3 | head -1
+"$klad" retime "$out" 12-19 --on 2 | head -1
+"$klad" timeline "$out" --origin 512,820 >/dev/null
+"$klad" clip "$out"
+echo "the walk's arcs, in-betweened:"
+"$klad" arcs "$out" --track 'lines:near leg' --track 'far:far leg' --clip walk --ground 823,811 --travel 3.5 --slack 3 --check \
+ | grep 'under the ground\|slides\|swap'
+"$klad" frames "$out"
+"$klad" gaps "$out" colour --sheet all | tail -1
+"$klad" hash "$out" --all --no-cache
+"$klad" render "$out" --sheet idle --drawings --cell 300 -o "${out%.draw}-idle.png"
+"$klad" render "$out" --sheet walk --drawings --cell 300 -o "${out%.draw}-walk.png"
+"$klad" render "$out" --sheet walk --drawings --cell 300 --track 'lines:near leg' --track 'far:far leg' --track 'lines:second leaf' -o "${out%.draw}-walk-arcs.png"
+"$klad" export "$out" --frame 0 --scale 2 -o "${out%.draw}@2x.png" >/dev/null
diff --git a/samples/creature/generate.py b/samples/creature/generate.py
new file mode 100644
index 0000000..c97ad6f
--- /dev/null
+++ b/samples/creature/generate.py
@@ -0,0 +1,259 @@
+import json
+import math
+import sys
+
+BODY = (512.0, 640.0)
+GROUND = 820.0
+DEPTH = 12.0
+LAYERS = ["shadow", "far", "colour", "shade", "rim", "lines"]
+
+IDLE = [
+ (0, 2, {"bob": 0, "sx": 1.0, "sy": 1.0, "tilt": 0, "sprout": 0, "eye": 9, "near": (0, 0), "far": (0, 0)}),
+ (2, 1, {"bob": 7, "sx": 1.04, "sy": 0.95, "tilt": 0, "sprout": -8, "eye": 5, "near": (0, 0), "far": (0, 0)}),
+]
+WALK = [
+ (3, 2, {"bob": 8, "sx": 1.03, "sy": 0.97, "tilt": 2, "sprout": -3, "eye": 9, "near": (14, 0), "far": (-14, 0)}),
+ (5, 2, {"bob": -6, "sx": 0.98, "sy": 1.03, "tilt": 5, "sprout": -8, "eye": 9, "near": (0, 0), "far": (4, 26)}),
+ (7, 2, {"bob": 8, "sx": 1.03, "sy": 0.97, "tilt": -2, "sprout": 3, "eye": 9, "near": (-14, 0), "far": (14, 0)}),
+ (9, 2, {"bob": -6, "sx": 0.98, "sy": 1.03, "tilt": -5, "sprout": 8, "eye": 9, "near": (4, 26), "far": (0, 0)}),
+]
+REORDERED = {7, 9}
+
+
+def body(pose):
+ tilt = math.radians(pose["tilt"])
+ ct, st = math.cos(tilt), math.sin(tilt)
+
+ def world(u, v):
+ x, y = u * pose["sx"], 100 + (v - 100) * pose["sy"]
+ return (BODY[0] + x * ct - y * st, BODY[1] + pose["bob"] + x * st + y * ct)
+
+ return world
+
+
+def oval(world, cx, cy, rx, ry, a0=0.0, a1=360.0, steps=40):
+ return [
+ world(cx + rx * math.cos(math.radians(a0 + (a1 - a0) * i / steps)), cy + ry * math.sin(math.radians(a0 + (a1 - a0) * i / steps)))
+ for i in range(steps + 1)
+ ]
+
+
+def rim_y(u):
+ return -10 + 14 * (1 - (u / 150) ** 2)
+
+
+def path(points):
+ return "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)
+
+
+def poly(points):
+ return [[round(x, 1), round(y, 1)] for x, y in points]
+
+
+def ink(frame, points, size, taper=(0, 0), pressure=(0.8, 1, 1, 0.85), layer="lines", color="ink", brush="ink", part="body"):
+ return {
+ "op": "stroke",
+ "layer": layer,
+ "frame": frame,
+ "brush": brush,
+ "color": color,
+ "size": size,
+ "path": path(points),
+ "pressure": list(pressure),
+ "taper": list(taper),
+ "part": part,
+ }
+
+
+def leg(world, angle, placed, depth=0.0):
+ step, lift = placed
+ def belly(a):
+ r = math.radians(a)
+ return world(130 * math.cos(r), -6.5 + 106 * math.sin(r))
+
+ hip = belly(angle)
+ planted = BODY[0] + 130 * math.cos(math.radians(angle))
+ f = (planted + step, GROUND - 16 - depth - lift)
+ dx, dy = f[0] - hip[0], f[1] - hip[1]
+ n = math.hypot(dx, dy) or 1.0
+ d = (dx / n, dy / n)
+ side = (-d[1], d[0])
+ w = 19
+ right = (f[0] - side[0] * w, f[1] - side[1] * w)
+ left = (f[0] + side[0] * w, f[1] + side[1] * w)
+ p1, p2 = belly(angle - 11), belly(angle + 11)
+ down = [(p1[0] + (right[0] - p1[0]) * t / 6, p1[1] + (right[1] - p1[1]) * t / 6) for t in range(6)]
+ turn = [
+ (f[0] + w * (-side[0] * math.cos(a) + d[0] * math.sin(a)), f[1] + w * (-side[1] * math.cos(a) + d[1] * math.sin(a)))
+ for a in (math.pi * i / 10 for i in range(11))
+ ]
+ up = [(left[0] + (p2[0] - left[0]) * t / 6, left[1] + (p2[1] - left[1]) * t / 6) for t in range(1, 7)]
+ return down + turn + up, ((hip[0] + f[0]) / 2, (hip[1] + f[1]) / 2)
+
+
+def sprout(world, sway):
+ a = math.radians(sway)
+ base = (0.0, -180.0)
+
+ def turned(u, v):
+ x, y = u - base[0], v - base[1]
+ return world(base[0] + x * math.cos(a) - y * math.sin(a), base[1] + x * math.sin(a) + y * math.cos(a))
+
+ stem = [turned(10 * math.sin(t * 2.4), -180 - 78 * t) for t in (i / 14 for i in range(15))]
+ tip = (10 * math.sin(2.4), -258.0)
+ leaf = [
+ turned(tip[0] - 64 * t, tip[1] - 14 * t + s * 22 * math.sin(math.pi * t) ** 0.8)
+ for s, ts in ((-1, range(17)), (1, range(16, -1, -1)))
+ for t in (i / 16 for i in ts)
+ ]
+ vein = [turned(tip[0] - 14 - 36 * t, tip[1] - 3 - 8 * t) for t in (i / 8 for i in range(9))]
+ bud = (10 * math.sin(0.5 * 2.4), -180 - 78 * 0.5)
+ ux, uy = math.cos(math.radians(-32)), math.sin(math.radians(-32))
+
+ def second(t, side):
+ w = side * 15 * math.sin(math.pi * t) ** 0.8
+ return turned(bud[0] + ux * 46 * t - uy * w, bud[1] + uy * 46 * t + ux * w)
+
+ leaf2 = [second(t, s) for s, ts in ((-1, range(17)), (1, range(16, -1, -1))) for t in (i / 16 for i in ts)]
+ vein2 = [second(0.22 + 0.5 * t, 0) for t in (i / 6 for i in range(7))]
+ return stem, leaf, vein, turned(tip[0] - 32, tip[1] - 14), (leaf2, vein2, second(0.5, -0.5))
+
+
+def drawing(frame, pose):
+ world = body(pose)
+ out = []
+ dome = oval(world, 0, -10, 150, 170, 180, 360, 48)
+ rim = [world(u, rim_y(u)) for u in (-150 + 300 * i / 30 for i in range(31))]
+ belly = oval(world, 0, -6.5, 130, 106, 180, 0, 40)
+ hood = [world(u, rim_y(u) + 54 * math.sin(math.pi * (u - 4) / 122) ** 0.7) for u in (4 + 122 * i / 24 for i in range(25))]
+ eyes = [oval(world, 44, 31, 6, pose["eye"], 0, 360, 16), oval(world, 84, 29, 6, pose["eye"], 0, 360, 16)]
+ ridges = [oval(world, 0, -10, 108, 124, a0, a1, 10) for a0, a1 in ((212, 236), (256, 284), (304, 328))]
+ stem, leaf, vein, leaf_seed, (leaf2, vein2, leaf2_seed) = sprout(world, pose["sprout"])
+ near, near_seed = leg(world, 70, pose["near"])
+ far, _ = leg(world, 104, pose["far"], DEPTH)
+ out += [
+ {"op": "fill", "layer": "far", "frame": frame, "polygon": poly(far), "color": "far", "part": "far leg"},
+ ink(frame, far, 7, pressure=(0.8, 1, 1, 0.8), layer="far", part="far leg"),
+ ink(frame, dome, 9, pressure=(0.7, 1, 1, 1, 0.8)),
+ ink(frame, rim, 6),
+ ink(frame, belly, 8, pressure=(0.8, 1, 1, 0.8)),
+ ink(frame, hood, 5, pressure=(0.6, 1, 1, 0.6)),
+ ink(frame, eyes[0], 4, pressure=(1, 1)),
+ ink(frame, eyes[1], 4, pressure=(1, 1)),
+ ]
+ out += [ink(frame, r, 4, (8, 10), (0.4, 1, 0.5)) for r in ridges]
+ sprouting = [
+ ink(frame, stem, 6, (0, 10), (1, 0.9, 0.7), part="sprout"),
+ ink(frame, leaf, 5, pressure=(1, 1), part="leaf"),
+ ink(frame, vein, 3, (2, 8), (0.8, 0.4), part="leaf"),
+ ink(frame, near, 7, pressure=(0.8, 1, 1, 0.8), part="near leg"),
+ ]
+ second = [
+ ink(frame, leaf2, 5, pressure=(1, 1), part="second leaf"),
+ ink(frame, vein2, 3, (2, 6), (0.8, 0.4), part="second leaf"),
+ ]
+ out += second + sprouting if frame in REORDERED else sprouting + second
+ shade_shell = oval(world, 0, -10, 175, 195, 290, 362, 16) + oval(world, 0, -10, 112, 138, 362, 290, 16)
+ shade_belly = [world(-150 + 300 * i / 16, 70 - 34 * (i / 16) - 18 * math.sin(math.pi * i / 16)) for i in range(17)] + [
+ world(150, 140),
+ world(-150, 140),
+ ]
+ out += [
+ {"op": "fill", "layer": "shade", "frame": frame, "polygon": poly(shade_shell), "color": "shade", "part": "body"},
+ {"op": "fill", "layer": "shade", "frame": frame, "polygon": poly(shade_belly), "color": "shade", "part": "body"},
+ ]
+ out += [
+ ink(frame, oval(world, 0, -10, 139, 158, 196, 246, 14), 7, (24, 30), (0.3, 1, 0.4), "rim", "rim"),
+ ink(frame, oval(world, 0, -6.5, 119, 95, 148, 172, 8), 5, (10, 14), (0.3, 1, 0.3), "rim", "rim"),
+ ]
+ spread = 1 - pose["bob"] / 60
+ shadow = [
+ (BODY[0] + 150 * spread * math.cos(2 * math.pi * i / 32), GROUND + 3 + 15 * spread * math.sin(2 * math.pi * i / 32))
+ for i in range(32)
+ ]
+ out.append({"op": "fill", "layer": "shadow", "frame": frame, "polygon": poly(shadow), "color": "ground", "part": "shadow"})
+ seeds = {
+ "shell": world(-40, -90),
+ "body": world(-50, 40),
+ "face": world(64, 44),
+ "eye": world(44, 31),
+ "eye2": world(84, 29),
+ "leaf": leaf_seed,
+ "leaf2": leaf2_seed,
+ "leg": near_seed,
+ }
+ return out, seeds
+
+
+def keys():
+ out = [
+ {"op": "palette", "add": "#17161d", "name": "ink"},
+ {"op": "palette", "add": "#5f7d4c", "name": "moss"},
+ {"op": "palette", "add": "#6b5643", "name": "bark"},
+ {"op": "palette", "add": "#20263a", "name": "dusk"},
+ {"op": "palette", "add": "#bff2ff", "name": "glow"},
+ {"op": "palette", "add": "#8dbb6a", "name": "leaf"},
+ {"op": "palette", "add": "#45372c", "name": "root"},
+ {"op": "palette", "add": "#2a211b", "name": "far"},
+ {"op": "palette", "add": "#44405a", "name": "shade"},
+ {"op": "palette", "add": "#eef6cf", "name": "rim"},
+ {"op": "palette", "add": "#3a3428", "name": "ground"},
+ ]
+ extra = {
+ "shadow": {"blend": "multiply", "opacity": 0.35},
+ "shade": {"blend": "multiply", "opacity": 0.7, "clip": True},
+ "rim": {"clip": True},
+ }
+ first, hold, _ = IDLE[0]
+ for layer in LAYERS:
+ out.append(
+ {"op": "add", "layer": {"id": layer, "kind": "paint", "name": layer, "cels": [{"id": f"{layer}{first}", "frame": first, "hold": hold}], **extra.get(layer, {})}}
+ )
+ for frame, hold, _ in IDLE[1:] + WALK:
+ for layer in LAYERS:
+ out.append({"op": "cel", "new": layer, "frame": frame, "hold": hold, "id": f"{layer}{frame}"})
+ for frame, _, pose in IDLE + WALK:
+ ops, seeds = drawing(frame, pose)
+ out += ops
+ if frame == first:
+ colours = {"shell": "moss", "body": "bark", "face": "dusk", "eye": "glow", "eye2": "glow", "leaf": "leaf", "leg": "root", "leaf2": "leaf"}
+ for name, colour in colours.items():
+ x, y = seeds[name]
+ gap = 2 if name.startswith("eye") else 4
+ out.append({"op": "fill", "layer": "colour", "frame": frame, "at": [round(x, 1), round(y, 1)], "ref": "lines", "gap": gap, "color": colour})
+ return out
+
+
+def leaf(bundle):
+ with open(f"{bundle}/doc.json") as f:
+ doc = json.load(f)
+ frames = {c["id"]: c["frame"] for layer in doc["layers"] for c in layer.get("cels", [])}
+ out = []
+ for key, _, pose in IDLE + WALK:
+ ops, seeds = drawing(frames[f"lines{key}"], pose)
+ out += [op for op in ops if op.get("part") == "second leaf"]
+ if key == IDLE[0][0]:
+ x, y = seeds["leaf2"]
+ fill = {"op": "fill", "layer": "colour", "frame": frames[f"colour{key}"], "at": [round(x, 1), round(y, 1)]}
+ out.append({**fill, "ref": "lines", "gap": 4, "color": "leaf"})
+ return out
+
+
+def redraw(bundle):
+ with open(f"{bundle}/doc.json") as f:
+ doc = json.load(f)
+ frames = {c["id"]: c["frame"] for layer in doc["layers"] for c in layer.get("cels", [])}
+ out = []
+ for key, _, pose in IDLE + WALK:
+ ops, _ = drawing(frames[f"lines{key}"], pose)
+ drawn = [layer for layer in LAYERS if layer != "colour"]
+ counts = {layer: sum(1 for op in ops if op.get("layer") == layer) for layer in drawn}
+ out.append({"op": "rm", "ids": [f"{layer}{key}:s{i}" for layer in drawn for i in range(1, counts[layer] + 1)]})
+ out += ops
+ return out
+
+
+if __name__ == "__main__":
+ modes = {"redraw": redraw, "leaf": leaf}
+ for op in modes[sys.argv[1]](sys.argv[2]) if sys.argv[1:2] and sys.argv[1] in modes else keys():
+ print(json.dumps(op))
diff --git a/samples/ink-shapes/build.sh b/samples/ink-shapes/build.sh
new file mode 100755
index 0000000..e230843
--- /dev/null
+++ b/samples/ink-shapes/build.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+klad="${KLAD:-$root/${CARGO_TARGET_DIR:-target}/release/klad}"
+out="${1:-$here/ink-shapes.draw}"
+rm -rf "$out"
+"$klad" new "$out" --width 960 --height 900 --layers 0 --background '#f4efe6' >/dev/null
+python3 "$here/generate.py" | "$klad" apply "$out" >/dev/null
+"$klad" render "$out" -o "${out%.draw}.png"
+"$klad" hash "$out" --no-cache
diff --git a/samples/ink-shapes/generate.py b/samples/ink-shapes/generate.py
new file mode 100644
index 0000000..e17d615
--- /dev/null
+++ b/samples/ink-shapes/generate.py
@@ -0,0 +1,32 @@
+import json
+
+SHAPES = [
+ ("circle", {"type": "ellipse", "cx": 0, "cy": 0, "rx": 70, "ry": 70}),
+ ("box", {"type": "rect", "x": -70, "y": -55, "w": 140, "h": 110, "radius": 18}),
+ ("star", {"type": "path", "d": "M0 -80 L22 -26 L78 -24 L34 10 L50 66 L0 34 L-50 66 L-34 10 L-78 -24 L-22 -26 Z"}),
+ ("blob", {"type": "path", "d": "M-60 10 C -70 -50 -10 -80 30 -60 C 80 -40 90 20 50 50 C 10 80 -50 70 -60 10 Z"}),
+]
+WAYS = [
+ {"weight": 6},
+ {"weight": 10, "break": 45, "gap": 3, "light": [1, 1]},
+ {"weight": 5, "wobble": 1.5, "light": [0, -1], "brush": "pencil"},
+]
+
+
+def ops():
+ out = [
+ {"op": "add", "layer": {"id": "sketch", "kind": "vector", "name": "sketch", "visible": False}},
+ {"op": "add", "layer": {"id": "lines", "kind": "paint", "name": "lines"}},
+ ]
+ for col, way in enumerate(WAYS):
+ ids = []
+ for row, (name, node) in enumerate(SHAPES):
+ sid = f"{name}{col}"
+ ids.append(sid)
+ out.append({"op": "add", "node": {**node, "id": sid, "transform": {"x": 170 + col * 300, "y": 120 + row * 210}}, "in": "sketch"})
+ out.append({"op": "ink", "layer": "lines", "from": ids, "color": "#15161c", **way})
+ return out
+
+
+if __name__ == "__main__":
+ print("\n".join(json.dumps(op) for op in ops()))
diff --git a/samples/lantern/build.sh b/samples/lantern/build.sh
new file mode 100755
index 0000000..f5cea3b
--- /dev/null
+++ b/samples/lantern/build.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+klad="${KLAD:-$root/${CARGO_TARGET_DIR:-target}/release/klad}"
+out="${1:-$here/lantern.draw}"
+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then
+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2
+ exit 1
+fi
+rm -rf "$out"
+"$klad" new "$out" --width 1024 --height 1280 --layers 0 >/dev/null
+python3 "$here/generate.py" ${PAINTED:+--painted} | "$klad" apply "$out" >/dev/null
+"$klad" render "$out" -o "${out%.draw}.png"
+"$klad" export "$out" --scale 2 -o "${out%.draw}@2x.png"
+"$klad" hash "$out" --no-cache
diff --git a/samples/lantern/generate.py b/samples/lantern/generate.py
new file mode 100644
index 0000000..ecbe013
--- /dev/null
+++ b/samples/lantern/generate.py
@@ -0,0 +1,121 @@
+import json
+import sys
+
+POST = ("M431 1088 C 419 950 451 760 435 600 C 419 470 425 380 449 330 C 481 260 600 250 646 300 "
+ "C 668 328 674 362 664 392 L 650 388 C 658 366 654 338 636 318 C 600 280 506 286 488 336 "
+ "C 466 384 462 470 478 600 C 494 760 466 950 474 1088 Z")
+POD = "M650 480 C 702 508 775 562 772 650 C 770 730 720 785 650 788 C 580 785 528 730 528 650 C 526 562 598 508 650 480 Z"
+STONE = ("M300 1180 C 298 1122 362 1088 452 1083 C 548 1078 646 1084 702 1112 C 742 1132 748 1176 722 1196 "
+ "C 600 1206 420 1206 322 1200 C 307 1198 300 1191 300 1180 Z")
+STONE_SIDE = ("M301 1172 C 380 1162 600 1160 744 1162 C 744 1180 736 1192 722 1196 "
+ "C 600 1206 420 1206 322 1200 C 307 1198 300 1191 301 1172 Z")
+
+
+def ring(cx, cy, rx, ry):
+ return (f"M{cx} {cy - ry} C {cx + rx * 1.33} {cy - ry} {cx + rx * 1.33} {cy + ry} {cx} {cy + ry} "
+ f"C {cx - rx * 1.33} {cy + ry} {cx - rx * 1.33} {cy - ry} {cx} {cy - ry} Z")
+
+
+SHAPES = {
+ "post": {"type": "path", "d": POST},
+ "knob": {"type": "ellipse", "cx": 657, "cy": 392, "rx": 10, "ry": 10},
+ "edge-link": {"type": "path", "d": "M649 419 C 649 415 655 415 655 419 L 654 436 C 654 440 648 440 648 436 Z"},
+ "bead": {"type": "ellipse", "cx": 650, "cy": 456, "rx": 7, "ry": 5},
+ "cap": {"type": "path", "d": "M624 484 C 624 466 676 466 676 484 C 664 492 636 492 624 484 Z"},
+ "pod": {"type": "path", "d": POD},
+ "window": {"type": "ellipse", "cx": 650, "cy": 655, "rx": 50, "ry": 70},
+ "stone": {"type": "path", "d": STONE},
+ "stone-side": {"type": "path", "d": STONE_SIDE},
+ "left-tuft": {"type": "rect", "x": 292, "y": 1192, "w": 44, "h": 8},
+ "right-tuft": {"type": "rect", "x": 690, "y": 1190, "w": 52, "h": 8},
+}
+FLATS = [("post", "iron"), ("knob", "iron"), ("edge-link", "chain"), ("bead", "chain"), ("cap", "iron"),
+ ("pod", "bone"), ("window", "glow"), ("stone", "stone"), ("stone-side", "stone dark")]
+LINKS = [ring(654, 410, 5.5, 8), ring(651, 445, 5.5, 8)]
+DETAILS = [
+ "M620 500 C 568 560 562 720 612 768", "M680 500 C 732 560 738 720 688 768", "M650 492 L 650 574", "M650 736 L 650 770",
+ "M650 790 C 654 818 646 846 626 852 C 612 856 604 846 612 838",
+ "M522 1090 L 536 1110 L 528 1132 L 540 1150", "M640 1094 C 660 1108 668 1124 688 1132",
+]
+COLOURS = {"ink": "#15161c", "iron": "#3b4352", "bone": "#d3cab3", "glow": "#a9ecff", "stone": "#6b7584",
+ "stone dark": "#4a5260", "chain": "#283039", "shadow": "#56607e", "rim": "#e2f5ff"}
+LIGHT = [-0.6, -0.8]
+
+
+def layer(id, kind, **extra):
+ return {"op": "add", "layer": {"id": id, "kind": kind, "name": id, **extra}}
+
+
+def lit(shapes, depth, soft, rim_width, strength=0.8):
+ return {"op": "light", "from": shapes, "light": LIGHT, "shade": "shade", "rim": "rim", "depth": depth, "soft": soft,
+ "shadeColor": COLOURS["shadow"], "rimColor": COLOURS["rim"], "rimWidth": rim_width, "shadeOpacity": strength}
+
+
+def glow():
+ halo = {"radial": {"center": [650, 655], "radius": 260, "stops": [[0, "#7fd6ff66"], [0.45, "#3f9fd022"], [1, "#2a6f8800"]]}}
+ core = {"radial": {"center": [650, 668], "radius": 64, "stops": [[0, "#f4feffff"], [0.5, "#bff0ff88"], [1, "#6fd0ff00"]]}}
+ motes = [(560, 560, 4), (742, 520, 3), (770, 712, 5), (590, 830, 3), (708, 452, 2.5), (520, 700, 2.5)]
+ return [
+ {"op": "add", "node": {"type": "ellipse", "cx": 650, "cy": 655, "rx": 260, "ry": 260, "fill": halo}, "in": "halo"},
+ {"op": "add", "node": {"type": "ellipse", "cx": 650, "cy": 668, "rx": 64, "ry": 64, "fill": core}, "in": "light"},
+ ] + [
+ {"op": "add", "node": {"type": "ellipse", "cx": x, "cy": y, "rx": r, "ry": r, "fill": "#dff8ffcc", "blur": r * 0.8}, "in": "light"}
+ for x, y, r in motes
+ ]
+
+
+def ink(path=None, shapes=None, weight=3.5, seed=1, color="ink"):
+ op = {"op": "ink", "layer": "lines", "weight": weight, "light": LIGHT, "color": color, "seed": seed}
+ return {**op, "path": path} if path else {**op, "from": shapes}
+
+
+PAINTED = "--painted" in sys.argv
+
+
+def painted():
+ def paint(shapes, colour, seed, **extra):
+ return {"op": "paint", "layer": "rim", "in": shapes, "color": COLOURS[colour], "light": LIGHT, "seed": seed, **extra}
+ return [
+ paint(["post"], "iron", 1, form="cylinder", axis=86, weight=7),
+ paint(["cap"], "iron", 2, weight=5),
+ paint(["pod"], "bone", 3, weight=11),
+ {"op": "fill", "layer": "rim", "shape": "window", "color": COLOURS["glow"], "expand": 2},
+ paint(["stone"], "stone", 4, form="flat", facing=[0, -1, 0.8], angle=8, weight=11),
+ paint(["stone-side"], "stone dark", 5, form="flat", facing=[0, 0.3, 1], angle=4, weight=9, brush="dry-brush", decisive=0.5),
+ ]
+
+
+def ops():
+ out = [{"op": "palette", "add": c, "name": n} for n, c in COLOURS.items()]
+ out += [
+ layer("sketch", "vector", visible=False),
+ layer("halo", "vector", blend="screen"),
+ layer("flats", "paint"),
+ layer("shade", "paint", blend="multiply", opacity=0.8, clip=True),
+ layer("rim", "paint", clip=True),
+ layer("lines", "paint"),
+ layer("light", "vector", blend="add"),
+ ]
+ out += [{"op": "add", "node": {**node, "id": sid}, "in": "sketch"} for sid, node in SHAPES.items()]
+ out += [{"op": "fill", "layer": "flats", "shape": sid, "color": c, "expand": 2} for sid, c in FLATS]
+ if PAINTED:
+ out += painted()
+ else:
+ out += [lit(["post", "cap", "stone"], 22, 2, 5), lit(["pod"], 44, 1, 6, 1.0)]
+ out.append({"op": "hatch", "layer": "shade", "in": ["stone-side"], "angle": 78, "spacing": 16, "length": [8, 14],
+ "weight": 2, "color": "shadow", "opacity": 0.55, "seed": 5})
+ out.append(ink(shapes=["knob", "cap", "pod", "window", "stone"], weight=9, seed=3))
+ out.append(ink(path=POST.removesuffix(" Z"), weight=9, seed=2))
+ out.append(ink(shapes=["edge-link", "bead"], weight=3, seed=9))
+ out += [ink(path=d, weight=3, seed=10 + i) for i, d in enumerate(LINKS)]
+ out += [ink(path=d, weight=3.5, seed=4 + i) for i, d in enumerate(DETAILS)]
+ out.append(ink(path="M310 1170 C 420 1160 600 1158 738 1160", weight=2.5, seed=20))
+ out += [{"op": "scatter", "layer": "lines", "in": [tuft], "avoid": [], "mark": mark, "count": 7,
+ "size": [0.9, 1.6], "turn": turn, "weight": 5, "color": "ink", "seed": 6 + i}
+ for i, (tuft, mark, turn) in enumerate([("left-tuft", "M0 0 Q -5 -30 -14 -58", [-30, 4]),
+ ("right-tuft", "M0 0 Q 5 -30 14 -58", [-4, 30])])]
+ return out + glow()
+
+
+if __name__ == "__main__":
+ print("\n".join(json.dumps(op) for op in ops()))
diff --git a/samples/solids/build.sh b/samples/solids/build.sh
new file mode 100755
index 0000000..c2fdae7
--- /dev/null
+++ b/samples/solids/build.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../.." && pwd)"
+klad="${KLAD:-$root/${CARGO_TARGET_DIR:-target}/release/klad}"
+out="${1:-$here/solids.draw}"
+if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then
+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it from generate.py" >&2
+ exit 1
+fi
+rm -rf "$out"
+"$klad" new "$out" --width 1200 --height 900 --layers 0 >/dev/null
+python3 "$here/generate.py" > "$out.jsonl"
+"$klad" apply "$out" --file "$out.jsonl" >/dev/null
+rm "$out.jsonl"
+"$klad" render "$out" -o "${out%.draw}.png" | sed -n 1p
+"$klad" hash "$out" --no-cache
diff --git a/samples/solids/generate.py b/samples/solids/generate.py
new file mode 100644
index 0000000..408af12
--- /dev/null
+++ b/samples/solids/generate.py
@@ -0,0 +1,771 @@
+import json
+import math
+import os
+import random
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "docs", "skill"))
+import drawkit
+
+W, H = 1200, 900
+F = 1500.0
+EYE = (0.0, 34.0, 0.0)
+HORIZON = 170.0
+CX = 600.0
+TABLE_Z = 165.0
+
+L = (lambda v: tuple(c / math.sqrt(sum(x * x for x in v)) for c in v))((-0.47, 0.86, -0.21))
+KEY = (1.0, 0.86, 0.68)
+AMB = (0.040, 0.048, 0.066)
+PLASTER = (0.82, 0.80, 0.76)
+TERRACOTTA = (0.60, 0.29, 0.16)
+CELADON = (0.40, 0.58, 0.50)
+TABLE = (0.46, 0.39, 0.31)
+WALL = (0.085, 0.088, 0.098)
+
+SPHERE = {"c": (-4.0, 7.0, 82.0), "r": 7.0}
+CUBE = {"c": (16.0, 0.0, 101.0), "s": 17.0, "yaw": math.radians(33)}
+CYL = {"c": (-27.0, 0.0, 112.0), "r": 5.0, "h": 16.0}
+
+rnd = random.Random(7)
+drawkit.seed(7)
+
+
+def sub(a, b):
+ return tuple(x - y for x, y in zip(a, b))
+
+
+def addv(a, b):
+ return tuple(x + y for x, y in zip(a, b))
+
+
+def mul(a, k):
+ return tuple(x * k for x in a)
+
+
+def dot(a, b):
+ return sum(x * y for x, y in zip(a, b))
+
+
+def norm(v):
+ d = math.sqrt(dot(v, v)) or 1.0
+ return tuple(x / d for x in v)
+
+
+CAMERA = drawkit.Camera(EYE, F, CX, HORIZON)
+
+
+def project(p):
+ return CAMERA.project(p)
+
+
+def to_eye(p):
+ return norm(sub(EYE, p))
+
+
+def encode(c):
+ c = max(0.0, min(1.0, c))
+ return 12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055
+
+
+def hexc(rgb):
+ return "#" + "".join(f"{round(encode(c) * 255):02x}" for c in rgb)
+
+
+def value(rgb):
+ y = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
+ return 10 * max(0.0, y) ** (1 / 3)
+
+
+def jitter(rgb, amount):
+ k = 1 + rnd.uniform(-amount, amount)
+ warm = rnd.uniform(-amount, amount) * 0.5
+ return (rgb[0] * k * (1 + warm), rgb[1] * k, rgb[2] * k * (1 - warm))
+
+
+def cube_local(p):
+ c, yaw = CUBE["c"], CUBE["yaw"]
+ x, y, z = sub(p, c)
+ return (x * math.cos(yaw) + z * math.sin(yaw), y, -x * math.sin(yaw) + z * math.cos(yaw))
+
+
+def cube_dir_local(d):
+ yaw = CUBE["yaw"]
+ x, y, z = d
+ return (x * math.cos(yaw) + z * math.sin(yaw), y, -x * math.sin(yaw) + z * math.cos(yaw))
+
+
+def hits(p, d):
+ c, r = SPHERE["c"], SPHERE["r"]
+ oc = sub(c, p)
+ t = dot(oc, d)
+ if t > 0 and dot(oc, oc) - t * t < r * r:
+ return True
+ q, e = cube_local(p), cube_dir_local(d)
+ h = CUBE["s"] / 2
+ lo, hi = (-h, 0.0, -h), (h, CUBE["s"], h)
+ t0, t1 = 1e-4, 1e9
+ for i in range(3):
+ if abs(e[i]) < 1e-9:
+ if q[i] < lo[i] or q[i] > hi[i]:
+ t0 = 2e9
+ continue
+ a, b = (lo[i] - q[i]) / e[i], (hi[i] - q[i]) / e[i]
+ t0, t1 = max(t0, min(a, b)), min(t1, max(a, b))
+ if t0 <= t1:
+ return True
+ cc, rr, hh = CYL["c"], CYL["r"], CYL["h"]
+ ox, oz = p[0] - cc[0], p[2] - cc[2]
+ a = d[0] ** 2 + d[2] ** 2
+ b = 2 * (ox * d[0] + oz * d[2])
+ k = ox * ox + oz * oz - rr * rr
+ disc = b * b - 4 * a * k
+ if a > 1e-9 and disc >= 0:
+ for t in ((-b - math.sqrt(disc)) / (2 * a), (-b + math.sqrt(disc)) / (2 * a)):
+ if t > 1e-4 and 0 <= p[1] + t * d[1] <= hh:
+ return True
+ if d[1] > 1e-6:
+ t = (hh - p[1]) / d[1]
+ if t > 0 and (ox + t * d[0]) ** 2 + (oz + t * d[2]) ** 2 <= rr * rr:
+ return True
+ return False
+
+
+SOFT = [norm(addv(L, (rnd.uniform(-0.05, 0.05), rnd.uniform(-0.05, 0.05), rnd.uniform(-0.05, 0.05)))) for _ in range(10)]
+
+
+def lit_fraction(p):
+ return sum(0 if hits(p, d) else 1 for d in SOFT) / len(SOFT)
+
+
+def occlusion(p):
+ c, r = SPHERE["c"], SPHERE["r"]
+ ds = math.hypot(p[0] - c[0], p[2] - c[2])
+ ao = 1 - 0.6 * math.exp(-(ds / (0.55 * r)) ** 2)
+ q = cube_local(p)
+ h = CUBE["s"] / 2
+ dc = math.hypot(max(0.0, abs(q[0]) - h), max(0.0, abs(q[2]) - h))
+ ao *= 1 - 0.55 * math.exp(-dc / 0.9)
+ cc, rr = CYL["c"], CYL["r"]
+ dy = max(0.0, math.hypot(p[0] - cc[0], p[2] - cc[2]) - rr)
+ ao *= 1 - 0.55 * math.exp(-dy / 0.8)
+ return ao
+
+
+def shade(p, n, albedo, shadowed=None, gloss=0.0):
+ key = max(0.0, dot(n, L)) * (lit_fraction(addv(p, mul(n, 0.05))) if shadowed is None else shadowed)
+ sky = 0.5 * (1 + n[1])
+ bounce = 0.5 * (1 - n[1]) * 0.26
+ out = [a * (k * key + am * sky * 1.6 + t * k * bounce) for a, k, am, t in zip(albedo, KEY, AMB, TABLE)]
+ if gloss:
+ h = norm(addv(L, to_eye(p)))
+ s = gloss * max(0.0, dot(n, h)) ** 70 * key
+ out = [c + k * s for c, k in zip(out, KEY)]
+ return tuple(out)
+
+
+def table_colour(x, z, shadowed=True, occluded=True):
+ p = (x, 0.0, z)
+ frac = lit_fraction(p) if shadowed else 1.0
+ ao = occlusion(p) if occluded else 1.0
+ light_pool = 1 - 0.35 * min(1.0, math.hypot(x + 2, z - 95) / 70) ** 2
+ out = [a * (k * L[1] * frac * light_pool + am * 1.6) * ao for a, k, am in zip(TABLE, KEY, AMB)]
+ return tuple(out), frac
+
+
+def path(points):
+ return "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)
+
+
+def poly(points):
+ return path(points) + " Z"
+
+
+def stroke(layer, brush, size, rgb, points, pressure=None, taper=None, opacity=1.0, bow=True):
+ if pressure is not None:
+ pts, _ = drawkit.resample(points, max(2, len(points)))
+ op = {"op": "stroke", "layer": layer, "brush": brush, "size": round(size, 1), "color": hexc(rgb), "path": path(pts), "pressure": list(pressure), "taper": list(taper or (0, 0))}
+ if opacity < 1:
+ op["opacity"] = round(opacity, 2)
+ return op
+ return drawkit.stroke(layer, brush, size, rgb, points, opacity=opacity, bow=bow)
+
+
+def basis(axis):
+ a = norm(axis)
+ t = (0.0, 1.0, 0.0) if abs(a[1]) < 0.9 else (1.0, 0.0, 0.0)
+ u = norm((a[1] * t[2] - a[2] * t[1], a[2] * t[0] - a[0] * t[2], a[0] * t[1] - a[1] * t[0]))
+ w = (a[1] * u[2] - a[2] * u[1], a[2] * u[0] - a[0] * u[2], a[0] * u[1] - a[1] * u[0])
+ return a, u, w
+
+
+def sphere_silhouette():
+ return drawkit.silhouette(CAMERA, drawkit.sphere_points(SPHERE["c"], SPHERE["r"], 30, 60))
+
+
+def cube_vertices():
+ c = CUBE["c"]
+ return drawkit.box((c[0], 0.0, c[2]), (CUBE["s"],) * 3, CUBE["yaw"])[0]
+
+
+def cylinder_points(n=72):
+ c = CYL["c"]
+ return drawkit.cylinder_points((c[0], 0.0, c[2]), CYL["r"], CYL["h"], n)
+
+def sphere_strokes(layer):
+ c, r = SPHERE["c"], SPHERE["r"]
+ a, u, w = basis(L)
+ scale = F / (c[2] - EYE[2])
+ ops = []
+ for step, size, opacity, jit, keep in ((7, 30, 1.0, 0.015, lambda al: True), (3.5, 15, 1.0, 0.012, lambda al: True), (1.6, 7, 0.9, 0.01, lambda al: al < 40 or 60 < al < 112)):
+ alpha = rnd.uniform(0.5, step)
+ while alpha < 180:
+ ring = math.radians(alpha)
+ circumference = 2 * math.pi * math.sin(ring) * r * scale
+ if keep(alpha) and circumference > 2:
+ width = min(size, max(3.0, circumference / 2.2))
+ count = max(2, int(circumference / (width * 2.0)) + 1)
+ span = 2 * math.pi / count * 1.7
+ beta = rnd.uniform(0, 2 * math.pi)
+ for k in range(count):
+ b0 = beta + 2 * math.pi * k / count
+ pts3 = [addv(c, mul(addv(mul(a, math.cos(ring)), mul(addv(mul(u, math.cos(b)), mul(w, math.sin(b))), math.sin(ring))), r)) for b in [b0 - span / 2 + span * i / 5 for i in range(6)]]
+ seen = [p for p in pts3 if dot(norm(sub(p, c)), to_eye(p)) > 0.03]
+ if len(seen) < len(pts3):
+ runs, run = [], []
+ for p in pts3:
+ if dot(norm(sub(p, c)), to_eye(p)) > 0.03:
+ run.append(p)
+ else:
+ runs.append(run)
+ run = []
+ runs.append(run)
+ seen = max(runs, key=len)
+ if len(seen) < 2:
+ continue
+ mid = seen[len(seen) // 2]
+ n = norm(sub(mid, c))
+ rgb = jitter(shade(mid, n, PLASTER), jit)
+ ops.append(stroke(layer, "oil", width * (0.9 + 0.2 * rnd.random()), rgb, [project(p) for p in seen], opacity=opacity, bow=False))
+ alpha += step * rnd.uniform(0.85, 1.15)
+ return ops
+
+
+def cube_faces():
+ v = cube_vertices()
+ faces = {
+ "top": [(-1, 1, -1), (1, 1, -1), (1, 1, 1), (-1, 1, 1)],
+ "x-": [(-1, 0, -1), (-1, 0, 1), (-1, 1, 1), (-1, 1, -1)],
+ "x+": [(1, 0, -1), (1, 0, 1), (1, 1, 1), (1, 1, -1)],
+ "z-": [(-1, 0, -1), (1, 0, -1), (1, 1, -1), (-1, 1, -1)],
+ "z+": [(-1, 0, 1), (1, 0, 1), (1, 1, 1), (-1, 1, 1)],
+ }
+ yaw = CUBE["yaw"]
+ normals = {"top": (0.0, 1.0, 0.0), "x-": (-math.cos(yaw), 0.0, -math.sin(yaw)), "x+": (math.cos(yaw), 0.0, math.sin(yaw)),
+ "z-": (math.sin(yaw), 0.0, -math.cos(yaw)), "z+": (-math.sin(yaw), 0.0, math.cos(yaw))}
+ out = []
+ for name, keys in faces.items():
+ pts = [v[k] for k in keys]
+ centre = mul(addv(addv(pts[0], pts[1]), addv(pts[2], pts[3])), 0.25)
+ if dot(normals[name], to_eye(centre)) > 0:
+ out.append((name, pts, normals[name]))
+ return out
+
+
+def cube_strokes(layer, only):
+ ops = []
+ for name, (p0, p1, p2, p3), n in cube_faces():
+ if name != only:
+ continue
+ along = sub(p1, p0)
+ up = sub(p3, p0)
+ height = abs(project(p3)[1] - project(p0)[1]) + abs(project(p2)[1] - project(p1)[1])
+ for size, brush, jit, opacity in ((24, "oil", 0.03, 1.0), (12, "oil", 0.04, 0.85), (9, "dry-brush", 0.05, 0.12), (5, "chalk", 0.05, 0.3)):
+ rows = max(3, int(height / 2 / (size * 0.42)))
+ for i in range(rows):
+ t = (i + rnd.uniform(0.25, 0.75)) / rows
+ s0 = rnd.uniform(-0.12, 0.05)
+ while s0 < 1.0:
+ s1 = min(1.06, s0 + rnd.uniform(0.25, 0.5))
+ pts3 = [addv(p0, addv(mul(along, x), mul(up, t + rnd.uniform(-0.006, 0.006)))) for x in (s0, (2 * s0 + s1) / 3, (s0 + 2 * s1) / 3, s1)]
+ rgb = jitter(shade(pts3[1], n, TERRACOTTA), jit)
+ ops.append(stroke(layer, brush, size * (0.85 + 0.3 * rnd.random()), rgb, [project(p) for p in pts3], opacity=opacity))
+ if s1 >= 1.0:
+ break
+ s0 = s1 - rnd.uniform(0.1, 0.18)
+ return ops
+
+
+def interior_edges():
+ faces = [set(pts) for _, pts, _ in [(n, [tuple(round(c, 4) for c in p) for p in ps], m) for n, ps, m in cube_faces()]]
+ v = cube_vertices()
+ keyed = {tuple(round(c, 4) for c in p): k for k, p in v.items()}
+ out = []
+ for i in range(len(faces)):
+ for j in range(i + 1, len(faces)):
+ shared = faces[i] & faces[j]
+ if len(shared) == 2:
+ a, b = sorted(shared)
+ out.append((keyed[a], keyed[b]))
+ return out
+
+
+def cube_chips(layer):
+ v = cube_vertices()
+ edges = interior_edges()
+ ops = []
+ for a, b in edges:
+ pa, pb = v[a], v[b]
+ for _ in range(7):
+ t = rnd.uniform(0.08, 0.92)
+ p = addv(pa, mul(sub(pb, pa), t))
+ x, y = project(p)
+ dx, dy = rnd.uniform(-2, 2), rnd.uniform(-2, 2)
+ shadow = shade(p, norm(addv((0.0, 0.3, 0.0), (rnd.uniform(-1, 1), 0, rnd.uniform(-1, 1)))), TERRACOTTA)
+ ops.append(stroke(layer, "chalk", rnd.uniform(3, 6), mul(shadow, 0.55), [(x, y), (x + dx, y + dy)], pressure=(0.6, 1), taper=(1, 2), opacity=0.8))
+ ops.append(stroke(layer, "chalk", rnd.uniform(2, 3.5), mul(shade(p, (0.0, 1.0, 0.0), TERRACOTTA), 1.15), [(x - dx * 0.6, y - dy * 0.6), (x, y)], pressure=(0.6, 1), taper=(1, 2), opacity=0.7))
+ return ops
+
+
+def cylinder_strokes(layer):
+ c, r, h = CYL["c"], CYL["r"], CYL["h"]
+ ops = []
+ term = math.atan2(-L[0], L[2])
+ for size, step, jit, opacity in ((20, 0.07, 0.004, 1.0), (10, 0.04, 0.003, 0.9)):
+ phi = rnd.uniform(0, step)
+ while phi < 2 * math.pi:
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ mid = (c[0] + r * n[0], h / 2, c[2] + r * n[2])
+ near_terminator = abs(dot(n, L)) < 0.22
+ if dot(n, to_eye(mid)) > -0.05 and (size > 12 or near_terminator or dot(n, L) > 0.3):
+ y0 = -h * rnd.uniform(0.35, 0.5)
+ while y0 < h:
+ y1 = h * rnd.uniform(1.35, 1.5)
+ pts3 = [(c[0] + r * n[0], y, c[2] + r * n[2]) for y in [y0 + (y1 - y0) * i / 4 for i in range(5)]]
+ rgb = jitter(shade(pts3[2], n, CELADON), jit)
+ ops.append(stroke(layer, "oil", size, rgb, [project(p) for p in pts3], opacity=opacity, bow=False))
+ if y1 >= h:
+ break
+ y0 = y1 - 0.25 * h
+ phi += step * rnd.uniform(0.85, 1.15)
+ return ops
+
+
+def cylinder_top(layer):
+ c, r, h = CYL["c"], CYL["r"], CYL["h"]
+ ops = []
+ for size, rings in ((12, 7), (6, 14)):
+ for i in range(rings):
+ rr = r * (i + rnd.uniform(0.2, 0.9)) / rings
+ a0 = rnd.uniform(0, 2 * math.pi)
+ count = max(3, int(rr * 2.2))
+ for k in range(count):
+ a = a0 + 2 * math.pi * k / count
+ pts3 = [(c[0] + rr * math.cos(t), h, c[2] + rr * math.sin(t)) for t in (a, a + 1.5 / count * math.pi, a + 3 / count * math.pi)]
+ rgb = jitter(shade(pts3[1], (0.0, 1.0, 0.0), CELADON), 0.008)
+ ops.append(stroke(layer, "oil", size, rgb, [project(p) for p in pts3], opacity=0.95))
+ return ops
+
+
+def cylinder_glint(layer):
+ c, r, h = CYL["c"], CYL["r"], CYL["h"]
+ ops = []
+ hv = norm(addv(L, to_eye((c[0], h / 2, c[2]))))
+ phi = math.atan2(hv[2], hv[0])
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ glint = tuple(min(1.0, 0.25 + x * 0.8) for x in shade((c[0] + r * n[0], h / 2, c[2] + r * n[2]), n, CELADON))
+ for k, (y0, y1, size, op) in enumerate(((1.5, 14.5, 7, 0.5), (3.0, 12.5, 3.5, 0.8), (6.0, 10.5, 2, 0.9))):
+ pts = [project((c[0] + r * math.cos(phi + 0.02 * k), y, c[2] + r * math.sin(phi + 0.02 * k))) for y in [y0 + (y1 - y0) * i / 4 for i in range(5)]]
+ ops.append(stroke(layer, "oil", size, glint, pts, opacity=op, bow=False))
+ rim = [project((c[0] + r * math.cos(t), h, c[2] + r * math.sin(t))) for t in [math.pi * (0.95 + 0.9 * i / 10) for i in range(11)]]
+ ops.append(stroke(layer, "oil", 2.5, glint, rim, opacity=0.55))
+ return ops
+
+
+def table_strokes(layer):
+ ops = []
+ for size, brush, jit, opacity in ((30, "oil", 0.02, 1.0), (14, "oil", 0.02, 0.9), (6, "chalk", 0.03, 0.25)):
+ y = TABLE_Y - size * 0.3
+ while y < H + size:
+ z = EYE[1] * F / max(1.0, y - HORIZON)
+ x0 = rnd.uniform(-60, -10)
+ while x0 < W + 10:
+ length = rnd.uniform(60, 150) * (size / 30) ** 0.5
+ xs = [x0 + length * i / 4 for i in range(5)]
+ cols = [table_colour((x - CX) * z / F, z, False, False) for x in xs]
+ rgb = jitter(cols[2][0], jit)
+ ops.append(stroke(layer, brush, size * (0.85 + 0.3 * rnd.random()), rgb, [(x, y + rnd.uniform(-0.8, 0.8)) for x in xs], opacity=opacity))
+ x0 += length * rnd.uniform(0.55, 0.75)
+ y += size * 0.4 * (1 + (y - TABLE_Y) / 900)
+ return ops
+
+
+def shadow_ops():
+ c, r = SPHERE["c"], SPHERE["r"]
+ sphere_pts = [addv(c, (r * math.sin(ph) * math.cos(th), r * math.cos(ph), r * math.sin(ph) * math.sin(th))) for th in [2 * math.pi * i / 48 for i in range(48)] for ph in [math.pi * j / 15 for j in range(16)]]
+ casters = [("sphere", sphere_pts, (c[0], 0.0, c[2])), ("cube", list(cube_vertices().values()), (CUBE["c"][0], 0.0, CUBE["c"][2])), ("cyl", cylinder_points(48), (CYL["c"][0], 0.0, CYL["c"][2]))]
+ ops = [{"op": "add", "layer": {"id": "shadows", "kind": "vector", "name": "cast shadows", "blend": "multiply"}}]
+ texture = []
+ for name, pts, base in casters:
+ ground = drawkit.shadow(pts, L)
+ d = poly(drawkit.silhouette(CAMERA, ground))
+ col = hexc(shadow_colour(ground, base))
+ bx, by = project(base)
+ near = poly([(bx + 150 * math.cos(t), by + 70 * math.sin(t)) for t in [2 * math.pi * i / 48 for i in range(48)]])
+ xs3, zs3 = [q[0] for q in ground], [q[2] for q in ground]
+ cxz = ((min(xs3) + max(xs3)) / 2, (min(zs3) + max(zs3)) / 2)
+ pool = 1 - 0.35 * min(1.0, math.hypot(cxz[0] + 2, cxz[1] - 95) / 70) ** 2
+ ratio = tuple((am * 1.6 + k * 0.035) / (k * L[1] * pool + am * 1.6) for am, k in zip(AMB, KEY))
+ col = hexc(ratio)
+ ops.append({"op": "add", "node": {"id": f"{name}-shadow-soft", "type": "path", "d": d, "fill": col, "blur": 9}, "in": "shadows"})
+ ops.append({"op": "add", "node": {"id": f"{name}-shadow-near", "type": "path", "d": d, "fill": col, "blur": 2.5, "clip": near}, "in": "shadows"})
+ cc, rr = CYL["c"], CYL["r"]
+ cyl_front = [project((cc[0] + rr * 1.04 * math.cos(t), 0.0, cc[2] + rr * 1.04 * math.sin(t))) for t in [math.pi * (0.95 + 1.1 * i / 16) for i in range(17)]]
+ v = cube_vertices()
+ cube_front = []
+ for name, pts, n in cube_faces():
+ if name != "top":
+ cube_front.append([project(p) for p in pts if p[1] < 0.01])
+ sc, sr = SPHERE["c"], SPHERE["r"]
+ sphere_foot = [project((sc[0] + sr * 0.55 * math.cos(t), 0.0, sc[2] + sr * 0.55 * math.sin(t))) for t in [2 * math.pi * i / 32 for i in range(32)]]
+ contact = [("cyl-contact", path(cyl_front), 9, 5), ("sphere-contact", poly(sphere_foot), 0, 7)] + [(f"cube-contact{i}", path(seg), 10, 5) for i, seg in enumerate(cube_front)]
+ for name, d, width, blur in contact:
+ node = {"id": name, "type": "path", "d": d, "blur": blur}
+ if width:
+ node.update({"fill": "none", "stroke": {"paint": "#6e6a66", "width": width, "cap": "round", "join": "round"}})
+ else:
+ node.update({"fill": "#5e5a56"})
+ ops.append({"op": "add", "node": node, "in": "shadows"})
+ return ops
+
+
+def project_inverse(x, y):
+ z = EYE[1] * F / max(1.0, y - HORIZON)
+ return ((x - CX) * z / F, 0.0, z)
+
+
+def shadow_colour(ground, base):
+ xs = [q[0] for q in ground]
+ zs = [q[2] for q in ground]
+ x, z = (min(xs) + max(xs)) / 2, (min(zs) + max(zs)) / 2
+ ao = occlusion((x, 0.0, z))
+ return tuple(a * (am * 1.6 + k * 0.035) * ao for a, am, k in zip(TABLE, AMB, KEY))
+
+
+TABLE_Y = HORIZON + F * EYE[1] / TABLE_Z
+
+
+def wall_strokes(layer):
+ ops = []
+ for size, n, opacity in ((110, 150, 0.45), (55, 220, 0.35)):
+ for _ in range(n):
+ x, y = rnd.uniform(-20, W + 20), rnd.uniform(-20, TABLE_Y - size * 0.5)
+ glow = math.exp(-((x - 560) ** 2 + (y - TABLE_Y) ** 2) / (2 * 420 ** 2))
+ rgb = warm_cool(jitter(mul(WALL, 0.85 + 0.5 * glow), 0.05), rnd.uniform(-0.04, 0.04))
+ ang = rnd.uniform(1.4, 1.75)
+ length = rnd.uniform(60, 160)
+ pts = [(x + math.cos(ang) * length * t, y + math.sin(ang) * length * t) for t in (0, 0.33, 0.66, 1)]
+ ops.append(stroke(layer, "oil-load" if size < 80 else "oil", size * (0.8 + 0.4 * rnd.random()), rgb, pts, opacity=opacity))
+ return ops
+
+
+def accents(layer):
+ ops = []
+ v = cube_vertices()
+ dark = (0.012, 0.01, 0.009)
+ for name, pts, n in cube_faces():
+ if name != "top":
+ continue
+ for i in range(4):
+ a3, b3 = pts[i], pts[(i + 1) % 4]
+ mid = mul(addv(a3, b3), 0.5)
+ outward = norm(sub(mid, (CUBE["c"][0], CUBE["s"], CUBE["c"][2])))
+ if dot(outward, to_eye(mid)) <= 0.1:
+ continue
+ for k in range(3):
+ t0 = rnd.uniform(0.0, 0.6)
+ t1 = min(1.0, t0 + rnd.uniform(0.25, 0.5))
+ seg = [project(addv(a3, mul(sub(b3, a3), t0 + (t1 - t0) * j / 3))) for j in range(4)]
+ ops.append(stroke(layer, "oil", rnd.uniform(2, 3.2), mul(shade(mid, norm(addv((0.0, 1.0, 0.0), outward)), TERRACOTTA), 1.25), seg, opacity=0.65, bow=False))
+ cc, rr = CYL["c"], CYL["r"]
+ front = [project((cc[0] + rr * math.cos(t), 0.0, cc[2] + rr * math.sin(t))) for t in [math.pi * (1 + i / 12) for i in range(13)]]
+ ops.append(stroke(layer, "oil", 4.5, dark, front[::-1], opacity=0.8, bow=False))
+ return ops
+
+
+def warm_cool(rgb, amount):
+ return (rgb[0] * (1 + amount), rgb[1] * (1 + amount * 0.2), rgb[2] * (1 - amount))
+
+
+def ring_point(c, r, frame, alpha, beta):
+ a, u, w = frame
+ return addv(c, mul(addv(mul(a, math.cos(alpha)), mul(addv(mul(u, math.cos(beta)), mul(w, math.sin(beta))), math.sin(alpha))), r))
+
+
+def visible_run(points, ok):
+ runs, run = [], []
+ for p in points:
+ if ok(p):
+ run.append(p)
+ else:
+ runs.append(run)
+ run = []
+ runs.append(run)
+ return max(runs, key=len)
+
+
+def decisive_sphere(layer):
+ c, r = SPHERE["c"], SPHERE["r"]
+ frame = basis(L)
+ scale = F / (c[2] - EYE[2])
+ ops = []
+ bands = [(60, 2, 72, (12, 24), "oil-load", 0.05, 0.03, 0.95), (26, 74, 98, (8, 14), "oil-load", 0.035, 0.05, 0.9), (16, 100, 150, (14, 22), "oil", 0.02, -0.03, 0.75)]
+ for count, a0, a1, (s0, s1), brush, jit, temp, opacity in bands:
+ for _ in range(count):
+ alpha = math.radians(rnd.uniform(a0, a1))
+ beta = rnd.uniform(0, 2 * math.pi)
+ length = rnd.uniform(40, 95)
+ span = min(2.6, length / max(1.0, r * scale * math.sin(alpha)))
+ pts3 = [ring_point(c, r, frame, alpha + rnd.uniform(-0.01, 0.01), beta + span * (i / 6 - 0.5)) for i in range(7)]
+ seen = visible_run(pts3, lambda p: dot(norm(sub(p, c)), to_eye(p)) > 0.04)
+ if len(seen) < 3:
+ continue
+ mid = seen[len(seen) // 2]
+ rgb = warm_cool(jitter(shade(mid, norm(sub(mid, c)), PLASTER), jit), temp + rnd.uniform(-0.03, 0.03))
+ ops.append(stroke(layer, brush, rnd.uniform(s0, s1), rgb, [project(p) for p in seen], opacity=opacity, bow=False))
+ return ops
+
+
+def sphere_pits(layer):
+ c, r = SPHERE["c"], SPHERE["r"]
+ frame = basis(L)
+ ops = []
+ light2 = norm((L[0], -L[1]))
+ for _ in range(170):
+ alpha = math.radians(min(150.0, max(5.0, rnd.gauss(80, 28))))
+ p = ring_point(c, r, frame, alpha, rnd.uniform(0, 2 * math.pi))
+ n = norm(sub(p, c))
+ if dot(n, to_eye(p)) < 0.25:
+ continue
+ x, y = project(p)
+ local = shade(p, n, PLASTER)
+ size = rnd.uniform(1.1, 2.4)
+ dx, dy = light2[0] * size * 0.6, light2[1] * size * 0.6
+ ops.append(stroke(layer, "oil", size, mul(local, 0.62), [(x + dx * 0.2, y + dy * 0.2), (x + dx, y + dy + 0.4)], pressure=(0.8, 1), taper=(0.5, 0.8), opacity=0.8))
+ if dot(n, L) > 0.05:
+ ops.append(stroke(layer, "oil", size * 0.8, mul(local, 1.1), [(x - dx, y - dy), (x - dx * 0.2, y - dy * 0.2 + 0.4)], pressure=(0.8, 1), taper=(0.5, 0.8), opacity=0.7))
+ return ops
+
+
+def sphere_edges(layer):
+ c, r = SPHERE["c"], SPHERE["r"]
+ sil = sphere_silhouette()
+ cx, cy = project(c)
+ ops = []
+ for x, y in sil:
+ ang = math.atan2(y - cy, x - cx)
+ if not (0.1 < ang < 2.2) or rnd.random() < 0.55:
+ continue
+ nx, ny = math.cos(ang), math.sin(ang)
+ tx, ty = -ny, nx
+ inner = project(addv(c, mul(norm((nx, -ny, -0.15)), r)))
+ col = shade(addv(c, mul(norm((nx, -ny, 0.1)), r)), norm((nx, -ny, 0.1)), PLASTER)
+ col = tuple(0.5 * a + 0.5 * b for a, b in zip(col, mul(TABLE, 0.11)))
+ ops.append(stroke(layer, "oil", rnd.uniform(5, 9), col, [(x - tx * 9 - nx * 2, y - ty * 9 - ny * 2), (x + nx * 1.5, y + ny * 1.5), (x + tx * 9 - nx * 2, y + ty * 9 - ny * 2)], opacity=0.55, bow=False))
+ return ops
+
+
+def decisive_cube(layer, only):
+ ops = []
+ for name, (p0, p1, p2, p3), n in cube_faces():
+ if name != only:
+ continue
+ along, up = sub(p1, p0), sub(p3, p0)
+ lit = dot(n, L) > 0.1
+ for _ in range(48 if lit else 14):
+ t = rnd.uniform(0.02, 0.98)
+ s0 = rnd.uniform(-0.05, 0.85)
+ s1 = min(1.05, s0 + rnd.uniform(0.12, 0.32))
+ cross = lit and rnd.random() < 0.2
+ if cross:
+ pts3 = [addv(p0, addv(mul(along, s0 + rnd.uniform(-0.01, 0.01)), mul(up, max(0.0, min(1.0, t - 0.1 + 0.2 * i / 4))))) for i in range(5)]
+ else:
+ tilt = rnd.uniform(-0.03, 0.03)
+ pts3 = [addv(p0, addv(mul(along, s0 + (s1 - s0) * i / 4), mul(up, t + tilt * i / 4))) for i in range(5)]
+ rgb = warm_cool(jitter(shade(pts3[2], n, TERRACOTTA), 0.06 if lit else 0.025), rnd.uniform(-0.04, 0.05))
+ ops.append(stroke(layer, "oil-load" if lit else "oil", rnd.uniform(12, 26) if lit else rnd.uniform(18, 30), rgb, [project(p) for p in pts3], opacity=0.9 if lit else 0.6))
+ return ops
+
+
+def cube_grain(layer, only):
+ ops = []
+ for name, (p0, p1, p2, p3), n in cube_faces():
+ if name != only:
+ continue
+ along, up = sub(p1, p0), sub(p3, p0)
+ lit = dot(n, L) > 0.1
+ spots = []
+ for _ in range(16 if lit else 5):
+ cu, cv = rnd.uniform(0.05, 0.95), rnd.uniform(0.05, 0.95)
+ spread = rnd.uniform(0.02, 0.07)
+ spots += [(min(0.99, max(0.01, rnd.gauss(cu, spread))), min(0.99, max(0.01, rnd.gauss(cv, spread)))) for _ in range(rnd.randint(4, 14))]
+ spots += [(rnd.uniform(0.01, 0.99), rnd.uniform(0.01, 0.99)) for _ in range(50 if lit else 15)]
+ for su, sv in spots:
+ p = addv(p0, addv(mul(along, su), mul(up, sv)))
+ x, y = project(p)
+ local = shade(p, n, TERRACOTTA)
+ k = rnd.choice((0.8, 0.86, 1.1, 1.16)) if lit else rnd.choice((0.88, 1.1))
+ size = rnd.uniform(0.8, 2.4) * rnd.choice((1, 1, 1, 1.8))
+ ang = rnd.uniform(0, math.pi)
+ ops.append(stroke(layer, "oil", size, mul(local, k), [(x, y), (x + math.cos(ang) * size * 1.4, y + math.sin(ang) * size * 1.4)], pressure=(0.9, 1), taper=(0.4, 0.6), opacity=0.55 if lit else 0.35))
+ bottom = sorted([p0, p1, p2, p3], key=lambda q: q[1])[:2]
+ if name != "top":
+ for _ in range(10):
+ t0 = rnd.uniform(0, 0.8)
+ a3 = addv(bottom[0], mul(sub(bottom[1], bottom[0]), t0))
+ b3 = addv(bottom[0], mul(sub(bottom[1], bottom[0]), min(1.0, t0 + rnd.uniform(0.15, 0.3))))
+ lift = (0.0, rnd.uniform(0.4, 1.4), 0.0)
+ ops.append(stroke(layer, "oil", rnd.uniform(5, 10), mul(shade(a3, n, TERRACOTTA), 0.7), [project(addv(a3, lift)), project(addv(mul(addv(a3, b3), 0.5), lift)), project(addv(b3, lift))], opacity=0.4))
+ return ops
+
+
+def cube_wear(layer):
+ ops = []
+ faces = {name: n for name, pts, n in cube_faces()}
+ for a, b in interior_edges():
+ v = cube_vertices()
+ pa, pb = v[a], v[b]
+ for t in sorted(rnd.uniform(0.06, 0.94) for _ in range(rnd.randint(2, 5))):
+ p = addv(pa, mul(sub(pb, pa), t))
+ x, y = project(p)
+ ex, ey = project(addv(p, mul(norm(sub(pb, pa)), 1.0)))
+ dx, dy = ex - x, ey - y
+ d = math.hypot(dx, dy) or 1
+ tx, ty = dx / d, dy / d
+ nx, ny = -ty, tx
+ size = rnd.uniform(2.0, 4.5) * rnd.choice((1, 1, 1.7))
+ length = rnd.uniform(4, 14)
+ dark = mul(shade(p, norm((0.3, -0.2, 0.4)), TERRACOTTA), 0.6)
+ light = mul(shade(p, (0.0, 1.0, 0.0), TERRACOTTA), 1.2)
+ side = rnd.choice((-1, 1))
+ ops.append(stroke(layer, "oil-load", size, dark, [(x - tx * length / 2 + nx * side * 1.2, y - ty * length / 2 + ny * side * 1.2), (x + nx * side * 2, y + ny * side * 2), (x + tx * length / 2 + nx * side * 1.2, y + ty * length / 2 + ny * side * 1.2)], opacity=0.85, bow=False))
+ ops.append(stroke(layer, "oil", size * 0.45, light, [(x - tx * length / 2 - nx * side * 0.6, y - ty * length / 2 - ny * side * 0.6), (x + tx * length / 2 - nx * side * 0.6, y + ty * length / 2 - ny * side * 0.6)], opacity=0.75, bow=False))
+ return ops
+
+
+def cylinder_detail(layer):
+ c, r, h = CYL["c"], CYL["r"], CYL["h"]
+ ops = []
+ for _ in range(30):
+ phi = rnd.uniform(0, 2 * math.pi)
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ if dot(n, L) < 0.25 or dot(n, to_eye((c[0], h / 2, c[2]))) < 0.1:
+ continue
+ y0 = rnd.uniform(1.5, h * 0.55)
+ y1 = min(h - 1.0, y0 + rnd.uniform(0.3, 0.6) * h)
+ pts = [project((c[0] + r * n[0], y0 + (y1 - y0) * i / 4, c[2] + r * n[2])) for i in range(5)]
+ rgb = warm_cool(jitter(shade((c[0] + r * n[0], (y0 + y1) / 2, c[2] + r * n[2]), n, CELADON), 0.03), rnd.uniform(-0.03, 0.03))
+ ops.append(stroke(layer, "oil-load", rnd.uniform(7, 14), rgb, pts, opacity=0.8, bow=False))
+ for band, y, k, size, opacity in (("foot", 0.35, None, 6, 0.95), ("pool", 1.15, 0.62, 5, 0.85)):
+ for i in range(36):
+ phi = 2 * math.pi * i / 36
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ if dot(n, to_eye((c[0], y, c[2]))) < 0.0:
+ continue
+ pts = [project((c[0] + r * math.cos(phi + d), y + rnd.uniform(-0.05, 0.05), c[2] + r * math.sin(phi + d))) for d in (-0.12, 0.0, 0.12)]
+ local = shade((c[0] + r * n[0], y, c[2] + r * n[2]), n, CELADON)
+ rgb = shade((c[0] + r * n[0], y, c[2] + r * n[2]), n, (0.66, 0.5, 0.38)) if band == "foot" else mul(local, k)
+ ops.append(stroke(layer, "oil", size, rgb, pts, opacity=opacity, bow=False))
+ for _ in range(34):
+ phi = rnd.uniform(0, 2 * math.pi)
+ y = rnd.uniform(2.0, h - 0.5)
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ if dot(n, L) < 0.1 or dot(n, to_eye((c[0], y, c[2]))) < 0.15:
+ continue
+ pts = []
+ for _ in range(4):
+ pts.append(project((c[0] + r * math.cos(phi), y, c[2] + r * math.sin(phi))))
+ phi += rnd.uniform(-0.12, 0.12)
+ y += rnd.uniform(-0.9, 0.9)
+ local = shade((c[0] + r * n[0], y, c[2] + r * n[2]), n, CELADON)
+ ops.append(stroke(layer, "oil", rnd.uniform(0.8, 1.3), mul(local, 0.72), pts, pressure=(0.6, 1, 0.9, 0.5), taper=(1, 2), opacity=0.55, bow=False))
+ for _ in range(10):
+ phi = rnd.uniform(0, 2 * math.pi)
+ n = (math.cos(phi), 0.0, math.sin(phi))
+ if dot(n, L) > -0.05 or dot(n, to_eye((c[0], 2, c[2]))) < 0.05:
+ continue
+ pts = [project((c[0] + r * n[0], y, c[2] + r * n[2])) for y in (0.6, 1.6, 2.6, 3.4)]
+ local = shade((c[0] + r * n[0], 1.5, c[2] + r * n[2]), n, CELADON)
+ rgb = tuple(0.85 * a + 0.15 * b for a, b in zip(local, table_colour(c[0] + 8, c[2] - 6, False, False)[0]))
+ ops.append(stroke(layer, "oil", rnd.uniform(4, 7), rgb, pts, opacity=0.35, bow=False))
+ return ops
+
+
+def table_marks(layer):
+ ops = []
+ for _ in range(90):
+ y = rnd.uniform(TABLE_Y + 8, H)
+ z = EYE[1] * F / (y - HORIZON)
+ x = rnd.uniform(-20, W)
+ length = rnd.uniform(70, 200)
+ xs = [x + length * i / 4 for i in range(5)]
+ col = table_colour((x + length / 2 - CX) * z / F, z, False, False)[0]
+ rgb = warm_cool(jitter(col, 0.035), rnd.uniform(-0.03, 0.04))
+ ops.append(stroke(layer, "oil-load", rnd.uniform(14, 30) * (0.6 + 0.6 * (y - TABLE_Y) / (H - TABLE_Y)), rgb, [(xx, y + rnd.uniform(-1.5, 1.5)) for xx in xs], opacity=0.55))
+ return ops
+
+
+def scene():
+ ops = [{"op": "add", "layer": {"id": "sketch", "kind": "vector", "name": "construction", "visible": False}},
+ {"op": "add", "layer": {"id": "wall-base", "kind": "vector", "name": "wall base"}},
+ {"op": "add", "node": {"id": "wall-grad", "type": "rect", "x": -5, "y": -5, "w": W + 10, "h": TABLE_Y + 6, "fill": {"radial": {"center": [560, TABLE_Y], "radius": 900, "stops": [[0, hexc(mul(WALL, 1.3))], [0.6, hexc(mul(WALL, 0.95))], [1, hexc(mul(WALL, 0.7))]]}}}, "in": "wall-base"}]
+ shapes = {
+ "table-shape": poly([(-5, TABLE_Y), (W + 5, TABLE_Y), (W + 5, H + 5), (-5, H + 5)]),
+ "sphere-shape": poly(sphere_silhouette()),
+ "cube-shape": poly(drawkit.hull([project(p) for p in cube_vertices().values()])),
+ "cyl-shape": poly(drawkit.hull([project(p) for p in cylinder_points()])),
+ }
+ cc, rr, hh = CYL["c"], CYL["r"], CYL["h"]
+ shapes["cyl-top-shape"] = poly([project((cc[0] + rr * math.cos(t), hh, cc[2] + rr * math.sin(t))) for t in [2 * math.pi * i / 72 for i in range(72)]])
+ for name, pts, n in cube_faces():
+ shapes[f"cube-{name}-shape"] = poly([project(p) for p in pts])
+ ops += [{"op": "add", "node": {"id": k, "type": "path", "d": d}, "in": "sketch"} for k, d in shapes.items()]
+ a = L
+ lit_mid = norm(addv(mul(a, 0.55), (0.0, 0.0, -0.45)))
+ ops.append({"op": "add", "layer": {"id": "wall", "kind": "paint", "name": "wall strokes"}})
+ ops += wall_strokes("wall")
+ ops.append({"op": "add", "layer": {"id": "table", "kind": "paint", "name": "table"}})
+ ops.append({"op": "fill", "layer": "table", "shape": "table-shape", "color": hexc(table_colour(0, 120)[0])})
+ ops.append({"op": "set", "id": "table", "lockAlpha": True})
+ ops += table_strokes("table") + table_marks("table") + shadow_ops()
+ ops.append({"op": "add", "layer": {"id": "cylinder", "kind": "paint", "name": "cylinder"}})
+ ops.append({"op": "fill", "layer": "cylinder", "shape": "cyl-shape", "color": hexc(shade((cc[0] - 3, 8, cc[2] - 4), norm((-0.6, 0.0, -0.8)), CELADON))})
+ ops.append({"op": "set", "id": "cylinder", "lockAlpha": True})
+ ops += cylinder_strokes("cylinder") + cylinder_detail("cylinder")
+ ops.append({"op": "add", "layer": {"id": "cylinder-top", "kind": "paint", "name": "cylinder top"}})
+ ops.append({"op": "fill", "layer": "cylinder-top", "shape": "cyl-top-shape", "color": hexc(shade((cc[0], hh, cc[2]), (0.0, 1.0, 0.0), CELADON))})
+ ops.append({"op": "set", "id": "cylinder-top", "lockAlpha": True})
+ ops += cylinder_top("cylinder-top")
+ ops.append({"op": "add", "layer": {"id": "cylinder-glint", "kind": "paint", "name": "cylinder glint"}})
+ ops += cylinder_glint("cylinder-glint")
+ for name, pts, n in cube_faces():
+ centre = mul(addv(addv(pts[0], pts[1]), addv(pts[2], pts[3])), 0.25)
+ lid = f"cube-{name}"
+ ops.append({"op": "add", "layer": {"id": lid, "kind": "paint", "name": f"cube {name}"}})
+ ops.append({"op": "fill", "layer": lid, "shape": f"cube-{name}-shape", "color": hexc(shade(centre, n, TERRACOTTA))})
+ ops.append({"op": "set", "id": lid, "lockAlpha": True})
+ ops += cube_strokes(lid, name) + decisive_cube(lid, name) + cube_grain(lid, name)
+ ops.append({"op": "add", "layer": {"id": "cube-chips", "kind": "paint", "name": "cube chips"}})
+ ops += cube_wear("cube-chips")
+ ops.append({"op": "add", "layer": {"id": "sphere", "kind": "paint", "name": "sphere"}})
+ ops.append({"op": "fill", "layer": "sphere", "shape": "sphere-shape", "color": hexc(shade(addv(SPHERE["c"], mul(lit_mid, SPHERE["r"])), lit_mid, PLASTER))})
+ ops.append({"op": "set", "id": "sphere", "lockAlpha": True})
+ ops += sphere_strokes("sphere") + decisive_sphere("sphere") + sphere_pits("sphere")
+ ops.append({"op": "add", "layer": {"id": "edges", "kind": "paint", "name": "lost edges"}})
+ ops += sphere_edges("edges")
+ ops.append({"op": "add", "layer": {"id": "accents", "kind": "paint", "name": "accents"}})
+ ops += accents("accents")
+ return ops
+
+
+print("\n".join(json.dumps(o) for o in scene()))