A drawing app built for agent/human collaboration
Rust
Licences: a source-available app, an MIT format, reference and client
Indicode BV362471ca9890
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex a71c1aa..507c642 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -11,82 +11,47 @@ jobs:check:uses: ./.github/workflows/check.yml- build:+ windows:needs: check- strategy:- fail-fast: false- matrix:- include:- - os: macos-14- target: aarch64-apple-darwin- app: true- - os: macos-14- target: x86_64-apple-darwin- - os: ubuntu-24.04- target: x86_64-unknown-linux-gnu- appimage: x86_64- - os: ubuntu-24.04-arm- target: aarch64-unknown-linux-gnu- appimage: aarch64- - os: windows-latest- target: x86_64-pc-windows-msvc- runs-on: ${{ matrix.os }}+ runs-on: windows-latest+ env:+ BUTLER_API_KEY: ${{ secrets.BUTLER_API_KEY }}+ ITCH_TARGET: ${{ vars.ITCH_TARGET }}steps:- uses: actions/checkout@v4with:fetch-depth: 0- - name: System libraries- if: runner.os == 'Linux'- run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libfontconfig1-dev libfuse2- uses: dtolnay/rust-toolchain@stablewith:- targets: ${{ matrix.target }}+ targets: x86_64-pc-windows-msvc- uses: Swatinem/rust-cache@v2with:- key: ${{ matrix.target }}- - name: AppImage tool- if: matrix.appimage- run: |- curl -fsSL -o appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${{ matrix.appimage }}.AppImage"- chmod +x appimagetool- echo "APPIMAGETOOL=$PWD/appimagetool" >> "$GITHUB_ENV"- - name: Archive+ key: x86_64-pc-windows-msvc+ - name: Build+ shell: bash+ run: bash packaging/archive.sh x86_64-pc-windows-msvc dist+ # TODO: sign klad.exe and klad-editor.exe before they are pushed+ - name: Push to itch.io+ if: env.BUTLER_API_KEY != '' && env.ITCH_TARGET != ''shell: bash- run: bash packaging/archive.sh ${{ matrix.target }} dist- - name: Mac app and disk image- if: matrix.app- env:- KLAD_MAC_TARGETS: aarch64-apple-darwin x86_64-apple-darwinrun: |- rustup target add x86_64-apple-darwin- bash packaging/macos/app.sh dist- - uses: actions/upload-artifact@v4- with:- name: klad-${{ matrix.target }}- path: |- dist/*.tar.gz- dist/*.zip- dist/*.dmg- dist/*.AppImage+ curl -fsSL -o butler.zip https://broth.itch.zone/butler/windows-amd64/LATEST/archive/default+ unzip -q butler.zip -d butler+ ./butler/butler.exe push dist/klad-*-windows-x86_64 "$ITCH_TARGET:windows" --userversion "${GITHUB_REF_NAME#v}"release:- needs: build+ needs: windowsruns-on: ubuntu-24.04permissions:contents: writesteps:- uses: actions/checkout@v4- - uses: actions/download-artifact@v4- with:- path: artefacts- merge-multiple: true- - name: Checksums and notes+ - name: Notesrun: |- cd artefacts && sha256sum * > checksums.txt && cd ..version="${GITHUB_REF_NAME#v}"awk -v v="$version" '$0 ~ "^## "v"( |$)" {on=1; next} /^## / {on=0} on' CHANGELOG.md > notes.md[ -s notes.md ] || echo "klad $version" > notes.md- name: Releaseenv:GH_TOKEN: ${{ github.token }}- run: gh release create "$GITHUB_REF_NAME" artefacts/* --title "klad ${GITHUB_REF_NAME#v}" --notes-file notes.md+ run: gh release create "$GITHUB_REF_NAME" --title "klad ${GITHUB_REF_NAME#v}" --notes-file notes.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex b30595f..7572c87 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,9 +2,11 @@## Unreleased-The first downloadable builds.+The first builds, and klad's licences.-- Downloads for macOS (an app and a disk image, Apple silicon and Intel in one), Windows and Linux (archives and AppImages), each with the `klad` command line, the editor, the fonts, the licences and the agent skill.+- klad is source-available, not open source: the app is under the PolyForm Internal Use License 1.0.0, with permission for personal use and to share the drawings you make (`LICENSE`). The file format (`docs/format.md`), the command reference (`docs/cli.md`), the agent skill and the new `klad-client` crate are MIT (`LICENSE-MIT`), so any program or agent can read, write and make klad drawings. Contributions come in under a contributor licence agreement (`CLA.md`).+- `klad-client`: run klad from Rust, apply edits as JSON ops, read drawings back as JSON, render them.+- Builds for macOS (an app, Apple silicon and Intel in one) and Windows, sold on itch.io; Linux from source. Each has the `klad` command line, the editor, the fonts, the licences and the agent skill.- The editor runs on Windows and Linux (`klad open`, or `klad-editor`), with the platform's open dialog; pens that report pressure through the system (Windows) draw with it.- On a Mac, `.draw` drawings show in Finder as one item and open in klad with a double click.- `klad install` (and "install the klad command" in the editor's document menu) puts `klad` on the terminal's path, for you and for agents. `klad skill` prints the agent skill.diff --git a/CLA.md b/CLA.mdnew file mode 100644index 0000000..21f1db3--- /dev/null+++ b/CLA.md@@ -0,0 +1,34 @@+# klad contributor licence agreement++Thank you for contributing to klad. This agreement is between you and Indicode BV, which makes klad. It lets Indicode BV ship what you send in klad, under the licences klad has now and any it has later; you keep the copyright to your work and may do anything else you like with it. Sign it once, through the CLA assistant on your first pull request, and it covers everything you contribute after.++## 1. Words used here++- **You**: the person signing, or the company or organisation you sign for. If you sign for one, "you" includes everyone it controls, is controlled by or is under common control with.+- **Contribution**: any work you send to Indicode BV for klad (code, documentation, drawings, brushes, fonts, translations, anything else), through a pull request, an issue, a patch or any other way, unless you mark it at the time as "not a contribution".++## 2. Copyright licence++You give Indicode BV, and everyone who receives klad from it, a perpetual, worldwide, non-exclusive, free, royalty-free and irrevocable licence to reproduce, change, make works based on, publicly display, publicly perform, sublicense and distribute your contributions and works based on them, under any terms, including the licences klad is offered under now and any Indicode BV chooses later, open source or not.++## 3. Patent licence++You give Indicode BV, and everyone who receives klad from it, a perpetual, worldwide, non-exclusive, free, royalty-free and irrevocable patent licence to make, have made, use, offer to sell, sell, import and otherwise transfer klad, for the patent claims you can license that your contribution infringes, alone or combined with klad as it was when you sent it. If anyone sues claiming that klad or a contribution infringes a patent, every patent licence this agreement gave them for klad ends on the day the suit is filed.++## 4. What you promise++- You have the right to give these licences. If your employer or anyone else has rights to what you make, you have their permission to contribute, or they have signed this agreement for you.+- Each contribution is your own work. Anything in it that is not (code, pictures or fonts made by someone else) you name in the pull request, with its source and its licence.+- You tell Indicode BV if any of this stops being true.++As far as the law allows, you will not use moral rights in your contributions to stop Indicode BV from using them as this agreement allows.++## 5. What it does not do++- Indicode BV does not have to use your contribution.+- You do not have to support your contribution. Unless you say otherwise, you give it as it is, without any warranty or condition.+- Your contribution stays yours: this agreement gives licences, it transfers no ownership.++## 6. Law++Belgian law governs this agreement, and the courts of the place where Indicode BV has its registered office decide any dispute about it.diff --git a/CLAUDE.md b/CLAUDE.mdindex 8a018e6..2e67587 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -32,5 +32,5 @@ Agent-first 2D art application in Rust: a `klad` CLI for agents and a native edi- 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), and the fonts in `fonts/` OFL-1.1 or Apache-2.0 (`fonts/update.py` fetches them unchanged; the notices list them). 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`).+- klad is source-available, not open source, copyright Indicode BV: the app is under the PolyForm Internal Use License 1.0.0 with a personal-use permission and one for drawings (`LICENSE`). `docs/format.md`, `docs/cli.md`, `docs/skill/` and `crates/client` are MIT (`LICENSE-MIT`): `klad-client` depends on none of the other crates, a format change updates `docs/format.md` in the same change, and a command change runs `just reference` (a test checks `docs/cli.md`). Outside contributions come in under the CLA (`CLA.md`).- No em-dashes in docs, messages or UI text.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a923e60..697a56f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -34,11 +34,15 @@ These come from `CLAUDE.md`, which is also the guide for coding agents working o1. 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.+4. The first time, the CLA assistant asks you in the pull request to sign the contributor licence agreement (`CLA.md`): one click, and it covers every later change. It lets Indicode BV ship your change in klad under its licences; you keep the copyright to your work.-By sending a contribution you agree that Indicode BV may publish it under the licence of the project.+klad is source-available, not open source (`LICENSE`): a fork on GitHub to send pull requests is fine, publishing klad or builds of it elsewhere is not. The file format, the command reference, the agent skill and `klad-client` are MIT (`LICENSE-MIT`); `klad-client` depends on nothing in the other crates, so it stays MIT on its own.## Releases-1. Move the changes under "Unreleased" in `CHANGELOG.md` to a section `## x.y.z (date)` and bump `version` in the workspace `Cargo.toml`.-2. Commit, tag `vx.y.z` and push the tag. The `release` workflow runs the checks, builds the macOS app and disk image (arm64 and x86_64 in one), `klad` archives for macOS, Linux (x86_64, arm64, also as AppImages) and Windows, writes `checksums.txt` and publishes them with that section of the changelog as the notes.-3. The builds are not signed or notarised yet; the README says how to open them.+The Mac and Windows builds are sold on itch.io (and later Steam); Linux is built from source. GitHub has the release notes, not downloads.++1. Move the changes under "Unreleased" in `CHANGELOG.md` to a section `## x.y.z (date)` and bump `version` in the workspace `Cargo.toml`. Commit.+2. On a Mac with [butler](https://itch.io/docs/butler/) logged in: `ITCH_TARGET=<user>/<page> just itch-mac` builds the app (arm64 and x86_64 in one) and pushes it to the page's `mac` channel.+3. Tag `vx.y.z` and push the tag. The `release` workflow runs the checks, builds the Windows version and pushes it to the `windows` channel (with the `BUTLER_API_KEY` secret and the `ITCH_TARGET` variable set in the repository), then publishes that changelog section as the release notes, which the editor's update check reads.+4. The builds are not signed yet.diff --git a/Cargo.lock b/Cargo.lockindex 1a3ae81..3886eff 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1794,6 +1794,7 @@ dependencies = ["clap","klad-app","klad-brush",+ "klad-client","klad-core","klad-render","libc",@@ -1804,6 +1805,13 @@ dependencies = ["zstd",]+[[package]]+name = "klad-client"+version = "0.1.0"+dependencies = [+ "serde_json",+]+[[package]]name = "klad-core"version = "0.1.0"diff --git a/LICENSE b/LICENSEindex 47def88..d6b49b8 100644--- a/LICENSE+++ b/LICENSE@@ -18,6 +18,9 @@ as itch.io or Steam, are licensed under these same terms.Third-party parts keep their own licences: see THIRD-PARTY-NOTICES.md.+These files are licensed under the MIT License instead (see LICENSE-MIT):+docs/format.md, docs/cli.md, docs/skill/ and crates/client/.+---# PolyForm Internal Use License 1.0.0diff --git a/LICENSE-MIT b/LICENSE-MITnew file mode 100644index 0000000..cc12df7--- /dev/null+++ b/LICENSE-MIT@@ -0,0 +1,35 @@+klad: the parts under the MIT License+Copyright (c) 2026 Indicode BV++These parts of klad describe and drive it, so that any program or agent can+read, write and make klad drawings without the app's licence. Unlike the rest+of klad (see LICENSE), they are licensed under the MIT License below:++- docs/format.md: the file format of a klad drawing+- docs/cli.md: the command reference+- docs/skill/: the agent skill (SKILL.md and drawkit.py)+- crates/client/: the klad-client crate++---++MIT License++Copyright (c) 2026 Indicode BV++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/README.md b/README.mdindex a95f501..8ab4827 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@-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.+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. klad is source-available, not open source: you can read the code, build it and change it for yourself or inside your company, and send changes back, but not hand out copies of it (see [Licence](#licence)).@@ -46,13 +46,10 @@ Early, and open for testing. What works today:## Try it-Download klad from the [releases page](https://github.com/klad-app/klad/releases):+- macOS and Windows: signed installers will be sold on itch.io and Steam. Until then, build klad from source as below.+- Linux: build it from source, free.-- macOS: `klad-<version>-macos.dmg`. Drag klad to Applications. The app is not signed yet: the first time, right click it and choose Open. In the editor, the document menu's "install the klad command" puts `klad` on your terminal's path for you and for agents.-- Windows: `klad-<version>-windows-x86_64.zip`. Unzip it anywhere and start `klad-editor.exe`; `klad.exe install` adds the folder to your PATH.-- Linux: `klad-<version>-<arch>.AppImage` (make it executable and run it), or the `tar.gz` with `klad` and `klad-editor`; `klad install` links `klad` into `~/.local/bin`.--Every download holds the same `klad` command line tool, the editor, the fonts, the licences and the agent skill (`klad skill` prints it). The editor checks the releases page once a day for a new version and says so; it installs nothing by itself (turn it off in the settings window).+Every build holds the `klad` command line tool, the editor, the fonts, the licences and the agent skill (`klad skill` prints it). In the editor, the document menu's "install the klad command" puts `klad` on your terminal's path for you and for agents (`klad install` does the same). The editor checks klad's releases once a day for a new version and says so; it installs nothing by itself (turn it off in the settings window).### From source@@ -79,7 +76,10 @@ The agent looks at the drawing through renders (`klad render`), changes it with## Building on it-- `docs/DESIGN.md`: the document format, the CLI, the brush engine, rendering, the editor, the dependencies.+- `docs/format.md`: the file format of a drawing, enough to read and write one from any program.+- `docs/cli.md`: every command with its options (`klad <command> --help` prints the same).+- `crates/client`: `klad-client`, a small Rust crate that runs klad commands, applies edits as JSON ops and reads drawings back.+- `docs/DESIGN.md`: how klad is built: 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.@@ -93,4 +93,10 @@ 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.+klad is source-available, not open source, copyright Indicode BV.++- The app (everything not listed below) is under the [PolyForm Internal Use License 1.0.0](https://polyformproject.org/licenses/internal-use/1.0.0) with two additional permissions (`LICENSE`): you may use it for your own personal purposes as well as inside your company, and the drawings you make with it are yours to share, with the brush settings and pictures klad copies into them. You may build it and change it for those uses; you may not distribute it, from source or as a build.+- The parts other programs and agents need to work with klad are under the MIT License (`LICENSE-MIT`): the file format (`docs/format.md`), the command reference (`docs/cli.md`), the agent skill (`docs/skill/`) and the `klad-client` crate (`crates/client`).+- Contributions are welcome under the contributor licence agreement (`CLA.md`); see `CONTRIBUTING.md`.++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/crates/app/src/layout.rs b/crates/app/src/layout.rsindex 773203e..e73d1ce 100644--- a/crates/app/src/layout.rs+++ b/crates/app/src/layout.rs@@ -327,7 +327,10 @@ mod tests {.unwrap().repaired();assert_eq!(old.panes.len(), 6);- assert!(!old.is_open(Pane::Agent), "the agent pane comes closed until it is asked for");+ assert!(+ !old.is_open(Pane::Agent),+ "the agent pane comes closed until it is asked for"+ );assert_eq!(old.panes[0].pane, Pane::Layers);assert_eq!(old.panes[0].body, Pane::Layers.min_body());}diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.tomlindex 8a044a4..ca1bb6a 100644--- a/crates/cli/Cargo.toml+++ b/crates/cli/Cargo.toml@@ -36,5 +36,8 @@ version = "0.1.0"path = "../app"optional = true+[dev-dependencies]+klad-client = { version = "0.1.0", path = "../client" }+[target."cfg(unix)".dependencies]libc = "0.2.191"diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex a3289f7..48001e8 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1701,6 +1701,8 @@ enum Command {},#[command(about = "Print the agent skill: how an agent draws with klad (the same text as docs/skill/SKILL.md)")]Skill,+ #[command(hide = true, about = "Print the command reference, docs/cli.md")]+ Reference,#[command(about = "Measure stroke storage, brush speed, replay, cache and compositing")]Bench {#[arg(long, default_value_t = 10_000)]@@ -3286,6 +3288,7 @@ fn run() -> Result<()> {Command::Licences => print!("{}\n{}", klad_core::notices::LICENSE, klad_core::notices::NOTICES),Command::Install { dir } => install::install(dir.as_deref())?,Command::Skill => print!("{}", include_str!("../../../docs/skill/SKILL.md")),+ Command::Reference => print!("{}", reference()),Command::Bench { strokes, size, seed } => bench::run(strokes, size, seed)?,#[cfg(feature = "editor")]Command::Open { bundle } => klad_app::run(bundle)?,@@ -3544,11 +3547,67 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {Ok(())}+const REFERENCE_HEAD: &str = "_Last updated: with the commands it lists. `just reference` writes it from `klad reference`; `cargo test -p klad-cli` fails when it is out of date._++# klad command reference++Every command of the `klad` command line with its options, as `klad <command> --help` prints them. A drawing is a `.draw` folder (`docs/format.md`); `klad apply` takes the same edits as JSON lines, one transaction per call. `docs/skill/SKILL.md` explains how an agent uses them, and the `klad-client` crate (`crates/client`) runs them from Rust.++This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad itself.++## Commands++";++fn reference() -> String {+ use clap::CommandFactory;+ let mut cli = Cli::command();+ cli.build();+ let sections: Vec<(String, String, String)> = cli+ .get_subcommands_mut()+ .filter(|c| !c.is_hide_set() && c.get_name() != "help")+ .map(|c| {+ let about = c.get_about().map(ToString::to_string).unwrap_or_default();+ (c.get_name().to_string(), about, c.render_long_help().to_string())+ })+ .collect();+ let index: String = sections+ .iter()+ .map(|(name, about, _)| format!("- [`klad {name}`](#klad-{name}): {about}\n"))+ .collect();+ let body: String = sections+ .iter()+ .map(|(name, _, help)| format!("\n## klad {name}\n\n```text\n{}\n```\n", trimmed(help)))+ .collect();+ format!("{REFERENCE_HEAD}{index}{body}")+}++fn trimmed(help: &str) -> String {+ help.trim_end()+ .lines()+ .map(str::trim_end)+ .collect::<Vec<_>>()+ .join("\n")+}+#[cfg(test)]mod tests {use super::*;use clap::CommandFactory;+ #[cfg(feature = "editor")]+ #[test]+ fn the_command_reference_is_current() {+ let text = std::thread::Builder::new()+ .stack_size(64 << 20)+ .spawn(reference)+ .unwrap()+ .join()+ .unwrap();+ let written = include_str!("../../../docs/cli.md").replace("\r\n", "\n");+ assert!(text == written, "docs/cli.md is out of date: just reference");+ }+#[test]fn every_command_parses_its_flags() {std::thread::Builder::new()diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex c8cff95..f06b917 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -69,3 +69,41 @@ fn an_error_is_one_line_and_the_backtrace_waits_for_klad_backtrace() {let traced = run(Some("1"));assert!(traced.contains("Caused by") && traced.contains("backtrace"), "{traced}");}++#[test]+fn the_client_makes_edits_reads_and_renders_a_drawing() {+ use klad_client::{Error, Klad, json};+ let dir = std::env::temp_dir().join(format!("draw-binary-client-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let klad = Klad::at(env!("CARGO_BIN_EXE_klad"));+ assert!(klad.version().unwrap().starts_with("klad"));+ let art = klad.drawing(dir.join("art.draw"));+ art.create(320, 200, Some("#e9e4da")).unwrap();+ let ids = art+ .apply([+ json!({"op": "add", "layer": {"kind": "vector", "name": "sky"}}),+ json!({"op": "stroke", "layer": "l1", "brush": "ink", "size": 6, "color": "#1b1b1b", "path": "M20 100 L300 100"}),+ ])+ .unwrap();+ assert!(!ids.is_empty());+ let layer = art.document().unwrap()["layers"]+ .as_array()+ .unwrap()+ .iter()+ .find(|l| l["name"] == "sky")+ .map(|l| l["id"].as_str().unwrap().to_string())+ .unwrap();+ art.apply([json!({"op": "add", "node": {"type": "rect", "x": 10, "y": 10, "w": 50, "h": 30, "fill": "#336699"}, "in": layer, "frame": 0})])+ .unwrap();+ assert!(art.ls(0).unwrap().to_string().contains("sky"));+ let strokes = art.strokes("l1", 0).unwrap();+ assert!(strokes.to_string().contains("ink"));+ let png = art.render(&dir.join("art.png"), 0, 0.5).unwrap();+ assert!(std::fs::metadata(png).unwrap().len() > 0);+ art.undo().unwrap();+ assert!(!art.document().unwrap().to_string().contains("#336699"));+ let missing = art.show("n999").unwrap_err();+ assert!(matches!(missing, Error::Failed { .. }), "{missing}");+ std::fs::remove_dir_all(&dir).unwrap();+}diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.tomlnew file mode 100644index 0000000..93461cf--- /dev/null+++ b/crates/client/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "klad-client"+version = "0.1.0"+edition.workspace = true+license = "MIT"+publish = false+repository.workspace = true+description = "Drive klad, the 2D art app you share with an AI agent: run its commands, edit drawings with JSON ops, read them back"+keywords = ["klad", "drawing", "painting", "agent", "gamedev"]+categories = ["graphics", "api-bindings"]+readme = "README.md"++[dependencies]+serde_json = "1.0.154"diff --git a/crates/client/LICENSE b/crates/client/LICENSEnew file mode 100644index 0000000..e992e2e--- /dev/null+++ b/crates/client/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Indicode BV++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/client/README.md b/crates/client/README.mdnew file mode 100644index 0000000..bbc0522--- /dev/null+++ b/crates/client/README.md@@ -0,0 +1,34 @@+# klad-client++Drive [klad](https://github.com/klad-app/klad), the 2D art app you share with an AI agent, from Rust. It runs the `klad` command line: create drawings, edit them with JSON ops (one transaction per call, undoable in the editor), read them back as JSON and render them to PNG. Someone with the drawing open in the klad editor sees every change within a second.++It needs `klad` on the path (or its path in `KLAD`, or `Klad::at`). The ops are the ones `klad apply` takes, described in the [command reference](https://github.com/klad-app/klad/blob/main/docs/cli.md); the drawing itself is described in the [file format](https://github.com/klad-app/klad/blob/main/docs/format.md).++```rust,no_run+use klad_client::{Klad, json};+use std::path::Path;++fn main() -> klad_client::Result<()> {+ let klad = Klad::new();+ let art = klad.drawing("art.draw");+ art.create(800, 600, Some("#e9e4da"))?;+ let ids = art.apply([+ json!({"op": "add", "layer": {"kind": "vector", "name": "sky"}}),+ json!({"op": "stroke", "layer": "l1", "brush": "ink", "size": 8, "color": "#1b1b1b",+ "path": "M100 400 C 300 200 500 600 700 400", "pressure": [0.1, 1, 0.05]}),+ ])?;+ println!("added {ids:?}");+ let tree = art.ls(0)?;+ println!("{}", tree);+ art.render(Path::new("art.png"), 0, 0.5)?;+ let notes = art.notes()?;+ println!("{notes}");+ Ok(())+}+```++Any other command runs through `Drawing::command` (text) or `Drawing::json` (for commands with `--json`), and `Klad::run` for those that take no drawing.++## Licence++MIT, copyright Indicode BV (`LICENSE`). klad itself is source-available under its own licence; this crate, the file format and the command reference are MIT so that any program or agent can work with klad drawings.diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rsnew file mode 100644index 0000000..22c8817--- /dev/null+++ b/crates/client/src/lib.rs@@ -0,0 +1,291 @@+#![doc = include_str!("../README.md")]++pub use serde_json::{self, Value, json};+use std::ffi::{OsStr, OsString};+use std::fmt;+use std::io::Write;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++#[derive(Debug)]+pub enum Error {+ Io {+ command: String,+ source: std::io::Error,+ },+ Failed {+ command: String,+ status: Option<i32>,+ stderr: String,+ },+ Json {+ command: String,+ source: serde_json::Error,+ },+}++impl fmt::Display for Error {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Error::Io { command, source } => write!(f, "{command}: {source}"),+ Error::Failed { command, stderr, .. } => write!(f, "{command}: {}", stderr.trim()),+ Error::Json { command, source } => write!(f, "{command} printed JSON that does not parse: {source}"),+ }+ }+}++impl std::error::Error for Error {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ match self {+ Error::Io { source, .. } => Some(source),+ Error::Json { source, .. } => Some(source),+ Error::Failed { .. } => None,+ }+ }+}++pub type Result<T> = std::result::Result<T, Error>;++const NONE: [&str; 0] = [];++#[derive(Clone, Debug)]+pub struct Klad {+ program: PathBuf,+}++impl Default for Klad {+ fn default() -> Self {+ Self::new()+ }+}++impl Klad {+ pub fn new() -> Self {+ Self::at(std::env::var_os("KLAD").map_or_else(|| PathBuf::from("klad"), PathBuf::from))+ }++ pub fn at(program: impl Into<PathBuf>) -> Self {+ Self {+ program: program.into(),+ }+ }++ pub fn program(&self) -> &Path {+ &self.program+ }++ pub fn version(&self) -> Result<String> {+ Ok(self.run(["--version"])?.trim().to_string())+ }++ pub fn run<I, S>(&self, args: I) -> Result<String>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ self.exec(args, None)+ }++ pub fn json<I, S>(&self, args: I) -> Result<Value>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ let args = owned(args);+ let text = self.exec(&args, None)?;+ serde_json::from_str(&text).map_err(|source| Error::Json {+ command: self.describe(&args),+ source,+ })+ }++ pub fn drawing(&self, path: impl Into<PathBuf>) -> Drawing {+ Drawing {+ klad: self.clone(),+ path: path.into(),+ }+ }++ fn exec<I, S>(&self, args: I, input: Option<&[u8]>) -> Result<String>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ let args = owned(args);+ let command = self.describe(&args);+ let io = |source| Error::Io {+ command: command.clone(),+ source,+ };+ let mut child = Command::new(&self.program)+ .args(&args)+ .stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() })+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(io)?;+ let stdin = child.stdin.take();+ let (out, written) = std::thread::scope(|scope| {+ let writer = scope.spawn(move || match (stdin, input) {+ (Some(mut pipe), Some(bytes)) => pipe.write_all(bytes),+ _ => Ok(()),+ });+ (child.wait_with_output(), writer.join().unwrap_or(Ok(())))+ });+ let out = out.map_err(io)?;+ if !out.status.success() {+ return Err(Error::Failed {+ command,+ status: out.status.code(),+ stderr: String::from_utf8_lossy(&out.stderr).into_owned(),+ });+ }+ written.map_err(io)?;+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+ }++ fn describe(&self, args: &[OsString]) -> String {+ std::iter::once(self.program.as_os_str())+ .chain(args.iter().map(OsString::as_os_str))+ .map(OsStr::to_string_lossy)+ .collect::<Vec<_>>()+ .join(" ")+ }+}++#[derive(Clone, Debug)]+pub struct Drawing {+ klad: Klad,+ path: PathBuf,+}++impl Drawing {+ pub fn path(&self) -> &Path {+ &self.path+ }++ pub fn create(&self, width: u32, height: u32, background: Option<&str>) -> Result<String> {+ let (width, height) = (width.to_string(), height.to_string());+ let mut args = vec!["--width", &width, "--height", &height];+ args.extend(background.map(|b| ["--background", b]).into_iter().flatten());+ self.command("new", args)+ }++ pub fn command<I, S>(&self, name: &str, args: I) -> Result<String>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ self.klad.run(self.args(name, args))+ }++ pub fn json<I, S>(&self, name: &str, args: I) -> Result<Value>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ self.klad.json(self.args(name, args))+ }++ pub fn apply<I>(&self, ops: I) -> Result<Vec<String>>+ where+ I: IntoIterator<Item = Value>,+ {+ let lines: String = ops.into_iter().map(|op| format!("{op}\n")).collect();+ let out = self.klad.exec(self.args("apply", NONE), Some(lines.as_bytes()))?;+ Ok(out.lines().map(str::to_string).collect())+ }++ pub fn document(&self) -> Result<Value> {+ let command = format!("reading {}", self.path.join("doc.json").display());+ let bytes = std::fs::read(self.path.join("doc.json")).map_err(|source| Error::Io {+ command: command.clone(),+ source,+ })?;+ serde_json::from_slice(&bytes).map_err(|source| Error::Json { command, source })+ }++ pub fn ls(&self, frame: u32) -> Result<Value> {+ self.json("ls", ["--json", "--frame", &frame.to_string()])+ }++ pub fn show(&self, id: &str) -> Result<Value> {+ self.json("show", [id])+ }++ pub fn strokes(&self, layer: &str, frame: u32) -> Result<Value> {+ self.json("strokes", [layer, "--json", "--frame", &frame.to_string()])+ }++ pub fn notes(&self) -> Result<Value> {+ self.json("notes", ["--json"])+ }++ pub fn selection(&self) -> Result<Value> {+ self.json("selection", ["--json"])+ }++ pub fn render(&self, out: &Path, frame: u32, scale: f32) -> Result<PathBuf> {+ let args = [+ OsString::from("--frame"),+ frame.to_string().into(),+ "--scale".into(),+ scale.to_string().into(),+ "--out".into(),+ out.as_os_str().to_os_string(),+ ];+ self.command("render", args)?;+ Ok(out.to_path_buf())+ }++ pub fn undo(&self) -> Result<String> {+ self.command("undo", NONE)+ }++ pub fn redo(&self) -> Result<String> {+ self.command("redo", NONE)+ }++ fn args<I, S>(&self, name: &str, args: I) -> Vec<OsString>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+ {+ [OsString::from(name), self.path.as_os_str().to_os_string()]+ .into_iter()+ .chain(owned(args))+ .collect()+ }+}++fn owned<I, S>(args: I) -> Vec<OsString>+where+ I: IntoIterator<Item = S>,+ S: AsRef<OsStr>,+{+ args.into_iter().map(|a| a.as_ref().to_os_string()).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_missing_program_is_an_io_error_naming_the_command() {+ let klad = Klad::at("/no/such/klad");+ let error = klad.drawing("a.draw").ls(0).unwrap_err();+ assert!(matches!(error, Error::Io { .. }));+ assert!(+ error+ .to_string()+ .starts_with("/no/such/klad ls a.draw --json --frame 0")+ );+ }++ #[test]+ fn klad_on_the_path_unless_the_environment_names_one() {+ let expected = std::env::var_os("KLAD").map_or_else(|| PathBuf::from("klad"), PathBuf::from);+ assert_eq!(Klad::new().program(), expected);+ assert_eq!(Klad::at("/opt/klad/klad").program(), Path::new("/opt/klad/klad"));+ }+}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 5ec6562..ead1f92 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-05 22:26_+_Last updated: 2026-11-06 11:54_# klad: design@@ -29,7 +29,7 @@ crates/Two binaries from one crate: `klad`, the command line, and `klad-editor`, the editor alone (a windowed program on Windows, the executable of `klad.app` on a Mac, started by the Linux AppImage). `klad open [bundle]` launches the same editor from the command line, on the bundle or, without one, on the start window (new, open, recent). `--no-default-features` builds `klad` without the editor. `klad --version` and the editor's About show the version and `git describe` of the commit it was built from (`crates/version.rs`, shared by both crates' build scripts; `KLAD_BUILD` overrides it).-**Platforms and packaging (M7).** Folders follow each platform: settings in `~/Library/Application Support/klad`, `%APPDATA%\klad` or `$XDG_CONFIG_HOME/klad`; downloaded fonts in the same places' data folder; drawings in `~/Drawings` by default. The open panel is `NSOpenPanel` on macOS and `rfd` elsewhere (the XDG portal on Linux, the common dialog on Windows). The pen: macOS reads `NSEvent`; elsewhere a pen that the system reports as a touch with force (Windows pens through `WM_POINTER`) draws with that pressure (`pen::from_egui`), and anything else draws as a mouse at full pressure; Linux tablets report no pressure through `winit` yet. `packaging/` makes the downloads: `macos/app.sh` builds `klad.app` (both binaries, lipo'd when several targets are given, the fonts, licences and skill in `Resources`, `.draw` declared as a document package of type `com.indicode.klad.drawing` so Finder shows a drawing as one item and opens it in klad) and a disk image; `archive.sh <target>` builds a `tar.gz` or `zip` with both binaries, `fonts/`, the licences and `SKILL.md`, and an AppImage on Linux when `APPIMAGETOOL` is set; `icon/` draws the icon in klad and packs `klad.icns` and `klad.ico`. Builds use the `dist` profile (no debug info, stripped, thin LTO); the samples hash the same from it. The fonts are found next to the binary (`fonts/`), in `../Resources/fonts` or `../share/klad/fonts`. On macOS a drawing opened from Finder arrives as an `application:openURLs:` message, which klad adds to `NSObject` before the event loop starts so it reaches whatever delegate `winit` installs; the paths queue up (`opened.rs`) and the start window or editor opens the last. `klad install` puts `klad` on the terminal's path (a link in `/usr/local/bin` through an administrator prompt on macOS, `~/.local/bin` on Linux, the user's `PATH` on Windows); the editor's document menu runs it as a job. `klad skill` prints the agent skill compiled into the binary. The `release` workflow (`.github/workflows`) builds all of it on a version tag and publishes it with checksums; `check` runs lint, tests and the audit on every pull request, tests on macOS and builds on Windows. The editor asks the GitHub releases API at most once a day (`updates.rs`, curl on a thread, off in the settings window) and, when a newer version is out, says so in the start window, the message line and About, with a link to what changed; it installs nothing.+**Platforms and packaging (M7).** Folders follow each platform: settings in `~/Library/Application Support/klad`, `%APPDATA%\klad` or `$XDG_CONFIG_HOME/klad`; downloaded fonts in the same places' data folder; drawings in `~/Drawings` by default. The open panel is `NSOpenPanel` on macOS and `rfd` elsewhere (the XDG portal on Linux, the common dialog on Windows). The pen: macOS reads `NSEvent`; elsewhere a pen that the system reports as a touch with force (Windows pens through `WM_POINTER`) draws with that pressure (`pen::from_egui`), and anything else draws as a mouse at full pressure; Linux tablets report no pressure through `winit` yet. `packaging/` makes the downloads: `macos/app.sh` builds `klad.app` (both binaries, lipo'd when several targets are given, the fonts, licences and skill in `Resources`, `.draw` declared as a document package of type `com.indicode.klad.drawing` so Finder shows a drawing as one item and opens it in klad) and a disk image; `archive.sh <target>` builds a `tar.gz` or `zip` with both binaries, `fonts/`, the licences and `SKILL.md`, and an AppImage on Linux when `APPIMAGETOOL` is set; `icon/` draws the icon in klad and packs `klad.icns` and `klad.ico`. Builds use the `dist` profile (no debug info, stripped, thin LTO); the samples hash the same from it. The fonts are found next to the binary (`fonts/`), in `../Resources/fonts` or `../share/klad/fonts`. On macOS a drawing opened from Finder arrives as an `application:openURLs:` message, which klad adds to `NSObject` before the event loop starts so it reaches whatever delegate `winit` installs; the paths queue up (`opened.rs`) and the start window or editor opens the last. `klad install` puts `klad` on the terminal's path (a link in `/usr/local/bin` through an administrator prompt on macOS, `~/.local/bin` on Linux, the user's `PATH` on Windows); the editor's document menu runs it as a job. `klad skill` prints the agent skill compiled into the binary. Builds are sold on itch.io (later Steam) for macOS and Windows, and Linux is built from source: on a version tag the `release` workflow builds the Windows version and pushes it to itch.io with butler (never as a workflow artifact, which anyone could download from a public repository) and publishes the changelog section as the release notes, and `just itch-mac` builds and pushes the Mac app from a Mac; `check` runs lint, tests and the audit on every pull request, tests on macOS and builds on Windows. The editor asks the GitHub releases API at most once a day (`updates.rs`, curl on a thread, off in the settings window) and, when a newer version is out, says so in the start window, the message line and About, with a link to what changed; it installs nothing.### Stack@@ -44,7 +44,7 @@ Two binaries from one crate: `klad`, the command line, and `klad-editor`, the ed| File dialogs (Windows, Linux) | `rfd` | The platform's own dialog (the XDG portal on Linux); macOS keeps `NSOpenPanel` || 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.+klad is source-available, not open source, copyright Indicode BV: the app is under the PolyForm Internal Use License 1.0.0 with a personal-use permission and one for drawings (`LICENSE`); the file format (`docs/format.md`), the command reference (`docs/cli.md`, written by `klad reference`), the agent skill and the `klad-client` crate (`crates/client`, which runs the CLI and depends on no other klad crate) are MIT (`LICENSE-MIT`), so any program or agent can work with klad drawings. Contributions come in under a CLA (`CLA.md`, signed through the CLA assistant). 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@@ -87,6 +87,8 @@ The CLI render and the editor must agree. Rules for `core`, `brush` and `render`## The document bundle+`docs/format.md` specifies everything below for other programs, byte by byte; this section is how klad itself uses it.+```art.draw/doc.json canonical document (pretty JSON, stable key order)@@ -362,6 +364,8 @@ A brush is JSON. The library is built in (`crates/core/brushes/library/`: `ink`Stateless: read the bundle, apply, write atomically, optionally render. Output is short text by default, `--json` for structure.+Every command with its options is in `docs/cli.md`, which `klad reference` (hidden) writes and a test keeps current. `klad-client` (`crates/client`) runs the commands from Rust: `Klad` finds the binary (`KLAD` or the path), `Drawing` applies op lines through `klad apply` and reads `ls`, `show`, `strokes`, `notes` and `selection` as JSON.+An error is one line on stderr (`error: reading a.draw/doc.json: No such file or directory`) and exit code 1, whatever `RUST_BACKTRACE` says; a bug (a panic) is one line too, with where it happened and where to report it. `KLAD_BACKTRACE=1` prints the whole chain and the backtrace instead.| Command | Purpose |diff --git a/docs/cli.md b/docs/cli.mdnew file mode 100644index 0000000..6e4fbb1--- /dev/null+++ b/docs/cli.md@@ -0,0 +1,3331 @@+_Last updated: with the commands it lists. `just reference` writes it from `klad reference`; `cargo test -p klad-cli` fails when it is out of date._++# klad command reference++Every command of the `klad` command line with its options, as `klad <command> --help` prints them. A drawing is a `.draw` folder (`docs/format.md`); `klad apply` takes the same edits as JSON lines, one transaction per call. `docs/skill/SKILL.md` explains how an agent uses them, and the `klad-client` crate (`crates/client`) runs them from Rust.++This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad itself.++## Commands++- [`klad new`](#klad-new): Create an empty bundle with paint layers+- [`klad frames`](#klad-frames): Exposure sheet: a row per frame, a column per layer (top first)+- [`klad frame`](#klad-frame): Insert or remove frames in every layer or the listed ones+- [`klad arcs`](#klad-arcs): Track marks, parts or points across frames: positions, spacing, ground contacts, feet crossing+- [`klad part`](#klad-part): Name a group of marks in a drawing (a part), so in-betweens pair them whatever their ids+- [`klad duplicate`](#klad-duplicate): Duplicate a layer with its drawings, links and mask, above it+- [`klad cel`](#klad-cel): Make drawings on the timeline: new, dup, link, unlink, move+- [`klad copy`](#klad-copy): Copy strokes and fills into another drawing, with new ids, moving them on the way+- [`klad retime`](#klad-retime): Retime a range of frames: on ones/twos/threes, fit into n frames, reverse, ping-pong+- [`klad inbetween`](#klad-inbetween): Make the drawings between two keys: a new cel on each frame between them+- [`klad font`](#klad-font): Copy a font into the bundle for text nodes, by name or from a file, or list the fonts it has+- [`klad fonts`](#klad-fonts): List the fonts that come with klad, search the open fonts it can download, or download one+- [`klad atmosphere`](#klad-atmosphere): Fog and haze by depth: show, set or turn off the document's atmosphere+- [`klad timeline`](#klad-timeline): Show the timeline (fps, length, origin, clips) or set fps, length and origin+- [`klad clip`](#klad-clip): List, add, change, rename and remove clips (named frame ranges)+- [`klad ls`](#klad-ls): Layer tree with ids, kinds, contents and bounds at a frame, top layer first+- [`klad show`](#klad-show): One layer, cel, node, stroke or fill (<cel>:s<id>) in full (JSON)+- [`klad add`](#klad-add): Add a layer, cel or shape+- [`klad set`](#klad-set): Change properties: klad set art.draw n4 fill=#ff0000 transform.rotate=15 (null removes)+- [`klad rm`](#klad-rm): Remove layers, cels or nodes+- [`klad transform`](#klad-transform): Move, rotate or scale strokes and fills (<cel>:s<id>)+- [`klad lasso`](#klad-lasso): Lasso strokes and fills on a paint layer; --cut also takes the parts crossing the edge+- [`klad path`](#klad-path): List the points of a path, rect or ellipse, or edit them+- [`klad mv`](#klad-mv): Move a layer or node: --above, --below, --in, --index+- [`klad apply`](#klad-apply): Apply many edits from JSON lines (stdin or --file) in one write+- [`klad render`](#klad-render): Render a frame to PNG and print the path+- [`klad stroke`](#klad-stroke): Paint a stroke with a brush along an SVG path or explicit points+- [`klad fill`](#klad-fill): Fill a region of a paint layer, inside the lines (flood) or inside a polygon (lasso)+- [`klad ink`](#klad-ink): Ink the outlines of vector shapes as tapered strokes, the way an inker would+- [`klad light`](#klad-light): Shade and rim light vector shapes from one light direction+- [`klad hatch`](#klad-hatch): Fill a shape's area with short tapered strokes: hatching, bark, fur, stone grain+- [`klad paint`](#klad-paint): Paint a shape as a form, with strokes that follow it and colours from a light model+- [`klad prepare`](#klad-prepare): Buffer the drawings of a span of frames, as the editor's prepare does+- [`klad scatter`](#klad-scatter): Scatter copies of a small mark over a shape: grass, cracks, dots+- [`klad foliage`](#klad-foliage): Paint closed shapes as clumps of leaves, lit as forms+- [`klad bone`](#klad-bone): Add, remove, rename, move or reparent a bone of a layer's or group's skeleton+- [`klad bones`](#klad-bones): List the skeletons, their bones and weights, and the posed drawings+- [`klad weights`](#klad-weights): Set how much each bone moves each part of the drawing: automatic, painted dabs, a whole part, smoothed+- [`klad pose`](#klad-pose): Pose a drawing with its bones: a new drawing at --to, bent from the rest drawing at --from+- [`klad key`](#klad-key): Key a layer, group or shape: its position, turn, scale or opacity at a frame, eased to the next key+- [`klad keys`](#klad-keys): List the keys of every keyed layer, group and shape (or one)+- [`klad compare`](#klad-compare): Measure a drawing against a reference picture: values, saturation, texture, edges, colour per region+- [`klad paintover`](#klad-paintover): Paint over a picture with brushwork: strokes that follow its forms and stop at its colour edges, big to small+- [`klad grass`](#klad-grass): Grow grass in closed shapes: blades lit by the ground, smaller with distance, breaking the top edge+- [`klad gaps`](#klad-gaps): List closed regions of the lines that no fill on the layer covers+- [`klad refill`](#klad-refill): Recompute the flood fills of a paint cel after the lines they were made from changed+- [`klad palette`](#klad-palette): The document palette: list, --add a colour (with --name), --rm a name, colour or index+- [`klad export`](#klad-export): Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene+- [`klad brushes`](#klad-brushes): List brushes: the library, and with a bundle the ones it embeds+- [`klad effect`](#klad-effect): List, add or remove a layer's effects: klad effect art.draw l3 glow radius=24 color=#ffd080+- [`klad reshape`](#klad-reshape): Bend a brush stroke along a new path; it keeps its pressure, tilt and timing (klad strokes --json gives each stroke's fitted path)+- [`klad undo`](#klad-undo): Undo the last change (from the CLI or the editor)+- [`klad redo`](#klad-redo): Redo the last undone change+- [`klad log`](#klad-log): Recent changes, newest first+- [`klad selection`](#klad-selection): What the human has selected in the editor (layer and shapes, with bounds)+- [`klad notes`](#klad-notes): Notes the human pinned on the canvas; --done <id> marks one as handled+- [`klad diff`](#klad-diff): Before and after renders of a change, side by side (default: the last one)+- [`klad info`](#klad-info): Paint cels with stroke counts and file sizes+- [`klad strokes`](#klad-strokes): List the strokes and fills of a paint layer's cel at a frame+- [`klad hash`](#klad-hash): Print pixel hashes, for comparing macOS and Linux renders+- [`klad demo`](#klad-demo): Write a sample bundle (vector sky and hills, painted glow, clouds, hatching, grass)+- [`klad stress`](#klad-stress): Create a large bundle of synthetic paint layers for editor performance tests+- [`klad scribble`](#klad-scribble): Append synthetic ink strokes to a paint layer (sync test)+- [`klad watch`](#klad-watch): Print editor saves as they arrive, with how long they took to show up here+- [`klad licences`](#klad-licences): Print the licence and the third-party notices (every open source part klad is built on)+- [`klad install`](#klad-install): Put klad on the terminal's path, for you and for agents+- [`klad skill`](#klad-skill): Print the agent skill: how an agent draws with klad (the same text as docs/skill/SKILL.md)+- [`klad bench`](#klad-bench): Measure stroke storage, brush speed, replay, cache and compositing+- [`klad open`](#klad-open): Open the editor, on a bundle or on the start window (new, open, recent)++## klad new++```text+Create an empty bundle with paint layers++Usage: klad new [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --width <WIDTH>+ [default: 2048]++ --height <HEIGHT>+ [default: 2048]++ --layers <LAYERS>+ [default: 1]++ --background <BACKGROUND>+ Background colour, for example #ffffff++ --fps <FPS>+ [default: 12]++ --frames <FRAMES>+ [default: 1]++ --sketch+ Add a vector layer named sketch on top, for blocking in shapes++ -h, --help+ Print help+```++## klad frames++```text+Exposure sheet: a row per frame, a column per layer (top first).++A 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).++Usage: klad frames [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --from <FROM>+++ --to <TO>+++ --json+++ -h, --help+ Print help (see a summary with '-h')+```++## klad frame++```text+Insert or remove frames in every layer or the listed ones.++ klad frame art.draw insert 4 --count 2+ klad frame art.draw remove 4 --layers l3,l5++Insert: 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).++Usage: klad frame [OPTIONS] <BUNDLE> <ACTION> <AT>++Arguments:+ <BUNDLE>+++ <ACTION>+ [possible values: insert, remove]++ <AT>+++Options:+ --count <COUNT>+ [default: 1]++ --layers <LAYERS>+ Layer ids or names (default: every layer)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad arcs++```text+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.++ klad arcs walk.draw --track 'near foot' --track 'far foot' --clip walk --ground 610,598 --travel 7 --check+ klad arcs walk.draw --track c12:s4 --from 12 --to 27 --json++Usage: klad arcs [OPTIONS] --track <TRACK> <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --track <TRACK>+++ --clip <CLIP>+ The frames of this clip++ --from <FROM>+++ --to <TO>+++ --ground <GROUND>+ The ground line's y, one for every track or one per track: report feet under it or sliding on it++ --travel <TRAVEL>+ 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++ [default: 0]++ --slack <SLACK>+ How many px off still counts as on the ground and not sliding++ [default: 2]++ --json+++ --check+ Exit with an error when a track goes under the ground, slides, or two tracks swap sides++ -h, --help+ Print help (see a summary with '-h')+```++## klad part++```text+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.++ klad part art.draw c4:s14 c4:s15 --name leaf+ klad part art.draw c9:s17 c9:s18 --name leaf+ klad stroke art.draw lines --path "M..." --part leaf++Also an op: {"op":"part","ids":["c4:s14","c4:s15"],"name":"leaf"}. klad strokes lists each mark's part.++Usage: klad part [OPTIONS] --name <NAME> <BUNDLE> [IDS]...++Arguments:+ <BUNDLE>+++ [IDS]...+++Options:+ --name <NAME>+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad duplicate++```text+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.++ klad duplicate art.draw l3++Also an op in klad apply: {"op":"duplicate","layer":"l3"}.++Usage: klad duplicate [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad cel++```text+Make drawings on the timeline.++ klad cel art.draw new l3 --frame 4 a blank drawing on layer l3 at frame 4+ klad cel art.draw dup c4 [--frame 6] a copy of c4's drawing (default: right after c4's exposure)+ klad cel art.draw link c4 --frame 8 show c4's drawing again at frame 8+ klad cel art.draw unlink c9 turn the link c9 into a drawing of its own+ klad cel art.draw move c5 --frame 12 start c5 at frame 12, keeping its hold; drawings in the way are pushed along++Inside 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.++Usage: klad cel [OPTIONS] <BUNDLE> <ACTION> <TARGET>++Arguments:+ <BUNDLE>+++ <ACTION>+ [possible values: new, dup, link, unlink, move]++ <TARGET>+ new: the layer; dup, link, unlink, move: the cel++Options:+ --frame <FRAME>+++ --hold <HOLD>+++ --insert+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad copy++```text+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.++ klad copy art.draw c1:s3 c1:s4 --frame 4+ klad copy art.draw c1:s3 --to c9 --move 12,-4 --rotate 8+ klad copy art.draw c1:s3 --frame 6 --layer shade --flip h --pivot 512,400++Also a copy op in klad apply: {"op":"copy","ids":["c1:s3"],"frame":4,"x":12,"y":-4} (or "to":"c9").++Usage: klad copy [OPTIONS] <BUNDLE> [IDS]...++Arguments:+ <BUNDLE>+++ [IDS]...+++Options:+ --to <TO>+ The drawing (cel id) the copies go into++ --frame <FRAME>+ The drawing shown at this frame (a new drawing on an empty frame)++ --layer <LAYER>+ With --frame: the layer (default: the marks' own)++ --move <OFFSET>+ dx,dy in px++ --rotate <ROTATE>+ Degrees, clockwise++ --scale <SCALE>+ Uniform scale++ --sx <SX>+++ --sy <SY>+++ --pivot <PIVOT>+ x,y to turn, scale and flip about++ --flip <FLIP>+ Mirror: h (left-right) or v (up-down)++ [possible values: h, v]++ --cut <CUT>+ Keep only the parts inside this polygon: x,y pairs separated by spaces++ --render+ Render a preview after the edit and print its path (longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad retime++```text+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.++ klad retime art.draw 0-11 --on 2 every picture shows for 2 frames (ones to twos)+ klad retime art.draw 0-23 --on 1 and back to ones+ klad retime art.draw 0-11 --fit 16 the range becomes 16 frames; order and relative timing kept, at least one frame each+ klad retime art.draw 0-7 --reverse+ klad retime art.draw 0-7 --pingpong the pictures again backwards as links, the ends not repeated: a b c d c b++Later 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).++Usage: klad retime [OPTIONS] <BUNDLE> <RANGE>++Arguments:+ <BUNDLE>+++ <RANGE>+ FROM-TO, both included++Options:+ --on <ON>+ Frames per picture: 1, 2, 3 ...++ --fit <FIT>+ The range becomes this many frames++ --reverse+++ --pingpong+++ --layers <LAYERS>+ Layer ids or names (default: every layer)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad inbetween++```text+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.++ klad inbetween art.draw --layers lines,colour --from 0 --to 6+ klad inbetween art.draw --layers lines --from 0 --to 8 --count 3 --spacing in-out+ klad inbetween art.draw --layers arm --from 4 --to 10 --match near --pair s3=s7+ klad inbetween art.draw --redo after a key changed++Strokes 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, taper and colour move at the spacing (colour evenly in OKLab, so colour the second key for its light and the in-betweens carry the change), 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.++Spacing: 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.++Usage: klad inbetween [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --layers <LAYERS>+ Paint layers (ids or names; a group means its paint layers)++ --from <FROM>+ The frame of the first key++ --to <TO>+ The frame where the second key starts++ --count <COUNT>+ How many in-betweens (default: one per frame between the keys)++ --spacing <SPACING>+ even, in, out, in-out, or positions like 0.25,0.5,0.9++ [default: even]++ --match <MATCHING>+ Pair strokes by id, order or near (nearest shape)++ [default: id]++ --pair <PAIR>+ Force pairs: s3=s7 (first key's s3 with the second key's s7)++ --redo+ Remake the in-betweens (of --layers, between --from and --to when given)++ --force+ Replace drawings between the keys, or redo in-betweens changed since they were made++ --loop+ The second key is the loop's first drawing (the clip holding --from, else frame 0); --to defaults to the loop's end++ --keep-drawn+ With --redo: remake the agent's marks and keep the marks drawn by hand on top, carried with the lines under them++ --unpaired <UNPAIRED>+ Marks in one key only: leave them out (listed), pop at --at, fade, or draw on along their length++ [default: leave]+ [possible values: leave, pop, fade, draw-on]++ --at <AT>+ With --unpaired pop: when it pops, 0 to 1 (default 0.5)++ --only <ONLY>+ With --redo: only these in-betweens (cel ids)++ --keep-cels <KEEP_CELS>+ With --redo: these in-betweens keep their hand-drawn marks on top++ --force-cels <FORCE_CELS>+ With --redo: these in-betweens are remade with their hand-drawn marks++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad font++```text+Copy one of klad's fonts (by family, or family and style) or a font file (TTF or OTF) into the bundle's fonts folder, so text nodes render the same on every machine; a family that klad does not have yet but Google Fonts does is downloaded first. With no font, list the bundle's fonts. Text nodes also take a family name directly (font=Inter, font="Inter Bold") and copy it in themselves.++ klad font art.draw Cinzel+ klad font art.draw "Barlow Bold"+ klad font art.draw ~/fonts/Signage.ttf+ klad add art.draw text --in l4 text=INN font=Cinzel size=48 x=120 y=80 fill=#2b1d12++Usage: klad font <BUNDLE> [FONT]++Arguments:+ <BUNDLE>+++ [FONT]+++Options:+ -h, --help+ Print help (see a summary with '-h')+```++## klad fonts++```text+List the font families that come with klad and the ones downloaded before, by group (sans, serif, mono, display, handwriting, pixel), with their licence and styles; with a bundle, also the fonts it holds. --search looks through every open family on Google Fonts (about 1,900) and --get downloads one into the per-user fonts folder, after which it works like the ones klad ships.++ klad fonts+ klad fonts --group pixel+ klad fonts --search "slab"+ klad fonts --get Lobster++Usage: klad fonts [OPTIONS] [BUNDLE]++Arguments:+ [BUNDLE]+++Options:+ --group <GROUP>+ Only this group: sans, serif, mono, display, handwriting or pixel++ --search <SEARCH>+ Search the open fonts that can be downloaded, by words of the family name or the group++ --get <GET>+ Download this family from Google Fonts into the per-user fonts folder++ --json+ Print JSON++ -h, --help+ Print help (see a summary with '-h')+```++## klad atmosphere++```text+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.++ klad atmosphere art.draw+ klad atmosphere art.draw color=#9aa8b8 top=#d8e0e8 density=0.5 blur=1 desaturate=0.15+ klad atmosphere art.draw --off++Usage: klad atmosphere [OPTIONS] <BUNDLE> [PROPS]...++Arguments:+ <BUNDLE>+++ [PROPS]...+++Options:+ --off+ Remove the atmosphere++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad timeline++```text+Show the timeline (fps, length, origin, clips) or set fps, length and origin.++ klad timeline art.draw+ klad timeline art.draw --fps 12 --frames 24+ klad timeline art.draw --origin 512,700 the canvas point a Godot export puts on the node's position+ klad timeline art.draw --origin centre back to the middle of the canvas (the default)++Usage: klad timeline [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --fps <FPS>+++ --frames <FRAMES>+++ --origin <ORIGIN>+ x,y on the canvas, or centre++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad clip++```text+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.++ klad clip art.draw list them+ klad clip art.draw --add run --from 0 --to 11 --loop --fps 12+ klad clip art.draw --set run --to 15 --no-loop+ klad clip art.draw --set run --name sprint rename+ klad clip art.draw --set run --fps doc use the document's fps again+ klad clip art.draw --rm run++Frames inserted or removed on every layer move and stretch clips; a clip ends where the timeline ends.++Usage: klad clip [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --add <ADD>+ Add a clip with this name++ --set <SET>+ Change the clip with this name++ --rm <RM>+ Remove the clip with this name++ --name <NAME>+ With --set: the clip's new name++ --from <FROM>+ First frame++ --to <TO>+ Last frame (included)++ --loop+ The clip loops++ --no-loop+ The clip plays once++ --fps <FPS>+ The clip's own fps, or doc for the document's++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad ls++```text+Layer tree with ids, kinds, contents and bounds at a frame, top layer first++Usage: klad ls [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --frame <FRAME>+ [default: 0]++ --json+++ -h, --help+ Print help+```++## klad show++```text+One layer, cel, node, stroke or fill (<cel>:s<id>) in full (JSON)++Usage: klad show <BUNDLE> <ID>++Arguments:+ <BUNDLE>+++ <ID>+++Options:+ -h, --help+ Print help+```++## klad add++```text+Add a layer, cel or shape.++ klad add art.draw layer vector name=sky+ klad add art.draw rect --in l2 x=0 y=0 w=2048 h=900 fill=#1b2a41+ 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"]]}}'+ klad add art.draw cel --in l3 frame=4 hold=2++Values are JSON when they parse as JSON, otherwise strings. Dotted keys nest: transform.rotate=15, stroke.width=3.++Usage: klad add [OPTIONS] <BUNDLE> <WHAT> [REST]...++Arguments:+ <BUNDLE>+++ <WHAT>+ layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text++ [REST]...+ 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++Options:+ --in <INTO>+ Container: group layer, vector layer, cel or group node++ --above <ABOVE>+ Place just above this sibling++ --below <BELOW>+ Place just below this sibling++ --index <INDEX>+ Position in the container, 0 is the bottom++ --frame <FRAME>+ Frame whose cel receives new nodes (default 0)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad set++```text+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.++ klad set art.draw n4 fill=#ff0000 transform.rotate=15+ klad set art.draw l2 opacity=0.5 blend=multiply+ klad set art.draw c4:s12 color=#c84a3a size=6 brush=pencil+ klad set art.draw c4:s7 color=skin opacity=0.8++Strokes take color, size, opacity, flow, brush and taper ([in,out] or null); fills take color and opacity. Colours may be palette names.++Usage: klad set [OPTIONS] <BUNDLE> <ID> [PROPS]...++Arguments:+ <BUNDLE>+++ <ID>+++ [PROPS]...+++Options:+ --frame <FRAME>+ Frame to render with --render++ [default: 0]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad rm++```text+Remove layers, cels or nodes++Usage: klad rm [OPTIONS] <BUNDLE> [IDS]...++Arguments:+ <BUNDLE>+++ [IDS]...+++Options:+ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad transform++```text+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.++ klad transform art.draw c4:s12 c4:s13 --move 40,-10+ klad transform art.draw c4:s12 --rotate 15 --scale 1.2+ klad transform art.draw c4:s3 c4:s5 --sx -1 --pivot 512,400++Also a transform op in klad apply: {"op":"transform","ids":["c4:s12"],"x":40,"y":-10,"rotate":15,"sx":1.2,"sy":1.2}++Usage: klad transform [OPTIONS] <BUNDLE> [IDS]...++Arguments:+ <BUNDLE>+++ [IDS]...+++Options:+ --move <OFFSET>+ dx,dy in px++ --rotate <ROTATE>+ Degrees, clockwise++ --scale <SCALE>+ Uniform scale++ --sx <SX>+++ --sy <SY>+++ --pivot <PIVOT>+ x,y to turn and scale about++ --flip <FLIP>+ Mirror: h (left-right) or v (up-down)++ [possible values: h, v]++ --frame <FRAME>+ Frame to render with --render++ [default: 0]++ --render+ Render a preview after the edit and print its path (longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad lasso++```text+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.++ klad lasso art.draw l3 --polygon '100,100 400,120 380,400 90,380'+ klad lasso art.draw l3 --polygon '100,100 400,120 380,400 90,380' --cut --move 60,-20+ klad lasso art.draw l3 --polygon '...' --cut --rotate 15 --scale 1.2+ klad lasso art.draw l3 --polygon '...' --flip h+ klad lasso art.draw l3 --polygon '...' --cut --rm++Also 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).++Usage: klad lasso [OPTIONS] --polygon <POLYGON> <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --polygon <POLYGON>+ x,y pairs separated by spaces++ --cut+ Split strokes and fills crossing the edge and take the inside parts too++ --move <OFFSET>+ dx,dy in px++ --rotate <ROTATE>+ Degrees, clockwise++ --scale <SCALE>+ Uniform scale++ --sx <SX>+++ --sy <SY>+++ --pivot <PIVOT>+ x,y to turn, scale and flip about++ --flip <FLIP>+ Mirror: h (left-right) or v (up-down)++ [possible values: h, v]++ --rm+ Delete what the lasso holds++ --frame <FRAME>+ [default: 0]++ --render+ Render a preview after the edit and print its path (longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad path++```text+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.++ 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 --insert 3,0.5 (split the segment after point 3)+ klad path art.draw n7 --add 418,236 (a point on the nearest segment)+ klad path art.draw n7 --rm 4,5 --corner 2 --smooth 6+ klad path art.draw n7 --simplify 1.5 (fewer, smooth points within 1.5 px)++As 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.++Usage: klad path [OPTIONS] <BUNDLE> <NODE>++Arguments:+ <BUNDLE>+++ <NODE>+++Options:+ --move <POINT> <X,Y>+++ --nudge <POINTS> <DX,DY>+++ --handle <POINT> <in|out> <X,Y>+++ --insert <POINT[,T]>+++ --add <X,Y>+++ --rm <POINTS>+++ --corner <POINTS>+++ --smooth <POINTS>+++ --simplify <PX>+++ --convert+ Turn a rect or ellipse into a path without other changes++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad mv++```text+Move a layer or node: --above, --below, --in, --index++Usage: klad mv [OPTIONS] <BUNDLE> <ID>++Arguments:+ <BUNDLE>+++ <ID>+++Options:+ --in <INTO>+ Container: group layer, vector layer, cel or group node++ --above <ABOVE>+ Place just above this sibling++ --below <BELOW>+ Place just below this sibling++ --index <INDEX>+ Position in the container, 0 is the bottom++ --frame <FRAME>+ Frame whose cel receives new nodes (default 0)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad apply++```text+Apply many edits from JSON lines in one transaction: all apply or none.++ {"op":"add","layer":{"kind":"vector","name":"sky"}}+ {"op":"add","node":{"type":"rect","x":0,"y":0,"w":100,"h":50,"fill":"#336699"},"in":"l1"}+ {"op":"set","id":"n2","fill":"#ff0000","transform.rotate":15}+ {"op":"rm","id":"n2"}+ {"op":"mv","id":"l1","below":"l3"}+ {"op":"add","cel":{"frame":4,"hold":2},"in":"l3"}++New ids are printed in order.++Usage: klad apply [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --file <FILE>+++ --frame <FRAME>+ Frame to render with --render++ [default: 0]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad render++```text+Render a frame to PNG and print the path++Usage: klad render [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ -o, --out <OUT>+++ --frame <FRAME>+ [default: 0]++ --scale <SCALE>+ Scale (default 1, or longest side 1024 px with --focus)++ --region <REGION>+ Only this canvas region: x,y,w,h++ --focus <FOCUS>+ Zoom to a layer, cel or node, with a margin++ --overlay <OVERLAY>+ 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++ --track <TRACK>+ 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++ --depth <DEPTH>+ How deep into groups the overlay labels go++ [default: 1]++ --no-cache+ Replay every stroke instead of using cached tiles++ --references+ Show reference layers (photos to trace over), which renders leave out++ --onion <BEFORE,AFTER>+ Onion skin: how many drawings (or frames) before and after (default 2,2)++ --onion-by <drawings|frames>+ Count the onion skin in drawings (default) or in frames++ --onion-layers <LAYERS>+ Layers that show onion skin (ids or names; default: every layer with more than one drawing)++ --no-tint+ Onion skin without the red and green tint++ --onion-loop <FROM-TO>+ Treat these frames as a loop: the onion skin wraps around inside them++ --sheet <all|FROM-TO|CLIP>+ Render many frames in one grid, labelled with frame numbers, drawing ids and holds++ --drawings+ With --sheet: one cell per drawing (frames that look the same share a cell)++ --cell <CELL>+ With --sheet: the longest side of each cell in px++ [default: 256]++ --columns <COLUMNS>+ With --sheet: cells per row (default: about square)++ -h, --help+ Print help+```++## klad stroke++```text+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.++ 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+ klad stroke art.draw l3 --brush ink --size 6 --taper 12,30 --path 'M100 100 Q 200 40 300 120'+ klad stroke art.draw l3 --points '10,10,0.5 40,30,1 80,35,0.2'++Pressure 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.++Usage: klad stroke [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --path <PATH>+++ --points <POINTS>+ x,y,pressure triples separated by spaces++ --brush <BRUSH>+ [default: ink]++ --color <COLOR>+ [default: #000000]++ --size <SIZE>+ [default: 8]++ --opacity <OPACITY>+ [default: 1]++ --flow <FLOW>+ [default: 1]++ --pressure <PRESSURE>+ Pressure along the stroke, for example 0.2,1,0.1++ --speed <SPEED>+ Pen speed in px/s, sets sample spacing and timing++ [default: 700]++ --seed <SEED>+++ --taper <TAPER>+ Taper in and out by length in px, for example 12,30 (default: the brush's)++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --second <SECOND>+ The second colour, for brushes that mix towards it with pressure or along the stroke++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad fill++```text+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.++ klad fill art.draw l2 --at 820,640 --ref lines --gap 4 --color '#c84a3a'+ klad fill art.draw l2 --at 820,640 --ref all --color skin+ klad fill art.draw l2 --polygon '100,100 400,120 260,380' --color '#20304a'++Colours 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"}++Usage: klad fill [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --at <AT>+ Seed point x,y for a flood fill++ --polygon <POLYGON>+ Lasso polygon: x,y pairs separated by spaces++ --ref <REFERENCE>+ this (default), all, or a layer id or name++ --tolerance <TOLERANCE>+ 0..1, how different a pixel may be from the seed++ [default: 0.1]++ --gap <GAP>+ Close openings in the lines up to this many px++ [default: 0]++ --expand <EXPAND>+ Grow the fill under the lines by this many px++ [default: 2]++ --color <COLOR>+ [default: #000000]++ --opacity <OPACITY>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --like <LIKE>+ Carry the flood fills of this drawing (a cel of the layer) to the layer's other drawings++ --frames <FRAMES>+ With --like: the frames whose drawings get them: all, FROM-TO or a clip++ --shape <SHAPE>+ Fill exactly the area of a vector shape (a group: each closed shape in it), grown by --expand++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad ink++```text+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.++ klad ink art.draw lines --from body,eye,leg --weight 6 --light -1,-1+ klad ink art.draw lines --from rock --weight 9 --break 45 --gap 3 --wobble 1+ klad ink art.draw lines --path "M10 10 C 80 0 120 60 200 40" --weight 4++The 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}.++Usage: klad ink [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --from <FROM>+ Vector shape ids; a group inks every shape in it++ --path <PATH>+ SVG path data to ink instead of shapes++ --weight <WEIGHT>+ The full line weight in px++ [default: 6]++ --light <LIGHT>+ Where the light comes from, x,y (-1,-1: top left)++ --break <BREAK_DEG>+ Split strokes at corners sharper than this many degrees++ [default: 60]++ --gap <GAP>+ Leave this many px open at the ends of each stroke++ [default: 0]++ --wobble <WOBBLE>+ Seeded wobble in px (0: none)++ [default: 0.6]++ --taper <TAPER>+ Taper in,out in px (default: the brush's)++ --brush <BRUSH>+ [default: ink]++ --color <COLOR>+ [default: #000000]++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --hand <HAND>+ How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)++ [default: 1]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad light++```text+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.++ klad light art.draw --from body,head --light -1,-1 --shade shade --rim rim+ klad light art.draw --from rock --shade shade --depth 24 --soft 4 --shade-color '#3a2f50'++Also a light op: {"op":"light","from":["n5"],"light":[-1,-1],"shade":"l5","rim":"l6","depth":14,"soft":3,"rimWidth":4}.++Usage: klad light [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --from <FROM>+ Vector shape ids; a group lights every closed shape in it++ --light <LIGHT>+ Where the light comes from, x,y (-1,-1: top left)++ --shade <SHADE>+ The paint layer for the shade++ --rim <RIM>+ The paint layer for the rim light++ --depth <DEPTH>+ How far the shade reaches into a shape, px++ [default: 14]++ --soft <SOFT>+ Overlapping shade steps (1: a hard edge)++ [default: 3]++ --rim-width <RIM_WIDTH>+ [default: 4]++ --shade-color <SHADE_COLOR>+ [default: #5a4a6a]++ --rim-color <RIM_COLOR>+ [default: #fff1cc]++ --shade-opacity <SHADE_OPACITY>+ [default: 0.6]++ --rim-opacity <RIM_OPACITY>+ [default: 0.85]++ --frame <FRAME>+ [default: 0]++ --lamp <LAMP>+ A lamp at x,y,height in canvas px: each shape is shaded away from it++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad hatch++```text+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.++ klad hatch art.draw shade --in body --angle 35 --spacing 7 --length 10-24+ klad hatch art.draw lines --in trunk --along --spacing 9 --weight 1.5 --color '#3b2a1e'++Also a hatch op: {"op":"hatch","layer":"l5","in":["n5"],"angle":30,"spacing":6,"length":[12,30],"jitter":0.3,"weight":2}.++Usage: klad hatch [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --in <WITHIN>+ Closed vector shapes to hatch inside++ --polygon <POLYGON>+ Or a polygon: x,y pairs separated by spaces++ --angle <ANGLE>+ [default: 30]++ --along+ Follow the outline instead of parallel lines++ --spacing <SPACING>+ [default: 6]++ --length <LENGTH>+ Stroke lengths MIN-MAX px++ [default: 12-30]++ --jitter <JITTER>+ [default: 0.3]++ --weight <WEIGHT>+ Stroke size in px++ [default: 2]++ --brush <BRUSH>+ [default: ink]++ --color <COLOR>+ [default: #000000]++ --opacity <OPACITY>+ [default: 1]++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --hand <HAND>+ How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)++ [default: 1]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad paint++```text+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.++Strokes 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.++Paint 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.++ klad paint art.draw paint --in rock --color '#8a8f96' --light -1,-1+ klad paint art.draw paint --in pillar --form cylinder --axis 90 --color '#c9b8a0' --lamp 200,600,150+ klad paint art.draw paint --in wall --form flat --facing 0,0,1 --angle 0 --weight 10++Also a paint op: {"op":"paint","layer":"l5","in":["n5"],"color":"#5d6a78","light":[-1,-1],"weight":14,"form":"round"}.++Usage: klad paint [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --in <WITHIN>+ Closed vector shapes to paint inside++ --polygon <POLYGON>+ Or a polygon: x,y pairs separated by spaces++ --brush <BRUSH>+ [default: oil]++ --bold <BOLD>+ The brush for the decisive strokes in the lights++ [default: oil-load]++ --color <COLOR>+ The local colour in full light++ [default: #808080]++ --form <FORM>+ round, flat or cylinder++ [default: round]++ --axis <AXIS>+ A cylinder's axis in degrees (90 is vertical)++ [default: 90]++ --facing <FACING>+ A flat form's facing x,y,z (z toward the viewer, y down)++ [default: 0,0,1]++ --light <LIGHT>+ Where the light comes from, as a direction x,y++ [default: -1,-1]++ --elevation <ELEVATION>+ How far the light is toward the viewer (0 grazes the picture)++ [default: 0.6]++ --lamp <LAMP>+ A lamp at x,y,height in canvas px instead of a direction++ --key <KEY>+ The key light's colour++ [default: #fff3e2]++ --fill <FILL>+ The fill light's colour, from above++ [default: #8a9ab8]++ --fill-strength <FILL_STRENGTH>+ [default: 0.16]++ --bounce <BOUNCE>+ The bounce light's colour, from below++ [default: #b08a66]++ --bounce-strength <BOUNCE_STRENGTH>+ [default: 0.1]++ --core <CORE>+ How much darker the core just past the terminator is++ [default: 0.35]++ --shadow <SHADOW>+ The shadow side takes this colour's hue and chroma and keeps its own values (a colour or a palette name)++ --shadow-mix <SHADOW_MIX>+ How far the shadow side goes towards --shadow, 0 to 1++ [default: 0.7]++ --angle <ANGLE>+ Stroke direction on flat forms, degrees++ [default: 30]++ --weight <WEIGHT>+ Stroke size in px of the middle pass++ [default: 14]++ --decisive <DECISIVE>+ How many decisive and quiet strokes, 0 for none++ [default: 1]++ --vary <VARY>+ How much each stroke's value strays++ [default: 0.03]++ --hand <HAND>+ How much each stroke is drawn like a hand (0 gives even strokes)++ [default: 1]++ --opacity <OPACITY>+ [default: 1]++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad prepare++```text+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.++ klad prepare art.draw+ klad prepare art.draw --from 0 --to 23++Usage: klad prepare [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --from <FROM>+++ --to <TO>+++ -h, --help+ Print help (see a summary with '-h')+```++## klad scatter++```text+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).++ klad scatter art.draw lines --in ground --mark "M0 0 L0 -18" --count 40 --size 0.7-1.2 --turn -15,15+ klad scatter art.draw lines --in rock --mark "M0 0 L6 3 L10 -2" --spacing 22 --avoid moss++Also 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"]}.++Usage: klad scatter [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --in <WITHIN>+ Closed vector shapes to scatter inside++ --polygon <POLYGON>+ Or a polygon: x,y pairs separated by spaces++ --avoid <AVOID>+ Shapes to keep clear of++ --mark <MARK>+ [default: "M0 0 L0 -18"]++ --count <COUNT>+ How many marks (default: one every --spacing px)++ --spacing <SPACING>+ [default: 14]++ --size <SIZE>+ Scale of each copy MIN-MAX++ [default: 0.7-1.2]++ --turn <TURN>+ Turn of each copy MIN,MAX degrees++ [default: -15,15]++ --weight <WEIGHT>+ Stroke size in px++ [default: 2]++ --brush <BRUSH>+ [default: ink]++ --color <COLOR>+ [default: #000000]++ --opacity <OPACITY>+ [default: 1]++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --hand <HAND>+ How much each stroke is drawn like a hand: its own pressure curve, tapers and width (0 gives even strokes)++ [default: 1]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad foliage++```text+Build each closed shape out of leaves: leaf marks across the clump take their colour from a round form lit by --light (or a --lamp x,y,height), in a few value steps from --shade through --color to --lit (by default darker and cooler, lighter and warmer than --color), with the most variety in the light; then leaves along the outline, most on the side facing the light and the sky, a few glowing (--glow) at the shadow side's edge, so the silhouette breaks up and the sky shows between them. --mass names a shape around the whole crown, so every clump also turns with the big form. --leaf is the leaf size in px, --density how close the leaves sit. Fill a darker, slightly smaller core under each clump first and paint clumps back to front on one layer. The brush is leaves (several leaf shapes, one per dab).++ klad foliage tree.draw canopy --in clump1 --color '#4d7a3b' --light -0.6,-0.8 --leaf 16 --mass crown++Also a foliage op: {"op":"foliage","layer":"canopy","in":["clump1"],"color":"#4d7a3b","light":[-0.6,-0.8],"leaf":16,"mass":"crown"}.++Usage: klad foliage [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --in <WITHIN>+ Closed vector shapes, each a clump of leaves++ --color <COLOR>+ The leaves' middle colour++ [default: #4f7a3c]++ --lit <LIT>+ The lit leaves' colour (default: lighter and warmer)++ --shade <SHADE>+ The shadowed leaves' colour (default: darker and cooler)++ --glow <GLOW>+ Light through thin leaves at the shadow edge (default: a warm yellow-green)++ --light <LIGHT>+ [default: -1,-1]++ --lamp <LAMP>+ A lamp at x,y,height in canvas px instead of a direction++ --leaf <LEAF>+ Leaf size in px++ [default: 14]++ --density <DENSITY>+ How close the leaves sit (2 is twice as many)++ [default: 1]++ --mass <MASS>+ A shape around the whole crown, so each clump also turns with the big form++ --brush <BRUSH>+ [default: leaves]++ --edges-only+ Only the leaves along the outline, not across the clump++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad bone++```text+Bones go on a paint layer or a group (a group's skeleton poses every paint layer in it together). A bone has a name, an optional parent, a head and a tail in canvas px; a child usually starts where its parent ends. Removing a bone removes its children.++ klad bone art.draw body --add hip --head 400,500 --tail 400,420+ klad bone art.draw body --add thigh --parent hip --head 400,500 --tail 410,620+ klad bone art.draw body --rename thigh --as femur+ klad bone art.draw body --move femur --tail 420,630+ klad bone art.draw body --reparent femur --parent pelvis+ klad bone art.draw body --rm femur++Also a bone op: {"op":"bone","layer":"body","add":"thigh","parent":"hip","head":[400,500],"tail":[410,620]}.++Usage: klad bone [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --add <ADD>+++ --rm <RM>+++ --rename <RENAME>+++ --as <TO_NAME>+++ --move <MOVED>+++ --reparent <REPARENT>+++ --parent <PARENT>+++ --head <HEAD>+++ --tail <TAIL>+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad bones++```text+List the skeletons, their bones and weights, and the posed drawings++Usage: klad bones [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --json+++ -h, --help+ Print help+```++## klad weights++```text+Every bone has a weight map over the rest drawing (a grid at a quarter of the canvas resolution); where weights blend, lines bend smoothly; a part held by one bone at weight 1 moves rigidly. --auto starts from the bones (by distance, blending across the joints). --set paints soft round dabs of a weight onto --bone: 'x,y,radius,weight ...'. --part makes a named part of the drawing (at --frame) fully that bone's (and no other's). --smooth blurs the maps a little. render --overlay weights:<bone> shows a bone's map.++ klad weights art.draw body --auto+ klad weights art.draw body --bone shin --set '400,600,30,1 410,640,20,0.8'+ klad weights art.draw body --bone head --part head++Also a weights op: {"op":"weights","layer":"body","bone":"shin","set":[[400,600,30,1]]}.++Usage: klad weights [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --auto+++ --bone <BONE>+++ --set <SET>+++ --part <PART>+++ --value <VALUE>+ [default: 1]++ --smooth+++ --frame <FRAME>+ [default: 0]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad pose++```text+A pose is a turn per bone (degrees from its rest angle, children follow their parent) and a move of the whole (--root). Every paint layer under the skeleton gets a new drawing at --to: each stroke point and fill moves by its bones' weighted blend, the same way Godot's Skeleton2D bends a Polygon2D. The pose is kept on the drawing; posing that frame again re-poses it from the same rest drawing, and posing from a posed drawing starts from its rest drawing. klad inbetween between two poses of one rest drawing turns the bones instead of matching strokes.++ klad pose art.draw body --from 0 --to 4 --bone thigh=25 --bone shin=-40 --root 0,6++Also a pose op: {"op":"pose","layer":"body","from":0,"to":4,"bones":{"thigh":25,"shin":-40},"root":[0,6]}.++Usage: klad pose [OPTIONS] --to <TO> <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --from <FROM>+ [default: 0]++ --to <TO>+++ --bone <BONES>+ name=degrees; repeat for more++ --root <ROOT>+ [default: 0,0]++ --hold <HOLD>+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad key++```text+Keys animate a layer, a group or a vector shape without a drawing per frame: x and y (px), rotate (degrees), sx, sy or scale, and opacity, each with its own keys. Between two keys the value follows the first key's ease: linear, in, out, in-out, step, or a curve x1,y1,x2,y2 (as in CSS). Before the first key and after the last the value holds. A layer or group turns and scales about the canvas centre; a shape about its own pivot. --rm removes the keys at that frame (only the named properties, or all).++ klad key art.draw lantern --frame 0 y=0+ klad key art.draw lantern --frame 12 y=-14 --ease in-out+ klad key art.draw glow --frame 6 opacity=0.4+ klad key art.draw lantern --frame 12 --rm++Also a key op: {"op":"key","id":"lantern","frame":12,"y":-14,"ease":"in-out"}.++Usage: klad key [OPTIONS] --frame <FRAME> <BUNDLE> <ID> [VALUES]...++Arguments:+ <BUNDLE>+++ <ID>+++ [VALUES]...+ prop=value: x, y, rotate, sx, sy, scale, opacity++Options:+ --frame <FRAME>+++ --ease <EASE>+ [default: linear]++ --rm+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad keys++```text+List the keys of every keyed layer, group and shape (or one)++Usage: klad keys [OPTIONS] <BUNDLE> [ID]++Arguments:+ <BUNDLE>+++ [ID]+++Options:+ --json+++ -h, --help+ Print help+```++## klad compare++```text+Render the drawing (or read a PNG or JPEG) at the reference's size and compare the two in OKLab: the value range (L at the 5th, 50th and 95th percentile), mean chroma, stroke texture (mean absolute Laplacian of L), edge sharpness (99th percentile of the gradient) and the mean colour difference, with what differs in words (lighter, bluer, busier, softer edges). --region adds a row per named rectangle; --heat writes a picture of where they differ most (black, red, yellow, white as the difference grows to 20).++ klad compare cafe.draw reference.png --region shade=40,300,200,120 --region cup=610,180,90,120 --heat diff.png++Usage: klad compare [OPTIONS] <DRAWING> <REFERENCE>++Arguments:+ <DRAWING>+++ <REFERENCE>+++Options:+ --frame <FRAME>+ [default: 0]++ --region <REGIONS>+ name=x,y,w,h in the reference's pixels; repeat for more++ --heat <HEAT>+++ --json+++ -h, --help+ Print help (see a summary with '-h')+```++## klad paintover++```text+Repaint what is below a paint layer (or the layers in --from) with strokes on that layer: big brushes first, then smaller ones only where the painting still differs from the source by more than --threshold (a colour difference in OKLab, x100), so detail lands where the source has it. Each stroke takes the source's colour where it starts, broken a little warm and cool (--vary), and runs along the forms (across the colour gradient) until the colour under it changes, it reaches --length (in brush widths, min,max) or it would bend more than --curve allows (0 straight, 1 follows every turn). --in limits it to closed shapes; --focus lets the smallest brush work only in and near one shape. The strokes are ordinary strokes in the part "paint over" (--part), one history step, so they take body and relief and can be edited.++For animation, paint over one key, then carry it to the next with --like <cel>: every stroke moves with the marks under it, takes its colour from the new drawing, and strokes are only added (part "paint over added") where the new drawing needs them. The carried strokes keep their order, so klad inbetween pairs them part by part and nothing boils.++ klad paintover still.draw brushwork --sizes 32,16,8 --threshold 6+ klad paintover walk.draw brushwork --frame 4 --like c12++Also a paintover op, alone in its batch: {"op":"paintover","layer":"brushwork","sizes":[32,16,8],"threshold":6}.++Usage: klad paintover [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --from <FROM>+ Layers to paint from (default: everything below the layer, with the background)++ --in <WITHIN>+ Closed vector shapes to paint inside++ --sizes <SIZES>+ Brush sizes in px, biggest first++ [default: 32 16 8]++ --threshold <THRESHOLD>+ How far the painting may differ from the source (OKLab difference x100)++ [default: 6]++ --length <LENGTH>+ Stroke length in brush widths: min,max++ [default: 1,8]++ --curve <CURVE>+ How closely strokes follow the forms' turns (0 to 1)++ [default: 0.5]++ --brush <BRUSH>+ [default: oil]++ --focus <FOCUS>+ A closed shape: the smallest brush only paints in and near it++ --vary <VARY>+ Warm and cool, light and dark break per stroke (OKLab)++ [default: 0.025]++ --like <LIKE>+ Carry the paint-over of this drawing (a cel id on the same layer) to this frame++ --frames <FRAMES>+ With --like: carry it from drawing to drawing over these frames (a-b), making a drawing on the layer wherever the source starts one++ --part <PART>+ [default: "paint over"]++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad grass++```text+Fill closed shapes with grass blades from the far (top) edge to the near (bottom) one: each blade rises from its root, leans with --wind (degrees) and bends, and is smaller and denser towards the top (--far is the far size against the near one). The ground under them rolls in soft patches about --patch px wide, lit by --light (or a --lamp x,y,height): each blade runs from a dark root to a lit tip in a few value families from --shade through --color to --lit. Along the top edge taller blades (--edge) break the outline against what is behind. Near blades are drawn last.++With a stroke brush (blade, the default, or any round or chalk tip) each blade is a tapered stroke whose colour runs from --color at the root to the lit colour at the tip when the brush blends to a second colour by pressure. With a picture brush (a tip made of pictures, like your own tufts) each blade is one stamp of the picture, turned to the blade. Build your own brush for your grass (klad brushes --picture, --set) and pass it with --brush: the op decides where the marks go and how they are lit, the brush decides what they look like.++ klad grass meadow.draw field --in field-shape --color '#6f8a3c' --light -0.9,-0.45 --blade 30 --far 0.22+ klad grass meadow.draw bank --in bank --brush my-tuft --blade 160 --density 0.1++Also a grass op: {"op":"grass","layer":"field","in":["field-shape"],"color":"#6f8a3c","blade":30,"far":0.22,"wind":12}.++Usage: klad grass [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --in <WITHIN>+ Closed vector shapes to grow grass in++ --color <COLOR>+ The grass's middle colour++ [default: #5f8a3e]++ --lit <LIT>+ The lit tips' colour (default: lighter and warmer)++ --shade <SHADE>+ The shadowed roots' colour (default: darker and cooler)++ --light <LIGHT>+ [default: -1,-1]++ --lamp <LAMP>+ A lamp at x,y,height in canvas px instead of a direction++ --blade <BLADE>+ Blade length in px at the near edge++ [default: 36]++ --width <WIDTH>+ Blade width in px at the near edge (default: an eighth of the length)++ --far <FAR>+ Size at the far edge against the near one++ [default: 0.45]++ --wind <WIND>+ How far the blades lean, degrees (negative leans left)++ [default: 8]++ --density <DENSITY>+ How close the blades stand (2 is twice as many)++ [default: 1]++ --edge <EDGE>+ How much taller the blades along the top edge are++ [default: 1.35]++ --patch <PATCH>+ Width of the ground's light patches in px (default: four blade lengths)++ --brush <BRUSH>+ [default: blade]++ --kinds <KINDS>+ The species, as JSON: [{"name":"fine","share":0.5,"width":0.7},{"brush":"my-clover","low":true,"share":0.2}] (default: a meadow mix of fine, broad, dry, seed heads and clover)++ --seed <SEED>+ [default: 1]++ --frame <FRAME>+ [default: 0]++ --part <PART>+ Put the new marks in this part of the drawing (see klad part)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad gaps++```text+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.++ klad gaps art.draw colour --frame 4+ klad gaps art.draw colour --sheet all+ klad gaps art.draw colour --sheet walk --ref lines --gap 4++The reference, gap and tolerance default to those of the layer's flood fills on those frames.++Usage: klad gaps [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --frame <FRAME>+++ --sheet <all|FROM-TO|CLIP>+ Check many frames++ --ref <REFERENCE>+ this, all or a layer (default: what the layer's fills use)++ --gap <GAP>+ Close openings up to this many px (default: the fills' gap)++ --tolerance <TOLERANCE>+++ --min <MIN>+ Ignore pockets smaller than this many px++ [default: 12]++ --render+ Render the frames even when nothing is found++ --json+++ -h, --help+ Print help (see a summary with '-h')+```++## klad refill++```text+Recompute the flood fills of a paint cel after the lines they were made from changed++Usage: klad refill [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --frame <FRAME>+ [default: 0]++ --id <ID>+ Only this fill (klad strokes lists fill ids)++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad palette++```text+The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin).++ klad palette art.draw+ klad palette art.draw --add '#f0c8a0' --name skin+ klad palette art.draw --add '#d0a080' --name skin (changes skin)+ klad palette art.draw --rm skin++As ops: {"op":"palette","add":"#f0c8a0","name":"skin"}, {"op":"palette","rm":"skin"}, {"op":"palette","set":[{"color":"#1b1b1b","name":"ink"}]}++Usage: klad palette [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --add <ADD>+++ --name <NAME>+++ --rm <RM>+++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad export++```text+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.++ klad export art.draw+ klad export art.draw --scale 2+ klad export art.draw --layer lines --scale 4 --depth 16 -o lines.png++Animations (each clip, or the whole timeline when there are no clips):++ klad export art.draw --sheet all [--scale 0.5] [--padding 2] [--max 4096]+ 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+ klad export art.draw --sheet run one clip; --sheet 0-11 a range+ klad export art.draw --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/+ 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.++Usage: klad export [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --png+ PNG output (the default for a single image)++ --layer <LAYER>+ A layer or group id or name instead of the whole image++ --frame <FRAME>+ [default: 0]++ --scale <SCALE>+ [default: 1]++ --depth <DEPTH>+ 8 (dithered) or 16 bits per channel++ [default: 8]++ --background+ Keep the canvas background instead of transparency++ --references+ Keep reference layers (photos to trace over), which exports leave out++ --sheet <SHEET>+ Sprite sheet and Aseprite JSON: all, a clip or a range like 0-11++ --frames <FRAMES>+ Numbered PNGs, one per frame: all, a clip or a range++ --godot [<GODOT>]+ Godot SpriteFrames and AnimatedSprite2D scene into this folder (default: the document's export.godot)++ --store+ Keep the --godot folder as the document's, replacing the one it has++ --godot-scene [<GODOT_SCENE>]+ A Godot parallax scene: each top-level layer a texture (with its fog) on a Parallax2D that scrolls by 1/(1+depth), into this folder (default: the document's export.godot)++ --godot-rig [<GODOT_RIG>]+ A Godot rig: the rest drawing as Polygon2Ds weighted to a Skeleton2D, and an AnimationPlayer with the poses of every clip, into this folder++ --padding <PADDING>+ Sheets: transparent pixels around each picture++ [default: 2]++ --max <MAX>+ Sheets: largest page side in px++ [default: 4096]++ -o, --out <OUT>+++ -h, --help+ Print help (see a summary with '-h')+```++## klad brushes++```text+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).++ klad brushes+ klad brushes art.draw+ klad brushes art.draw --show ink++Usage: klad brushes [OPTIONS] [BUNDLE]++Arguments:+ [BUNDLE]+++Options:+ --show <SHOW>+ Print one brush in full (JSON)++ --json+++ --set <ID> <FILE>+ Add a brush to the bundle from a JSON file (- for stdin)++ --picture <NAME> <PNG>+ Add a picture (tip or texture) to the bundle's brushes/images++ -h, --help+ Print help (see a summary with '-h')+```++## klad effect++```text+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.++Usage: klad effect [OPTIONS] <BUNDLE> <LAYER> [REST]...++Arguments:+ <BUNDLE>+++ <LAYER>+++ [REST]...+ blur, glow, outline, shadow, noise or displace, then key=value pairs++Options:+ --rm <RM>+ Remove the effect at this position (0 is the first)++ --clear+ Remove every effect++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help (see a summary with '-h')+```++## klad reshape++```text+Bend a brush stroke along a new path; it keeps its pressure, tilt and timing (klad strokes --json gives each stroke's fitted path)++Usage: klad reshape [OPTIONS] --path <PATH> <BUNDLE> <STROKE>++Arguments:+ <BUNDLE>+++ <STROKE>+ The stroke, <cel>:s<id>++Options:+ --path <PATH>+ SVG path data the stroke follows from start to end++ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad undo++```text+Undo the last change (from the CLI or the editor)++Usage: klad undo [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad redo++```text+Redo the last undone change++Usage: klad redo [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --render+ Render a preview after the edit and print its path++ --scale <SCALE>+ Preview scale (default: longest side 1024 px)++ --json+ Print the result as JSON++ --overlay <OVERLAY>+ Draw on the preview: ids, bbox, grid or all (comma separated)++ -h, --help+ Print help+```++## klad log++```text+Recent changes, newest first++Usage: klad log [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --limit <LIMIT>+ [default: 20]++ --json+++ -h, --help+ Print help+```++## klad selection++```text+What the human has selected in the editor (layer and shapes, with bounds)++Usage: klad selection [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --json+++ -h, --help+ Print help+```++## klad notes++```text+Notes the human pinned on the canvas; --done <id> marks one as handled++Usage: klad notes [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --done <DONE>+++ --all+ Include notes already marked done++ --json+++ -h, --help+ Print help+```++## klad diff++```text+Before and after renders of a change, side by side (default: the last one)++Usage: klad diff [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --step <STEP>+ History step number from klad log++ --frame <FRAME>+ [default: 0]++ --scale <SCALE>+++ -h, --help+ Print help+```++## klad info++```text+Paint cels with stroke counts and file sizes++Usage: klad info <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ -h, --help+ Print help+```++## klad strokes++```text+List the strokes and fills of a paint layer's cel at a frame++Usage: klad strokes [OPTIONS] <BUNDLE> <LAYER>++Arguments:+ <BUNDLE>+++ <LAYER>+++Options:+ --frame <FRAME>+ [default: 0]++ --after <AFTER>+ Only strokes with an id above this++ [default: 0]++ --json+ Print strokes as JSON with their points (x, y, pressure)++ -h, --help+ Print help+```++## klad hash++```text+Print pixel hashes, for comparing macOS and Linux renders++Usage: klad hash [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --frame <FRAME>+ [default: 0]++ --all+ One line per frame of the timeline++ --no-cache+++ -h, --help+ Print help+```++## klad demo++```text+Write a sample bundle (vector sky and hills, painted glow, clouds, hatching, grass)++Usage: klad demo [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --size <SIZE>+ [default: 2048]++ --seed <SEED>+ [default: 1]++ --force+ Replace an existing bundle++ -h, --help+ Print help+```++## klad stress++```text+Create a large bundle of synthetic paint layers for editor performance tests++Usage: klad stress [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --size <SIZE>+ [default: 4096]++ --layers <LAYERS>+ [default: 30]++ --strokes <STROKES>+ [default: 300]++ --seed <SEED>+ [default: 1]++ --frames <FRAMES>+ Timeline length; a drawing per layer every --every frames++ [default: 1]++ --every <EVERY>+ [default: 2]++ -h, --help+ Print help+```++## klad scribble++```text+Append synthetic ink strokes to a paint layer (sync test)++Usage: klad scribble [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --layer <LAYER>+++ --frame <FRAME>+ [default: 0]++ --count <COUNT>+ [default: 1]++ --seed <SEED>+++ --size <SIZE>+ Brush size for every stroke (default: varied)++ --color <COLOR>+ [default: #bf2620]++ -h, --help+ Print help+```++## klad watch++```text+Print editor saves as they arrive, with how long they took to show up here++Usage: klad watch [OPTIONS] <BUNDLE>++Arguments:+ <BUNDLE>+++Options:+ --poll+ Poll instead of native file events++ --seconds <SECONDS>+ [default: 120]++ -h, --help+ Print help+```++## klad licences++```text+Print the licence and the third-party notices (every open source part klad is built on)++Usage: klad licences++Options:+ -h, --help+ Print help+```++## klad install++```text+Put klad on the terminal's path, for you and for agents. macOS: a link in /usr/local/bin (asks for your password when that folder is not yours). Linux: a link in ~/.local/bin. Windows: this folder is added to your PATH. --dir puts the link in another folder.++ klad install+ klad install --dir ~/bin++Usage: klad install [OPTIONS]++Options:+ --dir <DIR>+++ -h, --help+ Print help (see a summary with '-h')+```++## klad skill++```text+Print the agent skill: how an agent draws with klad (the same text as docs/skill/SKILL.md)++Usage: klad skill++Options:+ -h, --help+ Print help+```++## klad bench++```text+Measure stroke storage, brush speed, replay, cache and compositing++Usage: klad bench [OPTIONS]++Options:+ --strokes <STROKES>+ [default: 10000]++ --size <SIZE>+ [default: 4096]++ --seed <SEED>+ [default: 1]++ -h, --help+ Print help+```++## klad open++```text+Open the editor, on a bundle or on the start window (new, open, recent)++Usage: klad open [BUNDLE]++Arguments:+ [BUNDLE]+++Options:+ -h, --help+ Print help+```diff --git a/docs/format.md b/docs/format.mdnew file mode 100644index 0000000..cdeb949--- /dev/null+++ b/docs/format.md@@ -0,0 +1,332 @@+_Last updated: 2026-11-06 (format `draw-anything/9`, stroke files version 6, brushes `draw-anything-brush/1`)_++# The klad drawing format++A klad drawing is a folder whose name ends in `.draw`, called a bundle. This document describes everything in it, so that any program can read, write and make klad drawings. It is licensed under the MIT License (`LICENSE-MIT`), unlike klad itself.++klad is the reference: when this text and klad's renders disagree, klad is right and this text is wrong. The data is exact (every key, every byte); how pixels come out of it is described as far as a reader needs to draw a faithful approximation, not to match klad's renders bit for bit.++## The folder++| Path | What | Required |+|---|---|---|+| `doc.json` | the document: canvas, timeline, palette, layers, drawings, vector shapes | yes |+| `strokes/<layer>/<cel>.strokes` | the brush strokes and fills of one paint drawing | for paint drawings with marks |+| `brushes/<id>.json` | every brush a stroke uses, embedded the first time it is used | for every brush id in a stroke file |+| `brushes/images/<name>.png` | pictures that brushes use as tips or grain | when a brush names one klad does not have built in |+| `images/<file>` | pictures placed by `image` nodes (PNG) | for every `src` |+| `fonts/<file>` | fonts used by `text` nodes, with their licence files | for every `font` |+| `weights/<owner>.weights` | how much each bone of a skeleton moves each part of the drawing | for every layer or group with `bones` |+| `.gitignore` | `.cache/`, so a drawing can live in a git repository | no |+| `.cache/` | rebuildable pixels, the undo history, the editor's selection and pinned notes | no: never read it as data |++Everything outside `.cache/` is the drawing. Copy, version or zip those files and the drawing renders the same on another machine. Read the selection and the notes through `klad selection --json` and `klad notes --json`, not from `.cache/`.++Writers replace files atomically (write a temporary file, then rename), so a reader that watches the folder never sees half a file. `rev` in `doc.json` grows by one on every write.++## Conventions++- **Coordinates** are canvas pixels, origin at the top left, y down. Angles are degrees; positive turns clockwise on screen.+- **Colours** are `"#rrggbb"` or `"#rrggbbaa"`: sRGB, straight (not premultiplied) alpha.+- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node) and `nextId`. Ids are case sensitive.+- **JSON** is UTF-8, written pretty with a stable key order. Keys at their default value are left out; readers must take the defaults listed below for missing keys. Most objects reject keys they do not know, so writers must not add their own.+- **Versions.** `format` names the version of `doc.json` and everything it implies. klad opens every older version and migrates it in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle.++## doc.json++```json+{+ "format": "draw-anything/9",+ "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 }] },+ "export": { "godot": "../game/art/hero" },+ "palette": [{ "color": "#1b1b1b", "name": "ink" }, { "color": "#5b6ee1" }],+ "layers": [+ { "id": "l3", "name": "lines", "kind": "paint",+ "cels": [{ "id": "c1", "frame": 0, "hold": 2 }, { "id": "c2", "frame": 2, "link": "c1" }] },+ { "id": "l4", "name": "shapes", "kind": "vector", "blend": "multiply",+ "cels": [{ "id": "c4", "frame": 0, "nodes": [+ { "id": "n5", "type": "rect", "x": 0, "y": 0, "w": 2048, "h": 900,+ "fill": { "linear": { "from": [0, 0], "to": [0, 900], "stops": [[0, "#121d31"], [1, "#4a6a8c"]] } } }+ ] }] }+ ],+ "nextId": 7+}+```++### The document++| Key | Type | Default | Meaning |+|---|---|---|---|+| `format` | string | | `"draw-anything/9"` |+| `rev` | integer | | grows by one on every write |+| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) |+| `timeline` | object | 12 fps, 1 frame | see below |+| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`) |+| `layers` | array | | the layers, **bottom first** |+| `export` | object | `{}` | `godot`: the folder Godot exports go to, relative to the folder holding the bundle |+| `atmosphere` | object | none | fog by depth: `color` (`#9aa8b8`), `top` (a colour higher up), `density` (0.5), `blur` (1), `desaturate` (0.15) |+| `nextId` | integer | 0 | the counter new ids are made from |++Strokes and fills store their colour, so the palette is a list of names for colours, never a reference: renaming or recolouring a swatch changes nothing drawn.++### The timeline++| Key | Type | Default | Meaning |+|---|---|---|---|+| `fps` | integer | 12 | frames per second |+| `frames` | integer | 1 | the length; it always covers every cel's first frame |+| `origin` | `[x, y]` | the canvas centre | the point an engine export puts at the node's position |+| `clips` | array | `[]` | named frame ranges, in order of their first frame |++A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `fps` (the timeline's when absent). Clips may overlap.++### Layers++| Key | Type | Default | Meaning |+|---|---|---|---|+| `id`, `name` | string | | |+| `kind` | string | | `paint`, `vector`, `group` or `adjust` |+| `cels` | array | `[]` | paint and vector layers: the drawings on the timeline |+| `children` | array | `[]` | groups: the layers inside, bottom first |+| `adjust` | object | | adjustment layers: one adjustment (below) |+| `opacity` | number | 1 | |+| `blend` | string | `normal` | `normal`, `multiply`, `screen`, `overlay`, `add`, `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity` |+| `visible` | bool | true | |+| `locked` | bool | false | the editor refuses edits |+| `clip` | bool | false | show only where the base has alpha (below) |+| `lockAlpha` | bool | false | new marks land only where the layer has paint (below) |+| `mask` | layer | none | a paint layer whose alpha hides this one (below) |+| `effects` | array | `[]` | applied in order when the layer composes (below) |+| `depth` | number | none | on a top-level layer or group: how far the plane is (0 near); drives the atmosphere and parallax |+| `reference` | bool | false | shown in the editor, left out of renders and exports (pictures to trace) |+| `bones` | array | `[]` | a skeleton (paint layers and groups, below) |+| `keys` | object | `{}` | animated properties (below) |++Layers compose bottom to top. Groups compose their children into one image, then blend that with the group's opacity and blend. An **adjustment layer** changes what is under it inside its group (or, with `clip`, only its base).++- **Clipping.** A layer with `clip: true` shows 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, kept inside the base's alpha; the group then blends with the base's blend and opacity. A hidden base hides its clipped layers; the lowest layer of a list is never clipped.+- **Masks.** `mask` is a paint layer of its own (own id, cels and stroke files, `strokes/<mask id>/...`) with opacity 1 and blend normal. Its alpha hides the layer: marks on the mask hide, eraser strokes on it show the layer again, and a frame without a mask cel hides nothing. `visible: false` on the mask turns it off.+- **Lock alpha** is recorded on each stroke and fill as it is made (a flag in the stroke file), so turning `lockAlpha` off later never changes what was drawn. A locked mark composites source-atop: it changes colour where the layer has paint and leaves alpha as it was.++### Cels: drawings on the timeline++A cel is a layer's content from `frame` on.++| Key | Type | Default | Meaning |+|---|---|---|---|+| `id` | string | | its marks are in `strokes/<layer>/<id>.strokes` (paint) |+| `frame` | integer | 0 | the first frame it shows on |+| `hold` | integer | until the next cel | how many frames it shows |+| `link` | string | none | show another cel's content (no chains) |+| `nodes` | array | `[]` | vector layers: the shapes |+| `parts` | object | `{}` | named groups of its marks: `{"leaf": [14, 15]}`, mark ids; a mark is in one part at most; unknown ids are ignored |+| `tween` | object | none | how an in-between was made (below) |+| `pose` | object | none | how a posed drawing was made (below) |++A cel that is not a link is a **drawing**; frames no cel covers are blank. Drawing on twos is `hold: 2`.++`tween` records an in-between made from two keys: `from` and `to` (the keys' drawing ids), `t` (0 to 1, after spacing), `match` (`order` or `near` when marks were not paired by id), `pairs` (forced pairs, `[first key mark, second key mark]`), `made` (a hash of the marks as made, so klad can tell whether someone drew on it since) and `unpaired` (`pop`, `pop 0.3`, `fade` or `draw-on`: how marks found in one key only were shown). The marks themselves are stored like any drawing's; the record only says how to remake them.++`pose` records a drawing bent from a rest drawing by its layer's skeleton: `rest` (the rest drawing's id), `angles` (degrees from rest per bone name) and `root` (`[dx, dy]`, default `[0, 0]`). Its marks are stored bent, so a reader can draw it without knowing about bones.++### Vector nodes++Every node has:++| Key | Type | Default | Meaning |+|---|---|---|---|+| `id` | string | | |+| `type` | string | | `rect`, `ellipse`, `path`, `group`, `image`, `text`, `rays`, `scatter`, `repeat`, `mirror` |+| `name` | string | `""` | |+| `fill` | paint | black | as in SVG, a node without `fill` is black; `"none"` for no fill |+| `stroke` | object | none | an outline: `paint` (black), `width` (1), `cap` (`butt`, `round`, `square`; round), `join` (`miter`, `round`, `bevel`; round), `dash` (SVG-style intervals) |+| `transform` | object | identity | `x`, `y`, `rotate` (degrees), `sx`, `sy` (1), `pivot` (`[x, y]`, default the centre of the node's bounds): translate, then rotate and scale about the pivot |+| `opacity` | number | 1 | |+| `blur` | number | 0 | Gaussian sigma in px over the whole node |+| `clip` | string | none | an SVG path in the node's own coordinates that clips it and its children |+| `visible` | bool | true | |+| `keys` | object | `{}` | animated properties (below) |++And by type:++| Type | Keys |+|---|---|+| `rect` | `x`, `y`, `w`, `h`, `radius` (0) |+| `ellipse` | `cx`, `cy`, `rx`, `ry` |+| `path` | `d`: SVG path data |+| `group` | `children`: nodes, drawn in order |+| `image` | `src` (a file in `images/`, named by a hash of its pixels), `x`, `y`, `w`, `h`: the picture stretched into that box |+| `text` | `text` (new lines allowed), `font` (a file in `fonts/`), `x` (the left, centre or right of each line, by `align`: `left`, `center`, `right`), `y` (the top of the first line), `size` (32), `tracking` (extra px between letters, 0), `leading` (line height as a multiple of the size, 1.2), `weight` (a variable font's `wght`, none); filled and outlined like any node |+| `rays` | light rays from a gap: `x`, `y` (the origin), `angle` (90, down), `spread` (40), `count` (7), `length` (600), `start` (the gap's width, 0), `falloff` (1), `noise` (0.5), `seed` (1); the node's fill colours them |+| `scatter` | copies of `children` (drawn around 0,0) over the box `x`, `y`, `w` (400), `h` (200): `count` (12), `seed` (1), `size` and `turn` ranges (`[0.8, 1.2]`, `[-20, 20]`), `avoid` (SVG paths no copy's centre lands in) |+| `repeat` | `count` (4) copies of `children`, each `step` (`[40, 0]`) further, turning `turn` degrees and growing `scale` (1) about `pivot`; or a grid `columns` wide with `row` (`[0, 40]`) between rows |+| `mirror` | `children` and their reflection across the line through `x`, `y` at `angle` |++**Paint** is a colour string, `"none"`, `{"linear": {"from": [x, y], "to": [x, y], "stops": [[offset, colour], ...]}}` or `{"radial": {"center": [x, y], "radius": r, "stops": [...]}}`, in the node's own coordinates.++### Effects++`effects` is a list of one-key objects, applied in order to the layer's composed image: `[{"glow": {"radius": 24}}, {"outline": {"width": 3}}]`. Missing settings take their defaults.++| Effect | Settings (defaults) |+|---|---|+| `blur` | `radius` (4) |+| `glow` | `radius` (12), `strength` (1), `threshold` (0: every pixel glows; about 0.7: only bright ones), `color` (none: the pixels' own), `blend` (`screen`) |+| `outline` | `width` (3), `color` (`#1b1b1b`), `inside` (false) |+| `shadow` | `x` (6), `y` (8), `radius` (6), `color` (`#00000080`) |+| `noise` | `amount` (0.08), `size` (1), `seed` (1), `mono` (true) |+| `displace` | `amount` (8), `size` (48), `seed` (1), `by` (a layer id whose red pushes across and green down, grey staying put; none: a seeded noise) |+| `haze` | `amount` (0.4), `color` (`#9aa8b8`), `top`, `span` (0), `desaturate` (0) |+| `relief` | `strength` (4), `light` (`[-1, -1]`), `highlight` (`#fff4dc`), `shade` (`#1c1826`), `softness` (0.8) |++### Adjustments++An adjustment layer's `adjust` is one of:++| Adjustment | Settings |+|---|---|+| `hsl` | `hue` (degrees), `saturation`, `lightness` (-1 to 1) |+| `levels` | `black` (0), `white` (1), `gamma` (1), `low` (0), `high` (1) |+| `curves` | `points` (`[[in, out], ...]` on brightness, 0 to 1), and `red`, `green`, `blue`, applied first |+| `balance` | `shadows`, `midtones`, `highlights` (each `[cyan-red, magenta-green, yellow-blue]`, -1 to 1), `keepLight` |+| `gradient-map` | `stops` by brightness |+| `fill` | `paint`, drawn with the layer's blend |++For example `{"kind": "adjust", "adjust": {"curves": {"points": [[0, 0], [0.5, 0.3], [1, 0.85]]}}}`.++### Keys: animated properties++Layers, groups and nodes may keep `keys`: per property (`x`, `y`, `rotate`, `sx`, `sy`, `opacity`) a list of keys sorted by frame.++```json+"keys": { "y": [{ "frame": 0, "value": 0, "ease": "in-out" }, { "frame": 12, "value": -40 }] }+```++A key is `frame`, `value` and `ease` (`linear` when absent; `in`, `out`, `in-out`, `step`, or `{"curve": [x1, y1, x2, y2]}`, a cubic curve as in CSS). Between two keys the value follows the first key's ease; it holds before the first key and after the last. A layer or group moves about the canvas centre; a node's keyed values replace its transform and opacity at that frame.++### Skeletons++A paint layer or a group may have `bones`: each a `name` (unique in the skeleton), a `parent` (a bone listed before it; none for a root), a `head` and a `tail` (`[x, y]` in canvas px, at rest). A group's skeleton moves every paint layer in it together. Each skeleton has a weights file (below). Posed drawings store their marks already bent (see `pose` above), so bones and weights are only needed to make new poses.++## Stroke files++`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills. Every mark has an id, unique within its drawing, from one counter shared by strokes and fills. A mark's address is `<cel>:s<id>`.++The file is one zstd frame (any level; klad uses 3). Inside:++| Bytes | What |+|---|---|+| 4 | `DAST` |+| 1 | the version, 6 now (klad reads 1 to 6) |+| varint | the number of marks |+| ... | each mark: a kind byte (0 stroke, 1 fill; from version 4, before that every mark is a stroke), then its record |++There must be nothing after the last mark.++Numbers: a **varint** is an unsigned LEB128 integer (7 bits per byte, low bits first, the high bit set on every byte but the last). A **signed varint** is zigzag encoded first (`(v << 1) ^ (v >> 63)`). `u16`, `u32` and `f32` are little-endian. A **colour** is four `u16`: red, green, blue, alpha, sRGB with straight alpha, 0 to 65535. A **string** is a varint length and that many UTF-8 bytes.++### Strokes++| Field | Encoding | Meaning |+|---|---|---|+| id | varint | |+| brush | string | a brush id: `brushes/<id>.json` |+| colour | colour | |+| size | f32 | px, at full pressure |+| opacity | f32 | 0 to 1 |+| flow | f32 | 0 to 1 |+| seed | u32 | the seed of the brush's randomness, so a stroke replays the same |+| channels | u8 | bits: 1 tilt, 2 time, 4 taper, 8 lock alpha, 16 cuts, 32 second colour |+| author | u8 | 0 a person, 1 an agent (from version 2) |+| taper | 2 f32 | if bit 4: px over which the start and end thin to a point, whatever the pressure (from version 3) |+| cuts | cuts | if bit 16 (from version 5) |+| second colour | colour | if bit 32: for brushes whose colour moves between two (from version 6) |+| samples | varint | n, the number of samples |+| x, y | 2 columns | position in 1/16 px |+| pressure | column | 0 to 4095 |+| tilt x, tilt y | 2 columns | if bit 1: the pen's tilt, -127 to 127 for -1 to 1 |+| time | column | if bit 2: milliseconds since the previous sample |++A **column** is n signed varints, each the difference from the previous value (the first from 0). Without the tilt or time bit those values are 0. Bit 8 has no data: it marks a stroke made with lock alpha on.++### Fills++| Field | Encoding | Meaning |+|---|---|---|+| id | varint | |+| colour | colour | |+| opacity | f32 | |+| author | u8 | 0 a person, 1 an agent |+| source | u8 | low bits: 0 a flood fill, 1 a polygon; bit `0x80` lock alpha, bit `0x40` cuts (from version 5) |+| flood fill | f32 x, f32 y, u8 reference, 3 f32 | the seed point; what it filled from: 0 this layer, 1 everything visible, 2 a layer (then a string, its id); `tolerance`, `gap`, `expand` |+| polygon | varint n, n pairs of f32 | the polygon's points |+| coverage | see below | the pixels the fill covered when it was made |+| cuts | cuts | if bit `0x40` |++A fill is drawn from its stored **coverage**, not recomputed, so it looks the same however the lines around it change (`klad refill` recomputes it on purpose). Coverage is a box and run-length coded alpha: varints `x`, `y`, `width`, `height`, a varint count of runs, then each run as a varint length and a `u8` alpha, row by row through the box.++### Cuts++When a lasso cuts across a mark, the mark is not split into new geometry: each part keeps the whole mark plus a cut that shows only its side. Cuts are a varint count, then for each a `u8` (0 keep inside, 1 keep outside) and a polygon (a varint n and n pairs of f32). A mark shows only where every one of its cuts keeps it.++## Brushes++`brushes/<id>.json` is the brush that strokes naming `<id>` were drawn with. A bundle keeps every brush its strokes use, and a brush in a bundle never changes once a stroke uses it, so a drawing renders the same on every version of klad.++| Key | Meaning |+|---|---|+| `format` | `"draw-anything-brush/1"` |+| `name` | |+| `tip` | `{"round": {"hardness": h}}`, `{"chalk": {"seed": n}}` or `{"image": {"image": name, "more": [names]}}` (several pictures take turns) |+| `spacing` | distance between dabs, as a share of the size |+| `roundness` | 1 round, less flattens the tip |+| `angle` | `"follow"` the stroke, `"tilt"` the pen, or `{"fixed": degrees}` |+| `flow`, `opacity` | per dab and per stroke (1) |+| `dynamics` | `size`, `flow`, `opacity`, each `{"pressure", "tilt", "speed"}` with curves `{"min", "max" (1), "gamma" (1)}` |+| `jitter` | `size`, `angle`, `scatter` per dab |+| `grain` | a texture: `paper` (`{"seed", "feature"}`, generated) or `image` (a picture name), `strength`, `scale` (1), `contrast` (1), `pressure` |+| `dual` | a second tip that cuts into the first: `tip`, `size` (0.5), `scatter` (1), `count` (3) |+| `color` | colour dynamics: `hue`, `saturation`, `value` per dab, `strokeHue`, `strokeSaturation`, `strokeValue` per stroke, `pressure` (a curve towards the second colour), `along` |+| `paint` | brushes that read the layer: `{"wet": {"wetness", "pickup", "dilution"}}`, `{"smudge": {"strength"}}` or `{"blend": {"strength"}}` |+| `blend` | `normal` or `erase` |+| `taper` | `[in, out]` px, used when a stroke has none of its own |+| `stabilizer`, `smoothing` | how the editor steadies the pen while drawing (strokes store the result) |+| `body` | bristle body for bristle brushes |++A picture named by a tip or grain is `brushes/images/<name>.png` (dark is paint, or the alpha where there is one) when the bundle has it, and otherwise one of the pictures built into klad.++Drawing a stroke: walk the samples, interpolate between them, stamp the tip every `spacing` x size along the way, with size, flow and opacity from the pressure (and tilt and speed) through the dynamics, the taper thinning the ends, and the per-dab jitter from the stroke's `seed`. A program that does not implement klad's brush engine can still draw a fair likeness with a round tip of the stroke's size and colour.++## Weights++`weights/<owner>.weights` holds the weights of the skeleton of layer or group `<owner>`: one map per bone over a grid of 4 px cells. The file is one zstd frame holding a line of JSON, a newline, then the maps:++```+{"width": 512, "height": 256, "bones": ["hip", "thigh", "shin"]}\n+<width x height bytes for "hip"><... for "thigh"><... for "shin">+```++`width` and `height` are the canvas size in cells (rounded up); each map is one byte per cell, 0 to 255, rows top first, in the order of `bones`. Weights are normalised across bones when used, and a place no bone weighs follows the nearest bone.++## Pictures and fonts++`images/` holds the pictures `image` nodes show, as PNG, each named by a hash of its contents so the same picture is stored once. `fonts/` holds the font files `text` nodes name (TrueType or OpenType) with their licence files beside them; text is shaped with HarfBuzz rules (kerning, ligatures, marks) from the file alone, never from fonts installed on the machine.++## Format history++| Format | Change |+|---|---|+| 0, 1 | the first versions: brushes were not embedded (klad embeds the brushes of that time when it opens one) |+| 2 | every brush a stroke uses is embedded in `brushes/` |+| 3 | `palette`; paint drawings may hold fills (stroke files version 4) |+| 4 | `mask`, `clip`, `lockAlpha`; stroke files version 5 (lock and cuts) |+| 5 | a clip's `fps`, `timeline.origin`, `export.godot` |+| 6 | a cel's `tween` |+| 7 | a cel's `parts`, a tween's `unpaired` |+| 8 | `effects`; adjustment layers, `depth`, `atmosphere`, `reference` and the `image`, `text`, `rays`, `scatter`, `repeat` and `mirror` nodes came while the format was 8 |+| 9 | `bones` on layers, `pose` on cels, `keys`, weights files |++klad migrates any older bundle on open.diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 596f6f7..8dcd3df 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -1,5 +1,6 @@---name: klad+license: MIT (LICENSE-MIT in the klad repository)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.---diff --git a/justfile b/justfileindex 483f95d..d8e6e9f 100644--- a/justfile+++ b/justfile@@ -27,9 +27,18 @@ app:dist target=`rustc -vV | sed -n 's/^host: //p'`:bash packaging/archive.sh {{target}}+itch-mac:+ test -n "${ITCH_TARGET:-}" || { echo "set ITCH_TARGET to the itch.io page, for example indicode/klad" >&2; exit 1; }+ KLAD_MAC_TARGETS="aarch64-apple-darwin x86_64-apple-darwin" bash packaging/macos/app.sh+ rm -rf dist/itch-mac && mkdir -p dist/itch-mac && cp -R dist/klad.app dist/itch-mac/+ butler push dist/itch-mac "$ITCH_TARGET:mac" --userversion "$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"+icon: buildKLAD={{klad}} bash packaging/icon/build.sh+reference: build+ {{klad}} reference > docs/cli.md+notices:bash licenses/notices.shdiff --git a/packaging/archive.sh b/packaging/archive.shindex 6563f7e..1790555 100755--- a/packaging/archive.sh+++ b/packaging/archive.sh@@ -21,7 +21,7 @@ cp "$built/klad$ext" "$stage/"[ -f "$built/klad-editor$ext" ] && cp "$built/klad-editor$ext" "$stage/"mkdir -p "$stage/fonts"(cd "$root/fonts" && tar cf - --exclude update.py .) | (cd "$stage/fonts" && tar xf -)-cp "$root/LICENSE" "$root/THIRD-PARTY-NOTICES.md" "$root/docs/skill/SKILL.md" "$stage/"+cp "$root/LICENSE" "$root/LICENSE-MIT" "$root/THIRD-PARTY-NOTICES.md" "$root/docs/skill/SKILL.md" "$stage/"cp "$root/packaging/icon/icon.png" "$stage/klad.png"case "$platform" inwindows)diff --git a/packaging/macos/app.sh b/packaging/macos/app.shindex 97d2f04..0894bf3 100755--- a/packaging/macos/app.sh+++ b/packaging/macos/app.sh@@ -27,7 +27,7 @@ donesed -e "s/@VERSION@/$version/" -e "s/@BUILD@/$build/" "$root/packaging/macos/Info.plist" > "$app/Contents/Info.plist"cp "$root/packaging/icon/klad.icns" "$app/Contents/Resources/"rsync -a --exclude update.py "$root/fonts/" "$app/Contents/Resources/fonts/"-cp "$root/LICENSE" "$root/THIRD-PARTY-NOTICES.md" "$app/Contents/Resources/"+cp "$root/LICENSE" "$root/LICENSE-MIT" "$root/THIRD-PARTY-NOTICES.md" "$app/Contents/Resources/"mkdir -p "$app/Contents/Resources/skill"cp "$root/docs/skill/SKILL.md" "$app/Contents/Resources/skill/"codesign --force --deep --sign - "$app" 2>/dev/null || true