mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fec1f8e34d | ||
|
|
ae87faf3c0 | ||
|
|
d7820dd7d2 | ||
|
|
74f83fb932 | ||
|
|
a21c1711e6 | ||
|
|
d88cc94b96 | ||
|
|
16612469a4 | ||
|
|
a7787d2825 | ||
|
|
afd88799f3 | ||
|
|
15e3c7363f | ||
|
|
9c1aecd162 | ||
|
|
b764405165 | ||
|
|
7422121c9e | ||
|
|
a011760786 | ||
|
|
a46b27f946 | ||
|
|
bc57f753db | ||
|
|
07d3036f04 | ||
|
|
77271b9304 | ||
|
|
3a8bbd0da4 |
No files matched your search
+11
-26
@@ -47,24 +47,20 @@ on:
|
||||
jobs:
|
||||
web:
|
||||
if: github.event_name == 'push' || inputs.web
|
||||
# Fork code always runs on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
runs-on: [self-hosted, target/wasm]
|
||||
permissions:
|
||||
contents: write
|
||||
deployments: write
|
||||
pull-requests: write
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from Binaryen
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -86,12 +82,7 @@ jobs:
|
||||
rustflags: ""
|
||||
target: wasm32-unknown-unknown
|
||||
|
||||
- name: 📦 Install sccache
|
||||
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: ${{ env.SCCACHE_VERSION }}
|
||||
|
||||
- name: 🚧 Install wasm-bindgen-cli, Binaryen wasm-opt, and cargo-about
|
||||
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
|
||||
run: |
|
||||
# Extracts into a temporary folder first so a cancelled download can't leave a truncated binary that later runs mistake for a finished install
|
||||
install_release_archive() {
|
||||
@@ -116,12 +107,6 @@ jobs:
|
||||
fi
|
||||
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
|
||||
|
||||
CARGO_ABOUT_DIR="$HOME/.cache/cargo-about-$CARGO_ABOUT_VERSION"
|
||||
if [ ! -x "$CARGO_ABOUT_DIR/cargo-about" ]; then
|
||||
install_release_archive "https://github.com/EmbarkStudios/cargo-about/releases/download/$CARGO_ABOUT_VERSION/cargo-about-$CARGO_ABOUT_VERSION-x86_64-unknown-linux-musl.tar.gz" "$CARGO_ABOUT_DIR"
|
||||
fi
|
||||
echo "$CARGO_ABOUT_DIR" >> "$GITHUB_PATH"
|
||||
|
||||
- name: 🔀 Choose production deployment environment and insert template
|
||||
id: production-env
|
||||
if: github.event_name == 'push'
|
||||
@@ -142,7 +127,7 @@ jobs:
|
||||
NODE_ENV: production
|
||||
# Split the Wasm binary to fit Cloudflare Pages' file size limit (see `wasmSplitting` in `frontend/vite.config.ts`)
|
||||
SPLIT_WASM: "1"
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
run: mold -run cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false
|
||||
@@ -314,7 +299,7 @@ jobs:
|
||||
cd frontend
|
||||
npm run check
|
||||
|
||||
# A job of its own so its native compile doesn't delay the web build and deploy
|
||||
# Runs on a GitHub-hosted runner to keep the self-hosted one free for web builds
|
||||
code-docs:
|
||||
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
|
||||
runs-on: ubuntu-latest
|
||||
@@ -340,7 +325,7 @@ jobs:
|
||||
|
||||
windows:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.windows
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'windows-latest' || vars.WINDOWS_RUNNER || 'windows-latest' }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
@@ -550,7 +535,7 @@ jobs:
|
||||
|
||||
mac:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.mac
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'macos-latest' || vars.MACOS_RUNNER || 'macos-latest' }}
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
@@ -756,7 +741,7 @@ jobs:
|
||||
|
||||
linux:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
@@ -3,14 +3,10 @@ name: "Check"
|
||||
on:
|
||||
pull_request: {}
|
||||
merge_group: {}
|
||||
# Checking each master commit also fills the compilation cache, which only master pushes may write to
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (merge queue refs are unique per entry, so those never cancel each other)
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
@@ -115,8 +111,7 @@ jobs:
|
||||
needs: skip-check
|
||||
# Always called with the skip decision passed in, since a skipped caller job reports only as `build` and leaves the required `build / web` check missing.
|
||||
# Like the jobs below, the checks still run if `skip-check` itself fails, since a skipped job counts as passing for required checks.
|
||||
# Master pushes are left out because `build.yml` builds and deploys those itself.
|
||||
if: ${{ !cancelled() && github.event_name != 'push' }}
|
||||
if: ${{ !cancelled() }}
|
||||
uses: ./.github/workflows/build.yml
|
||||
# The called workflow's jobs can only narrow these, so this grants the union of what they request
|
||||
permissions:
|
||||
@@ -130,22 +125,18 @@ jobs:
|
||||
web: ${{ needs.skip-check.outputs.skip != 'true' }}
|
||||
merge_queue: ${{ github.event_name == 'merge_group' }}
|
||||
|
||||
# Run the Rust tests
|
||||
# Run the Rust tests on the self-hosted native runner
|
||||
test:
|
||||
needs: skip-check
|
||||
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
|
||||
# Fork PRs always run on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
|
||||
runs-on: ${{ github.event.pull_request.head.repo.fork && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
runs-on: [self-hosted, target/native]
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep in sync with the web job in `build.yml`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder of its own
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -158,11 +149,6 @@ jobs:
|
||||
cache: false
|
||||
rustflags: ""
|
||||
|
||||
- name: 📦 Install sccache
|
||||
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: ${{ env.SCCACHE_VERSION }}
|
||||
|
||||
- name: 🦀 Fetch Rust dependencies
|
||||
run: cargo fetch --locked
|
||||
|
||||
@@ -170,7 +156,7 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: cargo test --all-features
|
||||
run: mold -run cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
rust-fmt:
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $0 <owner> <repo> <branch> <target-path> <artifact-file> <commit-message> <github-token>
|
||||
|
||||
Arguments:
|
||||
owner : GitHub user or organization of the target repo
|
||||
repo : Target repo name
|
||||
branch : Branch name (e.g. main)
|
||||
target-path : Full path (including folders + filename) in the target repo where to upload
|
||||
artifact-file : Local file path to upload
|
||||
commit-message : Commit message for creating/updating the file
|
||||
github-token : GitHub token (PAT or equivalent) with write access to the target repo
|
||||
|
||||
This will perform a GitHub API PUT to /repos/{owner}/{repo}/contents/{target-path}.
|
||||
If a file already exists at that path, it will auto-detect the SHA and update; otherwise it will create a new one.
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ $# -ne 7 ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
OWNER="$1"
|
||||
REPO="$2"
|
||||
BRANCH="$3"
|
||||
TARGET_PATH="$4"
|
||||
ARTIFACT_PATH="$5"
|
||||
COMMIT_MSG="$6"
|
||||
TOKEN="$7"
|
||||
|
||||
if [ ! -f "$ARTIFACT_PATH" ]; then
|
||||
echo "Error: artifact file not found: $ARTIFACT_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LOCAL_SHA=$(git hash-object "$ARTIFACT_PATH")
|
||||
echo "Local blob SHA: $LOCAL_SHA"
|
||||
|
||||
GET_URL="https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}?ref=${BRANCH}"
|
||||
GET_RESPONSE=$(curl -s -H "Authorization: token ${TOKEN}" "$GET_URL")
|
||||
|
||||
REMOTE_SHA=$(echo "$GET_RESPONSE" | jq -r .sha 2>/dev/null || echo "")
|
||||
|
||||
if [ "$REMOTE_SHA" != "null" ] && [ -n "$REMOTE_SHA" ]; then
|
||||
echo "Remote blob SHA: $REMOTE_SHA"
|
||||
if [ "$LOCAL_SHA" = "$REMOTE_SHA" ]; then
|
||||
echo "The remote file is identical. Skipping upload."
|
||||
exit 0
|
||||
else
|
||||
echo "Remote file differs. Preparing to upload."
|
||||
fi
|
||||
else
|
||||
echo "No existing remote file or no SHA found. Creating."
|
||||
fi
|
||||
|
||||
CONTENT_TMP_BASE64=$(mktemp)
|
||||
if base64 --help 2>&1 | grep -q -- "-w"; then
|
||||
base64 -w 0 "$ARTIFACT_PATH" > "$CONTENT_TMP_BASE64"
|
||||
else
|
||||
base64 "$ARTIFACT_PATH" | tr -d '\n' > "$CONTENT_TMP_BASE64"
|
||||
fi
|
||||
|
||||
PAYLOAD_TMP=$(mktemp)
|
||||
jq -n \
|
||||
--arg message "$COMMIT_MSG" \
|
||||
--arg branch "$BRANCH" \
|
||||
--arg sha "$REMOTE_SHA" \
|
||||
--rawfile content "$CONTENT_TMP_BASE64" \
|
||||
'{
|
||||
message: $message,
|
||||
content: $content,
|
||||
branch: $branch
|
||||
} + (if ($sha != "" and $sha != "null") then { sha: $sha } else {} end)' \
|
||||
> "$PAYLOAD_TMP"
|
||||
|
||||
UPLOAD_RESPONSE=$(curl -s -X PUT \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @"$PAYLOAD_TMP" \
|
||||
"https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}")
|
||||
|
||||
echo "Upload Response:"
|
||||
echo "$UPLOAD_RESPONSE"
|
||||
|
||||
rm -f "$CONTENT_TMP_BASE64" "$PAYLOAD_TMP"
|
||||
Generated
+29
-35
@@ -2063,7 +2063,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -2151,7 +2150,6 @@ dependencies = [
|
||||
"rand",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -2164,13 +2162,10 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -2283,6 +2278,7 @@ dependencies = [
|
||||
"base64",
|
||||
"dirs",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
"graphite-wasm-wrapper",
|
||||
"image",
|
||||
@@ -3504,10 +3500,10 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"log",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -3716,6 +3712,7 @@ dependencies = [
|
||||
"proc-macro-error2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strum",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
@@ -4112,7 +4109,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"smallvec",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -4623,18 +4619,6 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
|
||||
|
||||
[[package]]
|
||||
name = "raster-kernels"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
@@ -4648,13 +4632,11 @@ dependencies = [
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
@@ -4676,7 +4658,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
"wgpu",
|
||||
@@ -4844,7 +4825,6 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
@@ -5637,6 +5617,27 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
|
||||
dependencies = [
|
||||
"strum_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
@@ -5783,13 +5784,13 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"ipsum",
|
||||
"log",
|
||||
"node-macro",
|
||||
"parley",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"thiserror 2.0.18",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
"unicode-segmentation",
|
||||
@@ -6189,7 +6190,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"rand",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -6451,7 +6451,6 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
@@ -6481,7 +6480,6 @@ dependencies = [
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -6490,7 +6488,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -6505,7 +6503,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -6519,7 +6517,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -6970,15 +6968,11 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.18",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
|
||||
+5
-4
@@ -84,7 +84,6 @@ core-types = { path = "node-graph/libraries/core-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
@@ -242,6 +241,7 @@ tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
@@ -252,6 +252,7 @@ rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
@@ -281,6 +282,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
+1
-4
@@ -111,10 +111,7 @@ impl App {
|
||||
loop {
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
|
||||
if start_render_receiver.recv_timeout(timeout).is_err() {
|
||||
node_runtime.begin_frame();
|
||||
}
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ gpu = ["graphite-editor/gpu"]
|
||||
# Local dependencies
|
||||
graphite-editor = { workspace = true }
|
||||
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
@@ -64,7 +63,7 @@ impl DesktopWrapper {
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
|
||||
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
|
||||
@@ -158,14 +158,6 @@ impl<L: Layout> Gdd<L> {
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
|
||||
// The facts name revs, so a copy without the history carries none.
|
||||
if options.include_history && !self.metadata.is_empty() {
|
||||
let mut lines = Vec::new();
|
||||
for fact in self.metadata.facts() {
|
||||
METADATA_CODEC.append(&mut lines, fact)?;
|
||||
}
|
||||
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &lines)?;
|
||||
}
|
||||
|
||||
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
|
||||
|
||||
|
||||
@@ -35,15 +35,6 @@ pub async fn iter<T: DeserializeOwned>(container: &AnyContainer, basename: &str,
|
||||
Ok(codec.iter::<T>(bytes.as_slice()).collect::<Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
/// Same as [`iter`] but skips the values that fail to decode.
|
||||
pub async fn iter_lenient<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<Vec<T>, ReadError> {
|
||||
let bytes = read_bytes(container, basename, codec).await?;
|
||||
let values = codec
|
||||
.iter::<T>(bytes.as_slice())
|
||||
.filter_map(|value| value.inspect_err(|error| log::warn!("Skipping an unreadable entry of {basename}: {error}")).ok());
|
||||
Ok(values.collect())
|
||||
}
|
||||
|
||||
/// Whether `{basename}.{ext}` exists for the given codec.
|
||||
pub async fn exists(container: &AnyContainer, basename: &str, codec: Codec) -> bool {
|
||||
container.exists(&path_for(basename, codec)).await
|
||||
|
||||
@@ -12,7 +12,6 @@ pub trait Layout {
|
||||
fn registry_basename(&self) -> &str;
|
||||
fn history_basename(&self) -> &str;
|
||||
fn hot_log_basename(&self) -> &str;
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
@@ -40,9 +39,6 @@ impl Layout for GddV1Layout {
|
||||
fn hot_log_basename(&self) -> &str {
|
||||
"hot-log"
|
||||
}
|
||||
fn metadata_basename(&self) -> &str {
|
||||
"metadata"
|
||||
}
|
||||
fn resources_dir(&self) -> &str {
|
||||
"resources"
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOp, PeerId, Registry, Session, UserId};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -52,8 +52,6 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
|
||||
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
/// One fact per line, so recording one only appends.
|
||||
pub const METADATA_CODEC: Codec = Codec::JsonLines;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
@@ -77,8 +75,6 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
/// and synchronous.
|
||||
pub(crate) manifest: Manifest,
|
||||
/// See [`HistoryMetadata`].
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
@@ -140,10 +136,6 @@ impl<L: Layout> Gdd<L> {
|
||||
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
|
||||
false => SessionState::default(),
|
||||
};
|
||||
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
|
||||
true => HistoryMetadata::fold(io::iter_lenient(&working, layout.metadata_basename(), METADATA_CODEC).await?),
|
||||
false => HistoryMetadata::default(),
|
||||
};
|
||||
|
||||
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
@@ -181,7 +173,6 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
metadata,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
})
|
||||
}
|
||||
@@ -208,7 +199,6 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
metadata: HistoryMetadata::default(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, Rev, Subject, TimeStamp, Value, WallStamp};
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
@@ -182,25 +182,6 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> &HistoryMetadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// State a fact at wall time `wall_ms`, taken on only once it is on disk. Returns whether it changed anything.
|
||||
pub fn record(&mut self, subject: Subject, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.statement(subject, key, value, stamp) else { return Ok(false) };
|
||||
// The leading newline keeps the fact off a tail a crash left unterminated. Reading skips the blank lines this leaves.
|
||||
let mut line = vec![b'\n'];
|
||||
METADATA_CODEC.append(&mut line, &fact)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &line)?;
|
||||
self.metadata.absorb(fact);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{GddV1, GddV1Layout, Layout};
|
||||
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
const ADA: Subject = Subject::User(UserId(10));
|
||||
|
||||
fn document_naming_ada() -> GddV1 {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
gdd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_facts_survive_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document_naming_ada();
|
||||
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = document_naming_ada();
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
futures::executor::block_on(async {
|
||||
let (working, layout) = document_naming_ada().into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
|
||||
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
|
||||
});
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
//! What people say about a document's history, kept beside it rather than in it: user names, step labels
|
||||
//! and tags. None of it is folded into the document, so moving the head never changes it and stating it
|
||||
//! never rewrites a delta.
|
||||
|
||||
use crate::ids::{PeerId, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct WallStamp {
|
||||
pub ms: u64,
|
||||
pub peer: PeerId,
|
||||
}
|
||||
|
||||
/// What a fact is about. A rev stands for the interaction it closes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Subject {
|
||||
User(UserId),
|
||||
Rev(Rev),
|
||||
}
|
||||
|
||||
/// One statement about a subject, and one line of the metadata file.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MetadataFact {
|
||||
pub subject: Subject,
|
||||
pub key: String,
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a user.
|
||||
pub mod user_attr {
|
||||
/// The display name the user chose. Absent or empty means unnamed.
|
||||
pub const NAME: &str = "name";
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a rev.
|
||||
pub mod rev_attr {
|
||||
/// The name a person gave the interaction. Absent or empty means unnamed.
|
||||
pub const LABEL: &str = "label";
|
||||
/// Prefixes each tag's name to form its key. The value is `true` while the tag stands and `false` once removed.
|
||||
pub const TAG_PREFIX: &str = "tag:";
|
||||
}
|
||||
|
||||
/// The standing fact for each subject and key. Folding the same facts in any order gives the same record.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HistoryMetadata {
|
||||
facts: BTreeMap<Subject, BTreeMap<String, MetadataFact>>,
|
||||
}
|
||||
|
||||
impl HistoryMetadata {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.facts.is_empty()
|
||||
}
|
||||
|
||||
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
|
||||
let mut record = Self::default();
|
||||
for fact in facts {
|
||||
record.absorb(fact);
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
pub fn facts(&self) -> impl Iterator<Item = &MetadataFact> {
|
||||
self.facts.values().flat_map(BTreeMap::values)
|
||||
}
|
||||
|
||||
fn standing(&self, subject: Subject, key: &str) -> Option<&MetadataFact> {
|
||||
self.facts.get(&subject)?.get(key)
|
||||
}
|
||||
|
||||
fn text(&self, subject: Subject, key: &str) -> Option<&str> {
|
||||
self.standing(subject, key)?.value.as_str().filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
pub fn user_name(&self, user: UserId) -> Option<&str> {
|
||||
self.text(Subject::User(user), user_attr::NAME)
|
||||
}
|
||||
|
||||
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
|
||||
self.text(Subject::Rev(rev), rev_attr::LABEL)
|
||||
}
|
||||
|
||||
/// The tags standing on `rev`, in name order.
|
||||
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
|
||||
let Some(attributes) = self.facts.get(&Subject::Rev(rev)) else { return Vec::new() };
|
||||
attributes
|
||||
.values()
|
||||
.filter(|fact| fact.value == true)
|
||||
.filter_map(|fact| fact.key.strip_prefix(rev_attr::TAG_PREFIX))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fact that would state `value`, stamped after the one it replaces so a clock behind a peer's still wins.
|
||||
/// `None` when the value already stands, or when the standing stamp is at the end of time and can't be outdone.
|
||||
pub fn statement(&self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
|
||||
if let Some(standing) = self.standing(subject, key) {
|
||||
if standing.value == value {
|
||||
return None;
|
||||
}
|
||||
if stamp <= standing.stamp {
|
||||
stamp.ms = standing.stamp.ms.checked_add(1)?;
|
||||
}
|
||||
}
|
||||
let key = key.to_string();
|
||||
Some(MetadataFact { subject, key, value, stamp })
|
||||
}
|
||||
|
||||
/// Take on a fact unless the standing one has a later stamp, or the same stamp and a value that encodes no lower.
|
||||
pub fn absorb(&mut self, fact: MetadataFact) {
|
||||
let attributes = self.facts.entry(fact.subject).or_default();
|
||||
let stands = |mine: &MetadataFact| mine.stamp.cmp(&fact.stamp).then_with(|| mine.value.to_string().cmp(&fact.value.to_string())).is_ge();
|
||||
if !attributes.get(&fact.key).is_some_and(stands) {
|
||||
attributes.insert(fact.key.clone(), fact);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ADA: Subject = Subject::User(UserId(1));
|
||||
|
||||
fn stamp(ms: u64) -> WallStamp {
|
||||
WallStamp { ms, peer: PeerId(1) }
|
||||
}
|
||||
|
||||
fn fact(subject: Subject, key: &str, value: impl Into<serde_json::Value>, ms: u64) -> MetadataFact {
|
||||
MetadataFact {
|
||||
subject,
|
||||
key: key.into(),
|
||||
value: value.into(),
|
||||
stamp: stamp(ms),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn facts_settle_alike_whatever_order_they_meet_in() {
|
||||
let name = |value, ms| fact(ADA, user_attr::NAME, value, ms);
|
||||
let later = HistoryMetadata::fold([name("Bea", 20), name("Ada", 10)]);
|
||||
assert_eq!(later, HistoryMetadata::fold([name("Ada", 10), name("Bea", 20)]));
|
||||
assert_eq!(later.user_name(UserId(1)), Some("Bea"));
|
||||
assert_eq!(HistoryMetadata::fold([name("Ada", 10), name("Bea", 10)]), HistoryMetadata::fold([name("Bea", 10), name("Ada", 10)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_behind_a_peers_still_gets_its_say() {
|
||||
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "Ada", 100)]);
|
||||
let stated = record.statement(ADA, user_attr::NAME, "Countess".into(), stamp(5)).expect("a change");
|
||||
assert_eq!(stated.stamp.ms, 101);
|
||||
assert!(record.statement(ADA, user_attr::NAME, "Ada".into(), stamp(500)).is_none(), "the same value is no change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_names_and_removed_tags_do_not_read_back() {
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
let subject = Subject::Rev(step);
|
||||
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "", 1), fact(subject, "tag:v1", true, 1), fact(subject, "tag:draft", false, 1)]);
|
||||
assert_eq!(record.user_name(UserId(1)), None);
|
||||
assert_eq!(record.rev_tags(step), vec!["v1"]);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
pub mod history;
|
||||
mod history_metadata;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
@@ -26,7 +25,6 @@ pub use attributes::*;
|
||||
pub use crdt::*;
|
||||
pub use document::*;
|
||||
pub use history::History;
|
||||
pub use history_metadata::{HistoryMetadata, MetadataFact, Subject, WallStamp, rev_attr, user_attr};
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
|
||||
+11
-28
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Clock, Scheduling, Spawn, Spawner};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
clock: Arc<dyn Clock>,
|
||||
scheduling: Scheduling,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new(clock: Arc<dyn Clock>) -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
application_io: (),
|
||||
clock,
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
pub fn new() -> Self {
|
||||
Self { wake: (), application_io: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A> RuntimeBuilder<W, A> {
|
||||
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
|
||||
Self { scheduling, ..self }
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,7 @@ mod tests {
|
||||
|
||||
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
|
||||
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
|
||||
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{file_type:?} should read back: {error}"));
|
||||
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
|
||||
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
|
||||
|
||||
// Only JPG lacks transparency, so it lands on white
|
||||
|
||||
@@ -32,7 +32,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -776,45 +776,6 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -1242,10 +1203,6 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1416,12 +1373,6 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -315,9 +315,6 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1877,14 +1877,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
|
||||
@@ -759,26 +759,20 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -611,7 +611,10 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::scope(raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string()),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
@@ -623,13 +626,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
@@ -834,7 +837,6 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,7 +388,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -439,9 +438,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -3001,79 +2997,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
scene: VelloSceneBuilder,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
@@ -1179,7 +1179,7 @@ impl OverlayContextInternal {
|
||||
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
|
||||
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
|
||||
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
|
||||
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false).unwrap_or_default();
|
||||
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
|
||||
(text_size, text_list)
|
||||
});
|
||||
let text_width = text_size.x;
|
||||
|
||||
@@ -51,8 +51,6 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -349,22 +347,21 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
|
||||
/// bounds for non-vector layers (groups, raster, text, color, gradient).
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
if let Some(item) = self.layer_vector_data.get(&layer) {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
.get(&layer)
|
||||
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
|
||||
.map(graphene_std::Coverage::stroke_params);
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
if let Some(bounds) = item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) {
|
||||
return Some(bounds);
|
||||
}
|
||||
}
|
||||
self.bounding_box_document(layer)
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
@@ -720,26 +717,6 @@ pub struct NodeRelations {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stroked_bounds_include_the_items_after_the_first() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
let line = |from: f64, to: f64| {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((from, 0.));
|
||||
path.line_to((to, 0.));
|
||||
path
|
||||
};
|
||||
|
||||
// Only the first item is recorded as vector data, while click targets cover every item
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
metadata.layer_vector_data.insert(layer, Arc::new(Vector::item_from_bezpath(&line(0., 10.))));
|
||||
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
|
||||
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
|
||||
@@ -50,7 +50,7 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graph_craft::document::{DefinitionId, DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::registry::MULTI_OUTPUT_NODES;
|
||||
@@ -140,9 +140,6 @@ impl NodeNetworkInterface {
|
||||
pub fn migrate_path_modify_node(&mut self) {
|
||||
self.migrate_graph(fix_network);
|
||||
fn fix_network(network: &mut NodeNetwork) {
|
||||
for definition in network.definitions.values_mut() {
|
||||
fix_network(definition);
|
||||
}
|
||||
for node in network.nodes.values_mut() {
|
||||
if let Some(network) = node.implementation.get_network_mut() {
|
||||
fix_network(network);
|
||||
@@ -195,7 +192,7 @@ mod network_interface_tests {
|
||||
fn instance_paths_resolve_through_the_definitions_table() {
|
||||
use super::*;
|
||||
|
||||
let definition = NetworkId(1);
|
||||
let definition = DefinitionId(1);
|
||||
let instance = |implementation| DocumentNode { implementation, ..Default::default() };
|
||||
let instances = [NodeId(10), NodeId(11)];
|
||||
|
||||
@@ -210,14 +207,12 @@ mod network_interface_tests {
|
||||
definition_metadata.persistent_metadata.node_metadata.insert(NodeId(0), DocumentNodeMetadata::default());
|
||||
|
||||
let mut network_metadata = NodeNetworkMetadata::default();
|
||||
let mut instance_metadata = DocumentNodeMetadata::default();
|
||||
instance_metadata.persistent_metadata.output_names = vec![String::new()];
|
||||
for id in instances {
|
||||
network_metadata.persistent_metadata.node_metadata.insert(id, instance_metadata.clone());
|
||||
network_metadata.persistent_metadata.node_metadata.insert(id, DocumentNodeMetadata::default());
|
||||
}
|
||||
network_metadata.persistent_metadata.definitions.insert(definition, definition_metadata);
|
||||
|
||||
let interface = NodeNetworkInterface::from_trees(network.clone(), network_metadata.clone());
|
||||
let interface = NodeNetworkInterface::from_trees(network, network_metadata);
|
||||
|
||||
let paths = instances.map(|id| [id]);
|
||||
let views = paths.each_ref().map(|path| interface.view(path).unwrap());
|
||||
@@ -229,28 +224,5 @@ mod network_interface_tests {
|
||||
assert_eq!(document_view.reference(&NodeId(10)), Ok(Some(DefinitionIdentifier::Network("Artboard".into()))));
|
||||
assert_eq!(document_view.number_of_outputs(&NodeId(10)), Ok(1));
|
||||
assert_eq!(interface.validate_invariants(), Vec::<String>::new());
|
||||
|
||||
let unused = NetworkId(2);
|
||||
let mut network_with_unused = network.clone();
|
||||
network_with_unused
|
||||
.definitions
|
||||
.insert(unused, NodeNetwork::value_network(instance(DocumentNodeImplementation::default())));
|
||||
let mut metadata_with_unused = network_metadata.clone();
|
||||
metadata_with_unused.persistent_metadata.definitions.insert(unused, NodeNetworkMetadata::default());
|
||||
let with_unused = NodeNetworkInterface::from_trees(network_with_unused, metadata_with_unused);
|
||||
assert_eq!(with_unused.validate_invariants(), vec!["Node 0 in network [] has no metadata entry".to_string()]);
|
||||
|
||||
let mut mismatched_network = network;
|
||||
mismatched_network.nodes.get_mut(&NodeId(11)).unwrap().inputs.push(NodeInput::value(TaggedValue::None, false));
|
||||
network_metadata
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.get_mut(&NodeId(11))
|
||||
.unwrap()
|
||||
.persistent_metadata
|
||||
.input_metadata
|
||||
.push(InputMetadata::default());
|
||||
let mismatched = NodeNetworkInterface::from_trees(mismatched_network, network_metadata);
|
||||
assert_eq!(mismatched.validate_invariants().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -970,11 +970,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -991,17 +991,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
-16
@@ -737,22 +737,6 @@ mod tests {
|
||||
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
|
||||
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
|
||||
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
|
||||
|
||||
assert!(
|
||||
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
|
||||
"a CPU raster should upload through the input adapter"
|
||||
);
|
||||
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
|
||||
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
|
||||
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_promote_onto_list_inputs() {
|
||||
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
|
||||
|
||||
@@ -200,9 +200,4 @@ impl NodeNetworkInterface {
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ impl Default for NodeTemplate {
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum NodeTemplateImplementation {
|
||||
Network(NodeNetworkTemplate),
|
||||
Definition(NetworkId),
|
||||
Definition(DefinitionId),
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
Extract,
|
||||
}
|
||||
|
||||
@@ -580,7 +580,7 @@ pub struct NodeNetworkPersistentMetadata {
|
||||
#[serde(skip)]
|
||||
pub selection_redo_history: VecDeque<SelectedNodes>,
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub definitions: HashMap<NetworkId, NodeNetworkMetadata>,
|
||||
pub definitions: HashMap<DefinitionId, NodeNetworkMetadata>,
|
||||
}
|
||||
|
||||
/// A lazily computed cache slot whose load and read paths work through &self, with interior mutability guarding the stored value.
|
||||
@@ -1137,9 +1137,6 @@ pub(crate) fn visit_network_resources(network: &NodeNetwork, visit: &mut impl Fn
|
||||
for node in network.nodes.values() {
|
||||
visit_node_resources(node, visit);
|
||||
}
|
||||
for definition in network.definitions.values() {
|
||||
visit_network_resources(definition, visit);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn visit_node_resources(node: &DocumentNode, visit: &mut impl FnMut(ResourceId)) {
|
||||
@@ -1195,37 +1192,6 @@ mod tests {
|
||||
assert_eq!(visits.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_visits_reach_each_definition_once() {
|
||||
let definition = NetworkId(1);
|
||||
let used = ResourceId::from(1);
|
||||
let instance = || DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(definition),
|
||||
..Default::default()
|
||||
};
|
||||
let body = NodeNetwork {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Resource(used), false)],
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), instance()), (NodeId(2), instance())].into_iter().collect(),
|
||||
definitions: [(definition, body)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut visits = Vec::new();
|
||||
visit_network_resources(&network, &mut |id| visits.push(id));
|
||||
assert_eq!(visits, vec![used]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_click_targets_reach_around_the_connector_where_wires_attach() {
|
||||
let center = DVec2::new(100., 50.);
|
||||
|
||||
+14
-86
@@ -1,5 +1,5 @@
|
||||
use super::{InputConnector, NodeNetworkInterface, NodeNetworkMetadata};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::document::{DefinitionId, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
@@ -9,44 +9,12 @@ impl NodeNetworkInterface {
|
||||
// O(nodes + wires) summed across all nesting levels, plus an acyclicity walk per network
|
||||
pub fn validate_invariants(&self) -> Vec<String> {
|
||||
let mut violations = Vec::new();
|
||||
self.validate_definition_tables(&mut violations);
|
||||
|
||||
let mut root = DocumentRoot {
|
||||
network: self.document_network(),
|
||||
metadata: &self.network_metadata,
|
||||
definition_import_counts: HashMap::new(),
|
||||
};
|
||||
validate_network(&mut root, self.document_network(), &self.network_metadata, &mut Vec::new(), Some(0), &mut violations);
|
||||
|
||||
for (id, definition) in &self.document_network().definitions {
|
||||
if root.definition_import_counts.contains_key(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(definition_metadata) = self.network_metadata.persistent_metadata.definitions.get(id) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
root.definition_import_counts.insert(*id, None);
|
||||
validate_network(&mut root, definition, definition_metadata, &mut Vec::new(), None, &mut violations);
|
||||
}
|
||||
validate_network(self.document_network(), self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
|
||||
self.validate_outward_wires(&mut Vec::new(), &mut HashSet::new(), &mut violations);
|
||||
self.validate_dots_stay_on_wires(&mut violations);
|
||||
violations
|
||||
}
|
||||
|
||||
/// The definitions table and its metadata table must contain exactly the same definitions.
|
||||
fn validate_definition_tables(&self, violations: &mut Vec<String>) {
|
||||
let definitions = &self.document_network().definitions;
|
||||
let definition_metadata = &self.network_metadata.persistent_metadata.definitions;
|
||||
|
||||
for id in definitions.keys().filter(|id| !definition_metadata.contains_key(id)) {
|
||||
violations.push(format!("Definition {id:?} has no metadata entry"));
|
||||
}
|
||||
for id in definition_metadata.keys().filter(|id| !definitions.contains_key(id)) {
|
||||
violations.push(format!("Metadata entry for definition {id:?} has no corresponding definition"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A redirect dot an edit took a wire from must be gone by the time the edit is done if that left it orphaned.
|
||||
fn validate_dots_stay_on_wires(&self, violations: &mut Vec<String>) {
|
||||
for (network_path, lost_wires) in &self.dots_that_lost_a_wire {
|
||||
@@ -57,7 +25,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// A loaded outward wire cache must match a fresh computation from the network.
|
||||
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, validated_definitions: &mut HashSet<NetworkId>, violations: &mut Vec<String>) {
|
||||
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, validated_definitions: &mut HashSet<DefinitionId>, violations: &mut Vec<String>) {
|
||||
let Some(network) = self.nested_network(path) else { return };
|
||||
|
||||
if let Some(computed) = self.compute_outward_wires(path)
|
||||
@@ -100,15 +68,7 @@ fn wire_counts(inputs: &[InputConnector]) -> HashMap<InputConnector, usize> {
|
||||
counts
|
||||
}
|
||||
|
||||
struct DocumentRoot<'a> {
|
||||
network: &'a NodeNetwork,
|
||||
metadata: &'a NodeNetworkMetadata,
|
||||
definition_import_counts: HashMap<NetworkId, Option<usize>>,
|
||||
}
|
||||
|
||||
fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: Option<usize>, violations: &mut Vec<String>) {
|
||||
let (document_network, document_metadata) = (root.network, root.metadata);
|
||||
|
||||
fn validate_network(document_network: &NodeNetwork, network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: usize, violations: &mut Vec<String>) {
|
||||
let node_metadata = &network_metadata.persistent_metadata.node_metadata;
|
||||
|
||||
// The network and its metadata tree must contain exactly the same set of nodes
|
||||
@@ -139,12 +99,8 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
NodeInput::Import { import_index, .. } => {
|
||||
if let Some(import_count) = import_count
|
||||
&& *import_index >= import_count
|
||||
{
|
||||
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
|
||||
}
|
||||
NodeInput::Import { import_index, .. } if *import_index >= import_count => {
|
||||
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
@@ -175,22 +131,19 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
|
||||
));
|
||||
}
|
||||
|
||||
let validate_output_names = |export_count: usize, violations: &mut Vec<String>| {
|
||||
if persistent.output_names.len() != export_count {
|
||||
violations.push(format!(
|
||||
"Node {node_id} in network {path:?} has {export_count} exports but {} output names",
|
||||
persistent.output_names.len()
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Nested network metadata must exist exactly for nodes implemented as networks
|
||||
match (&node.implementation, &persistent.network_metadata) {
|
||||
(DocumentNodeImplementation::Network(nested_network), Some(nested_metadata)) => {
|
||||
validate_output_names(nested_network.exports.len(), violations);
|
||||
if persistent.output_names.len() != nested_network.exports.len() {
|
||||
violations.push(format!(
|
||||
"Node {node_id} in network {path:?} has {} exports but {} output names",
|
||||
nested_network.exports.len(),
|
||||
persistent.output_names.len()
|
||||
));
|
||||
}
|
||||
|
||||
path.push(*node_id);
|
||||
validate_network(root, nested_network, nested_metadata, path, Some(node.inputs.len()), violations);
|
||||
validate_network(document_network, nested_network, nested_metadata, path, node.inputs.len(), violations);
|
||||
path.pop();
|
||||
}
|
||||
(DocumentNodeImplementation::Network(_), None) => {
|
||||
@@ -199,31 +152,6 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
|
||||
(_, Some(_)) => {
|
||||
violations.push(format!("Non-network node {node_id} in network {path:?} has nested network metadata"));
|
||||
}
|
||||
(DocumentNodeImplementation::Definition(id), None) => {
|
||||
let Some(definition) = document_network.definitions.get(id) else {
|
||||
violations.push(format!("Node {node_id} in network {path:?} references nonexistent definition {id:?}"));
|
||||
continue;
|
||||
};
|
||||
validate_output_names(definition.exports.len(), violations);
|
||||
|
||||
match root.definition_import_counts.get(id) {
|
||||
Some(&Some(validated_import_count)) if validated_import_count != node.inputs.len() => violations.push(format!(
|
||||
"Node {node_id} in network {path:?} has {} inputs but another instance of definition {id:?} has {validated_import_count}",
|
||||
node.inputs.len()
|
||||
)),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
root.definition_import_counts.insert(*id, Some(node.inputs.len()));
|
||||
|
||||
let Some(definition_metadata) = document_metadata.persistent_metadata.definitions.get(id) else {
|
||||
continue;
|
||||
};
|
||||
path.push(*node_id);
|
||||
validate_network(root, definition, definition_metadata, path, Some(node.inputs.len()), violations);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
(_, None) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,11 +16,12 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::RedGreenBlueAlpha;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -299,6 +300,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -493,6 +498,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::BlackAndWhiteNode",
|
||||
"graphene_core::raster::adjustments::BlackAndWhiteNode",
|
||||
"graphene_core::raster::BlackAndWhiteNode",
|
||||
"raster_nodes::adjustments::black_and_white_shader_node::BlackAndWhiteShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -508,8 +514,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -518,7 +524,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::BrightnessContrastNode",
|
||||
"graphene_raster_nodes::adjustments::brightness_contrast_classic",
|
||||
"graphene_raster_nodes::adjustments::BrightnessContrastClassicNode",
|
||||
"raster_nodes::adjustments::BrightnessContrastClassicNode",
|
||||
"raster_nodes::adjustments::brightness_contrast_shader_node::BrightnessContrastShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -527,11 +533,15 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::ChannelMixerNode",
|
||||
"graphene_core::raster::adjustments::ChannelMixerNode",
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
"raster_nodes::adjustments::channel_mixer_shader_node::ChannelMixerShaderNodeNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::adjustments::color_balance::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::color_balance_shader_node::ColorBalanceShaderNodeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -539,7 +549,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::color_overlay_shader_node::ColorOverlayShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -560,6 +570,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::ExposureNode",
|
||||
"graphene_core::raster::adjustments::ExposureNode",
|
||||
"graphene_core::raster::ExposureNode",
|
||||
"raster_nodes::adjustments::exposure_shader_node::ExposureShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -568,7 +579,11 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::GammaCorrectionNode",
|
||||
"graphene_core::raster::adjustments::GammaCorrectionNode",
|
||||
"raster_nodes::adjustments::gamma_correction_shader_node::GammaCorrectionShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gradient_map::IDENTIFIER,
|
||||
@@ -587,6 +602,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::HueSaturationNode",
|
||||
"graphene_core::raster::adjustments::HueSaturationNode",
|
||||
"graphene_core::raster::HueSaturationNode",
|
||||
"raster_nodes::adjustments::hue_saturation_shader_node::HueSaturationShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -612,6 +628,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::InvertNode",
|
||||
"graphene_core::raster::InvertNode",
|
||||
"graphene_core::raster::InvertRGBNode",
|
||||
"raster_nodes::adjustments::invert_shader_node::InvertShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -620,6 +637,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::LevelsNode",
|
||||
"graphene_core::raster::adjustments::LevelsNode",
|
||||
"graphene_core::raster::LevelsNode",
|
||||
"raster_nodes::adjustments::levels_shader_node::LevelsShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -629,6 +647,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::LuminanceNode",
|
||||
"graphene_core::raster::adjustments::LuminanceNode",
|
||||
"graphene_core::raster::LuminanceNode",
|
||||
"raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -637,6 +656,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::MakeOpaqueNode",
|
||||
"graphene_core::raster::adjustments::MakeOpaqueNode",
|
||||
"graphene_core::raster::ExtractOpaqueNode",
|
||||
"raster_nodes::adjustments::make_opaque_shader_node::MakeOpaqueShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -647,12 +667,17 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::photo_filter::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::photo_filter_shader_node::PhotoFilterShaderNodeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::PosterizeNode",
|
||||
"graphene_core::raster::adjustments::PosterizeNode",
|
||||
"graphene_core::raster::PosterizeNode",
|
||||
"raster_nodes::adjustments::posterize_shader_node::PosterizeShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -661,7 +686,11 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::selective_color::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::SelectiveColorNode", "graphene_core::raster::adjustments::SelectiveColorNode"],
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::SelectiveColorNode",
|
||||
"graphene_core::raster::adjustments::SelectiveColorNode",
|
||||
"raster_nodes::adjustments::selective_color_shader_node::SelectiveColorShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER,
|
||||
@@ -669,6 +698,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::ThresholdNode",
|
||||
"graphene_core::raster::adjustments::ThresholdNode",
|
||||
"graphene_core::raster::ThresholdNode",
|
||||
"raster_nodes::adjustments::threshold_shader_node::ThresholdShaderNodeNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -677,6 +707,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_raster_nodes::adjustments::VibranceNode",
|
||||
"graphene_core::raster::adjustments::VibranceNode",
|
||||
"graphene_core::raster::VibranceNode",
|
||||
"raster_nodes::adjustments::vibrance_shader_node::VibranceShaderNodeNode",
|
||||
],
|
||||
},
|
||||
// ================================
|
||||
@@ -1195,49 +1226,11 @@ fn is_monitored_transform_subgraph(node: &DocumentNode) -> bool {
|
||||
monitor_reads_first_import && transform_reads_monitor_and_other_imports && exports_transform
|
||||
}
|
||||
|
||||
/// The CPU node a removed GPU twin was generated from, as named in its era, like `raster_nodes::adjustments::InvertNode` for `raster_nodes::adjustments::invert_shader_node::InvertShaderNodeNode`.
|
||||
fn cpu_node_of_gpu_twin(identifier: &str) -> Option<String> {
|
||||
let identifier = identifier.split('<').next()?;
|
||||
let (module_path, struct_name) = identifier.rsplit_once("::")?;
|
||||
let (parent_module_path, twin_module) = module_path.rsplit_once("::")?;
|
||||
let cpu_struct_name = struct_name.strip_suffix("ShaderNodeNode")?;
|
||||
|
||||
twin_module.ends_with("_shader_node").then(|| format!("{parent_module_path}::{cpu_struct_name}Node"))
|
||||
}
|
||||
|
||||
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
|
||||
document.network_interface.migrate_path_modify_node();
|
||||
document.network_interface.migrate_rewired_previews();
|
||||
document.network_interface.normalize_stored_types();
|
||||
|
||||
// The removed GPU twins become their CPU nodes minus the trailing executor input, so the renames below carry them forward like their era's CPU nodes
|
||||
let gpu_twins = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
let kept_input_count = node.inputs.len().saturating_sub(1);
|
||||
Some((*node_id, path, cpu_node_of_gpu_twin(identifier.as_str())?, node.inputs[..kept_input_count].to_vec()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, cpu_identifier, inputs) in gpu_twins {
|
||||
let input_metadata = document
|
||||
.network_interface
|
||||
.node_metadata(&node_id, &network_path)
|
||||
.map(|metadata| metadata.persistent_metadata.input_metadata.iter().take(inputs.len()).cloned().collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::with_owned_string(cpu_identifier)),
|
||||
inputs,
|
||||
input_metadata,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_implementation(&node_id, &network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(&node_id, &network_path, &mut node_template);
|
||||
}
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
|
||||
// Apply string and node replacements to each node
|
||||
@@ -1270,10 +1263,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
|
||||
}
|
||||
|
||||
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1636,49 +1625,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1903,6 +1849,35 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
|
||||
}
|
||||
|
||||
let cpu_raster_type_defaults: Vec<(NodeId, Vec<NodeId>, usize, Type, bool)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.flat_map(|(node_id, node, path)| {
|
||||
node.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, input)| {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let TaggedValue::TypeDefault(stored_type) = &**tagged_value else { return None };
|
||||
let gpu_type = if *stored_type == item!(Raster<CPU>) {
|
||||
item!(Raster<GPU>)
|
||||
} else if *stored_type == list!(Raster<CPU>) {
|
||||
list!(Raster<GPU>)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some((*node_id, path.clone(), index, gpu_type, *exposed))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, index, gpu_type, exposed) in cpu_raster_type_defaults {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::type_default(gpu_type, exposed), &network_path);
|
||||
}
|
||||
|
||||
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
|
||||
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
|
||||
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
|
||||
@@ -2440,6 +2415,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -3530,18 +3506,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
|
||||
}
|
||||
|
||||
// Load Image's URL is empty until set, it used to be `graphite:null`
|
||||
if reference == DefinitionIdentifier::Network("Load Image".into())
|
||||
&& let Some(url) = node.inputs.get(1)
|
||||
&& matches!(url.as_value(), Some(TaggedValue::String(url)) if url == "graphite:null")
|
||||
{
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 1),
|
||||
NodeInput::value(TaggedValue::String(String::new()), url.is_exposed()),
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
|
||||
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
|
||||
for (i, input) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Scope(name) = input
|
||||
@@ -3579,16 +3543,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
photo_filter::IDENTIFIER,
|
||||
color_lookup::IDENTIFIER,
|
||||
image_to_channels::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
|
||||
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::image::IDENTIFIER,
|
||||
graphene_std::platform_application_io::bytes_to_image::IDENTIFIER,
|
||||
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
|
||||
graphene_std::platform_application_io::rasterize::IDENTIFIER,
|
||||
]
|
||||
@@ -3708,11 +3674,11 @@ fn modifications_following_turned_segments(network: &graph_craft::document::Node
|
||||
};
|
||||
|
||||
// Where the output comes from: the node itself, or the nodes a network node exports
|
||||
let sources: Vec<Location> = match network.implementation_network(&origin_node.implementation) {
|
||||
Some(nested) => (0..nested.exports.len())
|
||||
let sources: Vec<Location> = match &origin_node.implementation {
|
||||
DocumentNodeImplementation::Network(nested) => (0..nested.exports.len())
|
||||
.filter_map(|output| producing_node(network, origin_path, &NodeInput::node(*origin_id, output), 0))
|
||||
.collect(),
|
||||
None => vec![origin.clone()],
|
||||
_ => vec![origin.clone()],
|
||||
};
|
||||
|
||||
let mut reached = HashSet::new();
|
||||
@@ -3770,9 +3736,9 @@ fn producing_node(network: &graph_craft::document::NodeNetwork, network_path: &[
|
||||
match input {
|
||||
NodeInput::Node { node_id, output_index } => {
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
match network.implementation_network(&node.implementation) {
|
||||
Some(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
|
||||
None => Some((network_path.to_vec(), *node_id)),
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::Network(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
|
||||
_ => Some((network_path.to_vec(), *node_id)),
|
||||
}
|
||||
}
|
||||
NodeInput::Import { import_index, .. } => {
|
||||
@@ -3914,13 +3880,12 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
}
|
||||
}
|
||||
|
||||
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
|
||||
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
||||
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
||||
Some(DefinitionIdentifier::ProtoNode(identifier)) => identifier.as_str().ends_with("::UploadTextureNode"),
|
||||
None => false,
|
||||
};
|
||||
if is_upload_texture {
|
||||
// The removed Upload Texture node, in its proto node form or its old wrapper-network form, degrades to a passthrough of its content since rasters now load onto the GPU
|
||||
if matches!(
|
||||
document.network_interface.reference(node_id, network_path),
|
||||
Some(DefinitionIdentifier::ProtoNode(identifier)) if identifier.as_str().ends_with("::UploadTextureNode")
|
||||
) || matches!(document.network_interface.reference(node_id, network_path), Some(DefinitionIdentifier::Network(name)) if name == "Upload Texture")
|
||||
{
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
@@ -4140,88 +4105,6 @@ mod tests {
|
||||
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_twins_name_the_cpu_nodes_they_came_from() {
|
||||
assert_eq!(
|
||||
cpu_node_of_gpu_twin("raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode").as_deref(),
|
||||
Some(graphene_std::raster_nodes::adjustments::desaturate::IDENTIFIER.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
cpu_node_of_gpu_twin("graphene_raster_nodes::blending_nodes::color_overlay_shader_node::ColorOverlayShaderNodeNode").as_deref(),
|
||||
Some("graphene_raster_nodes::blending_nodes::ColorOverlayNode")
|
||||
);
|
||||
assert_eq!(cpu_node_of_gpu_twin(graphene_std::raster_nodes::adjustments::invert::IDENTIFIER.as_str()), None);
|
||||
}
|
||||
|
||||
// Upload Texture opens as a passthrough, and GPU twins open as the CPU nodes they were generated from, keeping their wires but not their executor input
|
||||
#[test]
|
||||
fn gpu_twins_and_upload_texture_open_as_cpu_nodes() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::raster_nodes::adjustments::desaturate;
|
||||
|
||||
let executor = || NodeInput::scope("graphene_std::platform_application_io::WgpuExecutorNode");
|
||||
let legacy_node = |identifier: &'static str, inputs: Vec<NodeInput>| NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let desaturate_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(desaturate::IDENTIFIER))
|
||||
.expect("the Desaturate definition should exist")
|
||||
.default_node_template();
|
||||
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
|
||||
let method = desaturate_template.inputs[1].clone();
|
||||
let brightness = NodeInput::value(TaggedValue::Number(25.), false);
|
||||
let contrast = NodeInput::value(TaggedValue::Number(-10.), false);
|
||||
|
||||
// Uploaded content feeds a Desaturate GPU twin, which feeds a Brightness/Contrast Classic GPU twin saved under the `raster_nodes` crate name
|
||||
let saved_nodes = [
|
||||
legacy_node("graphene_std::platform_application_io::UploadTextureNode", vec![content.clone(), executor()]),
|
||||
legacy_node(
|
||||
"raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode",
|
||||
vec![NodeInput::node(NodeId(0), 0), method.clone(), executor()],
|
||||
),
|
||||
legacy_node(
|
||||
"raster_nodes::adjustments::brightness_contrast_classic_shader_node::BrightnessContrastClassicShaderNodeNode",
|
||||
vec![NodeInput::node(NodeId(1), 0), brightness.clone(), contrast.clone(), executor()],
|
||||
),
|
||||
];
|
||||
let nodes = saved_nodes
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, node_template)| (NodeId(index as u64), node_template))
|
||||
.collect::<Vec<_>>();
|
||||
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = |index: u64| opened.network_interface.document_node(&NodeId(index), &[]).expect("the node should still exist");
|
||||
|
||||
let upload_texture = node(0);
|
||||
assert_eq!(upload_texture.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert_eq!(upload_texture.inputs, [content]);
|
||||
|
||||
let desaturate_node = node(1);
|
||||
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
|
||||
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
|
||||
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
|
||||
|
||||
let brightness_contrast = node(2);
|
||||
assert_eq!(
|
||||
brightness_contrast.implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER)
|
||||
);
|
||||
assert_eq!(brightness_contrast.inputs[..3], [NodeInput::node(NodeId(1), 0), brightness, contrast]);
|
||||
assert_eq!(
|
||||
brightness_contrast.inputs[3],
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
"the Classic twin should turn on the Use Classic toggle"
|
||||
);
|
||||
}
|
||||
|
||||
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
|
||||
#[test]
|
||||
fn every_into_group_alias_resets_the_merge_definition() {
|
||||
@@ -4684,7 +4567,7 @@ mod tests {
|
||||
migrate(&mut document);
|
||||
|
||||
let image_node = &document.network_interface.document_network().nodes[&image_id];
|
||||
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
|
||||
assert_eq!(image_node.inputs.len(), 3, "the image node should gain its placeholder primary input and pipeline scope input");
|
||||
let migrated = &image_node.inputs[1];
|
||||
match legacy_input.as_value() {
|
||||
None => assert_eq!(migrated.as_node(), Some(upstream_id), "the wire should sit at input 1"),
|
||||
@@ -4720,51 +4603,46 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
fn cpu_raster_type_defaults_become_gpu_defaults() {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut blur_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::filter::blur::IDENTIFIER))
|
||||
.expect("the definition should exist")
|
||||
.default_node_template();
|
||||
blur_template.inputs[0] = NodeInput::type_default(item!(Raster<CPU>), true);
|
||||
document.network_interface.insert_node(node_id, blur_template, &[]);
|
||||
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[0];
|
||||
assert_eq!(
|
||||
migrated.as_value(),
|
||||
Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))),
|
||||
"the CPU raster default should become the GPU raster default"
|
||||
);
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn upload_texture_becomes_passthrough() {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)
|
||||
.expect("the definition should exist")
|
||||
.default_node_template();
|
||||
template.implementation = NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::platform_application_io::UploadTextureNode"));
|
||||
template.inputs = vec![
|
||||
NodeInput::type_default(item!(Raster<GPU>), true),
|
||||
NodeInput::scope("graphene_std::platform_application_io::WgpuExecutorNode"),
|
||||
];
|
||||
document.network_interface.insert_node(node_id, template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert_eq!(node.inputs.len(), 1, "the executor scope input should be dropped");
|
||||
assert_eq!(node.inputs[0].as_value(), Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))), "the content should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
|
||||
@@ -480,8 +480,7 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
let points = sides as u64;
|
||||
let Ok(star) = star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2) else { return };
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star)];
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
|
||||
|
||||
overlay_context.outline(targets.iter(), viewport, None);
|
||||
}
|
||||
@@ -496,8 +495,7 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
|
||||
let viewport = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
let points = sides as u64;
|
||||
let Ok(polygon) = regular_polygon_bezpath(DVec2::ZERO, points, radius) else { return };
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(polygon)];
|
||||
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
|
||||
|
||||
overlay_context.outline(targets.iter(), viewport, None);
|
||||
}
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,14 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3369,7 +3366,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3378,7 +3375,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3387,10 +3384,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -58,7 +58,7 @@ pub type NodeErrorTrace = Box<[NodePaths]>;
|
||||
pub type NodePaths = Box<[Box<[NodeId]>]>;
|
||||
|
||||
impl EvaluationErrors {
|
||||
pub(crate) fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync + 'static), &NodeErrorTrace)> {
|
||||
fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync), &NodeErrorTrace)> {
|
||||
self.0.iter().map(|(error, trace)| (&**error, trace))
|
||||
}
|
||||
}
|
||||
@@ -97,11 +97,6 @@ pub struct NodeGraphExecutor {
|
||||
node_graph_document: Option<DocumentId>,
|
||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||
previous_node_to_inspect: Vec<NodeId>,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
/// Evaluation errors of the last evaluation, used in tests
|
||||
#[cfg(test)]
|
||||
evaluation_errors: Option<EvaluationErrors>,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// In-progress one-time pre-pass that converts legacy bounding-box-relative gradients to absolute space, if any.
|
||||
gradient_migration: Option<GradientMigration>,
|
||||
@@ -109,6 +104,8 @@ pub struct NodeGraphExecutor {
|
||||
/// Documents whose gradient migration pass already ran this session, so entries that failed to measure
|
||||
/// (kept pending for a retry on the next open) don't re-run the pass on every render request.
|
||||
gradient_migration_attempted: HashSet<DocumentId>,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -143,19 +140,17 @@ impl NodeGraphExecutor {
|
||||
let node_runtime = NodeRuntime::new(request_receiver, response_sender, editor_wake);
|
||||
|
||||
let node_executor = Self {
|
||||
futures: Default::default(),
|
||||
sender: request_sender,
|
||||
receiver: response_receiver,
|
||||
futures: Default::default(),
|
||||
pending: None,
|
||||
current_execution_id: 0,
|
||||
node_graph_hash: 0,
|
||||
node_graph_document: None,
|
||||
current_execution_id: 0,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
canvas_images_sent: HashSet::new(),
|
||||
#[cfg(test)]
|
||||
evaluation_errors: None,
|
||||
gradient_migration: None,
|
||||
gradient_migration_attempted: HashSet::new(),
|
||||
pending: None,
|
||||
canvas_images_sent: HashSet::new(),
|
||||
};
|
||||
(node_executor, node_runtime)
|
||||
}
|
||||
@@ -171,12 +166,6 @@ impl NodeGraphExecutor {
|
||||
self.current_execution_id
|
||||
}
|
||||
|
||||
/// Allows the test runner to access last executions evaluation errors.
|
||||
#[cfg(test)]
|
||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
/// Execute the network by flattening it and creating a borrow stack.
|
||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||
let execution_id = self.current_execution_id;
|
||||
@@ -209,7 +198,6 @@ impl NodeGraphExecutor {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&mut network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
@@ -383,11 +371,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -505,10 +493,7 @@ impl NodeGraphExecutor {
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
path.split_last()
|
||||
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
|
||||
};
|
||||
let in_document = |path: &&[NodeId]| path.split_last().is_some_and(|(node, network)| document.network_interface.document_node(node, network).is_some());
|
||||
errors
|
||||
.iter()
|
||||
.flat_map(|(error, trace)| {
|
||||
@@ -530,28 +515,10 @@ impl NodeGraphExecutor {
|
||||
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.evaluation_errors = None;
|
||||
}
|
||||
let node_graph_output = match result {
|
||||
ExecutionResult::Pending => Ok(None),
|
||||
ExecutionResult::Value(value) => Ok(Some(value)),
|
||||
ExecutionResult::Fallback(value, _errors) => {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.evaluation_errors = Some(_errors);
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
ExecutionResult::Error(errors) => {
|
||||
let message = errors.to_string();
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.evaluation_errors = Some(errors);
|
||||
}
|
||||
Err(message)
|
||||
}
|
||||
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Ok(Some(value)),
|
||||
ExecutionResult::Error(errors) => Err(errors.to_string()),
|
||||
ExecutionResult::Panic(payload) => {
|
||||
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||
Err(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||
@@ -762,12 +729,6 @@ impl NodeGraphExecutor {
|
||||
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
|
||||
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
|
||||
let full_path: Vec<NodeId> = network_path.iter().copied().chain(std::iter::once(fill_node_id)).collect();
|
||||
if let Err(error) = network.inline_definitions() {
|
||||
log::error!("Gradient migration: could not inline the document's network definitions: {error}; dropping the pending gradient bake of fill node {fill_node_id:?}");
|
||||
remove_pending_gradient_bake(document, &network_path, fill_node_id);
|
||||
self.advance_gradient_migration(document, document_id, responses);
|
||||
return;
|
||||
}
|
||||
if !redirect_export_chain(&mut network, &full_path) {
|
||||
// The fill was deleted or is otherwise unreachable, so drop its stale entry instead of retrying it on every open
|
||||
log::warn!("Gradient migration: could not redirect the document network's export chain to fill node {fill_node_id:?}; dropping its pending gradient bake");
|
||||
@@ -959,7 +920,6 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -976,7 +936,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -1238,82 +1197,3 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod raster_input_adapter_tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
use graphene_std::Effects;
|
||||
use graphene_std::list::{ATTR_EFFECTS, Item};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::raster_nodes::adjustments::invert;
|
||||
use graphene_std::raster_nodes::dehaze::dehaze;
|
||||
use graphene_std::raster_nodes::filter::median_filter;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
|
||||
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(Image::new(4, 4, color), None).await;
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
|
||||
let mut ids = Vec::new();
|
||||
let mut previous = OutputConnector::node(image, 0);
|
||||
for (index, identifier) in nodes.iter().enumerate() {
|
||||
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
|
||||
let input = InputConnector::node_at_index(id, 0);
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
|
||||
previous = OutputConnector::node(id, 0);
|
||||
ids.push(id);
|
||||
}
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
|
||||
ids
|
||||
}
|
||||
|
||||
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
|
||||
let executor = editor.gpu_executor();
|
||||
raster.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
|
||||
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
|
||||
let reached_median: Item<Raster<CPU>> = instrumented
|
||||
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the image should arrive at Median as a CPU raster");
|
||||
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
|
||||
|
||||
// Median at its default radius passes its input through, so its output shows what the adapter gave it
|
||||
let output = instrumented
|
||||
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("Median should output a GPU raster");
|
||||
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
|
||||
let raster = read(&editor, output.into_element()).await;
|
||||
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
|
||||
|
||||
// A compile error or a failed render fails this
|
||||
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::task::{Scheduling, Spawn, Spawner, Task};
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use glam::{DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
@@ -18,15 +18,15 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::runtime::{AsyncRuntime, Clock};
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
|
||||
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use std::time::Duration;
|
||||
use thumbnails::Thumbnails;
|
||||
|
||||
mod thumbnails;
|
||||
@@ -42,15 +42,12 @@ pub struct NodeRuntime {
|
||||
receiver: Receiver<GraphRuntimeRequest>,
|
||||
sender: Sender<NodeGraphUpdate>,
|
||||
editor_wake: Wake,
|
||||
/// A re-evaluation waiting for the next frame, or for the end of an export.
|
||||
rerun: bool,
|
||||
dirty: Arc<AtomicBool>,
|
||||
pending: Option<ExecutionRequest>,
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
/// The network the executor last compiled successfully, with previews applied.
|
||||
old_graph: Option<NodeNetwork>,
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
scheduling: Scheduling,
|
||||
frame_start: Duration,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
@@ -128,14 +125,12 @@ impl NodeRuntime {
|
||||
receiver,
|
||||
sender,
|
||||
editor_wake,
|
||||
rerun: false,
|
||||
dirty: Default::default(),
|
||||
pending: None,
|
||||
pending_export: None,
|
||||
old_graph: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
scheduling: Scheduling::default(),
|
||||
frame_start: Duration::ZERO,
|
||||
|
||||
editor_api: PlatformEditorApi {
|
||||
#[cfg(not(test))]
|
||||
@@ -221,13 +216,8 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
let rerun = std::mem::take(&mut self.rerun) | self.async_runtime().take_bumped();
|
||||
if rerun && execution.is_none() {
|
||||
if self.frame_has_budget() {
|
||||
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
|
||||
} else {
|
||||
self.rerun = true;
|
||||
}
|
||||
if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() {
|
||||
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
|
||||
}
|
||||
|
||||
// Eydropper should use the same time and pointer to not invalidate the cache
|
||||
@@ -322,7 +312,7 @@ impl NodeRuntime {
|
||||
self.pending_export = Some(request);
|
||||
return None;
|
||||
}
|
||||
(true, _) => self.rerun = true,
|
||||
(true, _) => self.dirty.store(true, Ordering::Release),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -577,54 +567,33 @@ impl NodeRuntime {
|
||||
.into();
|
||||
}
|
||||
|
||||
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake, clock: Arc<dyn Clock>) {
|
||||
self.async_runtime = Some(AsyncRuntime::new(Arc::new(NodeTaskExecutor { spawner, wake }), clock));
|
||||
self.begin_frame();
|
||||
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
|
||||
let spawn = NodeTaskExecutor {
|
||||
spawner,
|
||||
dirty: self.dirty.clone(),
|
||||
wake,
|
||||
};
|
||||
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
|
||||
}
|
||||
|
||||
pub fn set_scheduling(&mut self, scheduling: Scheduling) {
|
||||
self.scheduling = scheduling;
|
||||
}
|
||||
|
||||
/// Called by the host once the previous output was presented.
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.frame_start = self.async_runtime().clock().now();
|
||||
}
|
||||
|
||||
/// How long a deferred re-evaluation waits for the next frame.
|
||||
pub fn until_next_frame(&self) -> Option<Duration> {
|
||||
let budget = self.frame_budget()?;
|
||||
let elapsed = self.frame_elapsed().as_nanos() % budget.as_nanos();
|
||||
self.rerun.then(|| budget - Duration::from_nanos(elapsed as u64))
|
||||
}
|
||||
|
||||
fn frame_elapsed(&self) -> Duration {
|
||||
self.async_runtime().clock().now().saturating_sub(self.frame_start)
|
||||
}
|
||||
|
||||
fn frame_budget(&self) -> Option<Duration> {
|
||||
self.scheduling.frame_budget.filter(|budget| !budget.is_zero())
|
||||
}
|
||||
|
||||
fn frame_has_budget(&self) -> bool {
|
||||
self.frame_budget().is_none_or(|budget| self.frame_elapsed() < budget)
|
||||
}
|
||||
|
||||
pub(crate) fn async_runtime(&self) -> &AsyncRuntime {
|
||||
fn async_runtime(&self) -> &AsyncRuntime {
|
||||
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
|
||||
}
|
||||
}
|
||||
|
||||
struct NodeTaskExecutor {
|
||||
spawner: Spawner,
|
||||
dirty: Arc<AtomicBool>,
|
||||
wake: Wake,
|
||||
}
|
||||
|
||||
impl Spawn for NodeTaskExecutor {
|
||||
fn spawn(&self, task: Task) {
|
||||
let dirty = self.dirty.clone();
|
||||
let wake = self.wake.clone();
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
task.await;
|
||||
dirty.store(true, Ordering::Release);
|
||||
wake();
|
||||
}));
|
||||
}
|
||||
@@ -733,10 +702,7 @@ impl InspectState {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{EditorTestUtils, FakeClock};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::runtime::Runtime;
|
||||
|
||||
#[test]
|
||||
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
|
||||
@@ -761,66 +727,4 @@ mod tests {
|
||||
|
||||
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
|
||||
}
|
||||
|
||||
const SOURCE: SourceId = SourceId(1);
|
||||
|
||||
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
|
||||
editor.new_document().await;
|
||||
// SVG Preview renders through the SVG pipeline, which sends each evaluation's artwork to the frontend where it can be seen
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
|
||||
editor.runtime.begin_frame();
|
||||
editor
|
||||
}
|
||||
|
||||
fn finish_task(editor: &EditorTestUtils) {
|
||||
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
|
||||
}
|
||||
|
||||
async fn evaluates(editor: &mut EditorTestUtils) -> bool {
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.editor.handle_message(Message::Wake);
|
||||
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reevaluations_past_the_frame_budget_wait_for_the_next_frame() {
|
||||
let clock = Arc::new(FakeClock::default());
|
||||
let mut editor = editor(&clock).await;
|
||||
|
||||
finish_task(&editor);
|
||||
finish_task(&editor);
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert!(!evaluates(&mut editor).await, "two finished tasks re-evaluated twice");
|
||||
|
||||
clock.advance(Duration::from_millis(20));
|
||||
finish_task(&editor);
|
||||
assert!(!evaluates(&mut editor).await);
|
||||
assert_eq!(editor.runtime.until_next_frame(), Some(Duration::from_millis(12)));
|
||||
|
||||
editor.runtime.begin_frame();
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert_eq!(editor.runtime.until_next_frame(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_requests_ignore_the_frame_budget() {
|
||||
let clock = Arc::new(FakeClock::default());
|
||||
let mut editor = editor(&clock).await;
|
||||
|
||||
clock.advance(Duration::from_millis(100));
|
||||
finish_task(&editor);
|
||||
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
|
||||
.unwrap();
|
||||
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert!(!evaluates(&mut editor).await, "the finished task re-evaluated after the explicit request");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
|
||||
pub use graphene_std::runtime::{Spawn, Task};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
|
||||
+12
-89
@@ -9,19 +9,17 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::Instrumented;
|
||||
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
|
||||
use crate::task::{Scheduling, Spawn, Task};
|
||||
use crate::node_graph_executor::NodeRuntime;
|
||||
use crate::task::{Spawn, Task};
|
||||
use crate::test_utils::test_prelude::LayerNodeIdentifier;
|
||||
use document_container::store::MemoryStore;
|
||||
use glam::{DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::runtime::Clock;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
/// A set of utility functions to make the writing of editor test more declarative
|
||||
pub struct EditorTestUtils {
|
||||
@@ -32,10 +30,6 @@ pub struct EditorTestUtils {
|
||||
|
||||
impl EditorTestUtils {
|
||||
pub fn create() -> Self {
|
||||
Self::create_with(Scheduling::UNLIMITED, Arc::new(FakeClock::default()))
|
||||
}
|
||||
|
||||
pub fn create_with(scheduling: Scheduling, clock: Arc<dyn Clock>) -> Self {
|
||||
init_test_logger();
|
||||
|
||||
let woken = Arc::new(AtomicBool::new(false));
|
||||
@@ -48,7 +42,7 @@ impl EditorTestUtils {
|
||||
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
|
||||
.with_document_store(Arc::new(MemoryStore::default())),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(gpu_application_io()))
|
||||
.with_spawner(BlockingSpawner)
|
||||
.with_random_seed(0)
|
||||
.build();
|
||||
@@ -63,11 +57,6 @@ impl EditorTestUtils {
|
||||
editor
|
||||
}
|
||||
|
||||
/// The GPU executor the graph runs on.
|
||||
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
let mut responses = self.editor.handle_message(message);
|
||||
while self.woken.swap(false, Ordering::Relaxed) {
|
||||
@@ -79,7 +68,7 @@ impl EditorTestUtils {
|
||||
/// Submit an evaluation to the executor, run the runtime, and process the results.
|
||||
///
|
||||
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
|
||||
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
async fn eval_graph_once(&mut self) -> Result<Instrumented, String> {
|
||||
let portfolio = &mut self.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
@@ -87,23 +76,17 @@ impl EditorTestUtils {
|
||||
|
||||
let instrumented = match executor.update_node_graph_instrumented(document) {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
|
||||
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
|
||||
};
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
|
||||
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
self.runtime.run().await;
|
||||
|
||||
let frontend_messages = self.dispatch(Message::Wake);
|
||||
let evaluation_errors = self.portfolio_message_handler_mut().executor.take_evaluation_errors();
|
||||
if evaluation_errors.is_none() && frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
|
||||
return Err(TestGraphError::Render);
|
||||
}
|
||||
#[cfg(feature = "gpu")]
|
||||
let evaluation_errors = evaluation_errors.filter(|errors| !errors.iter().all(|(error, _)| error.is::<wgpu_executor::NoGpuError>()));
|
||||
if let Some(errors) = evaluation_errors {
|
||||
return Err(TestGraphError::Evaluation(errors));
|
||||
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
|
||||
return Err("Graph should render".to_string());
|
||||
}
|
||||
|
||||
for message in frontend_messages {
|
||||
@@ -113,35 +96,8 @@ impl EditorTestUtils {
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
|
||||
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
|
||||
let portfolio = &mut self.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
|
||||
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
self.finish_evaluation().await
|
||||
}
|
||||
|
||||
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
|
||||
async fn finish_evaluation(&mut self) -> Result<(), String> {
|
||||
self.runtime.run().await;
|
||||
|
||||
let frontend_messages = self.dispatch(Message::Wake);
|
||||
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
|
||||
return Err("Graph should render".to_string());
|
||||
}
|
||||
for message in frontend_messages {
|
||||
message.check_node_graph_error();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, String> {
|
||||
const MAX_ITERATIONS: usize = 16;
|
||||
for _iteration in 0..MAX_ITERATIONS {
|
||||
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
|
||||
@@ -151,7 +107,7 @@ impl EditorTestUtils {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
return Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")));
|
||||
return Err(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping"));
|
||||
}
|
||||
|
||||
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
@@ -460,23 +416,6 @@ impl FrontendMessageTestUtils for FrontendMessage {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TestGraphError {
|
||||
Evaluation(EvaluationErrors),
|
||||
Render,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TestGraphError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Evaluation(errors) => write!(f, "Graph evaluation failed:\n{errors}"),
|
||||
Self::Render => write!(f, "Graph should render"),
|
||||
Self::Other(message) => write!(f, "{message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static CAPTURED_ERRORS: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
@@ -541,22 +480,6 @@ pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String
|
||||
(result, errors)
|
||||
}
|
||||
|
||||
/// A clock that only moves when advanced.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FakeClock(Mutex<Duration>);
|
||||
|
||||
impl FakeClock {
|
||||
pub fn advance(&self, by: Duration) {
|
||||
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += by;
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for FakeClock {
|
||||
fn now(&self) -> Duration {
|
||||
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
struct BlockingSpawner;
|
||||
impl Spawn for BlockingSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
@@ -578,7 +501,7 @@ pub mod test_prelude {
|
||||
pub use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, is_layer_fed_by_node_of_name};
|
||||
pub use crate::messages::tool::utility_types::ToolType;
|
||||
pub use crate::node_graph_executor::NodeRuntime;
|
||||
pub use crate::test_utils::{EditorTestUtils, TestGraphError};
|
||||
pub use crate::test_utils::EditorTestUtils;
|
||||
pub use core::f64;
|
||||
pub use glam::{DVec2, IVec2};
|
||||
pub use graph_craft::document::DocumentNode;
|
||||
|
||||
@@ -540,10 +540,9 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -36,7 +36,7 @@ serde-wasm-bindgen = { workspace = true }
|
||||
js-sys = { workspace = true }
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
wgpu = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true, features = ["Performance"] }
|
||||
web-sys = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
spin = { workspace = true, optional = true }
|
||||
tsify = { workspace = true }
|
||||
|
||||
@@ -81,11 +81,7 @@ impl EditorWrapper {
|
||||
.with_resource_storage(storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(
|
||||
RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock))
|
||||
.with_wake(crate::helpers::wake_runtime)
|
||||
.with_application_io(application_io),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io))
|
||||
.with_spawner(crate::helpers::WasmSpawner)
|
||||
.with_random_seed(uuid_random_seed)
|
||||
.build();
|
||||
@@ -197,14 +193,7 @@ impl EditorWrapper {
|
||||
|
||||
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
|
||||
#[cfg(not(feature = "native"))]
|
||||
{
|
||||
if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock()
|
||||
&& let Some(runtime) = runtime.as_mut()
|
||||
{
|
||||
runtime.begin_frame();
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(run_node_runtime());
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(run_node_runtime());
|
||||
|
||||
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||
wrapper(|wrapper| {
|
||||
|
||||
@@ -7,7 +7,7 @@ use editor::messages::input_mapper::utility_types::keyboard::Key;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::messages::prelude::*;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::task::{Clock, Spawn, Task};
|
||||
use editor::task::{Spawn, Task};
|
||||
use js_sys::{Object, Reflect};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
@@ -70,16 +70,6 @@ impl Spawn for WasmSpawner {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
pub(crate) struct PerformanceClock;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
impl Clock for PerformanceClock {
|
||||
fn now(&self) -> Duration {
|
||||
let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`");
|
||||
Duration::from_secs_f64(performance.now() / 1000.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Web editor wake: queues a microtask that dispatches [`Message::Wake`].
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
pub(crate) fn wake_editor() {
|
||||
|
||||
@@ -9,7 +9,7 @@ use core_types::{Context, Cow, MemoHash, NodeCompileMetadata, NodeParameter, Pro
|
||||
use dyn_any::DynAny;
|
||||
use glam::IVec2;
|
||||
use log::Metadata;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
@@ -145,7 +145,7 @@ impl DocumentNode {
|
||||
|
||||
let mut construction_args = ConstructionArgs::Nodes(vec![]);
|
||||
|
||||
// If we have one input of the type value, set it as the construction args
|
||||
// If we have one input of the type inline, set it as the construction args
|
||||
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
|
||||
construction_args = ConstructionArgs::Value(tagged_value.clone());
|
||||
}
|
||||
@@ -286,9 +286,9 @@ pub enum OldDocumentNodeImplementation {
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, core_types::CacheHash, PartialOrd, Ord, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NetworkId(pub u64);
|
||||
pub struct DefinitionId(pub u64);
|
||||
|
||||
impl NetworkId {
|
||||
impl DefinitionId {
|
||||
pub fn new() -> Self {
|
||||
Self(generate_uuid())
|
||||
}
|
||||
@@ -301,7 +301,7 @@ pub enum DocumentNodeImplementation {
|
||||
///
|
||||
/// A nested [`NodeNetwork`] that is flattened by the [`NodeNetwork::flatten`] function.
|
||||
Network(NodeNetwork),
|
||||
Definition(NetworkId),
|
||||
Definition(DefinitionId),
|
||||
/// This describes a (document) node implemented as a proto node.
|
||||
///
|
||||
/// A proto node identifier which can be found in `node_registry.rs`.
|
||||
@@ -313,11 +313,13 @@ pub enum DocumentNodeImplementation {
|
||||
///
|
||||
/// This is explained in more detail here: <https://www.youtube.com/watch?v=72KJa3jQClo>
|
||||
///
|
||||
/// Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
|
||||
/// Currently we use it for GPU execution, where a node has to get "extracted" to its source code representation and stored as a value that can be given to the GpuCompiler node at runtime
|
||||
/// (to become a compute shader). Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
|
||||
/// We would use an assortment of nodes that operate on Graphene source code (just data, no different from any other data flowing through the graph) to make graph transformations.
|
||||
///
|
||||
/// We use this for dealing with macros in a syntactic way of modifying the node graph from within the graph itself. Just like we often deal with lambdas to represent a whole group of
|
||||
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, rather than its executable logic.
|
||||
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, because we need to pass the GPU SPIR-V compiler the source code for a lambda,
|
||||
/// not the executable logic of a lambda.
|
||||
///
|
||||
/// This is analogous to how Rust macros operate at the level of source code, not executable code. When we speak of source code, that represents Graphene's source code in the form of a
|
||||
/// DocumentNode network, not the text form of Rust's source code. (Analogous to the token stream/AST of a Rust macro.)
|
||||
@@ -548,21 +550,21 @@ pub struct NodeNetwork {
|
||||
)]
|
||||
pub scope_injections: FxHashMap<String, (NodeId, Type)>,
|
||||
#[serde(default, skip_serializing_if = "FxHashMap::is_empty")]
|
||||
pub definitions: FxHashMap<NetworkId, NodeNetwork>,
|
||||
pub definitions: FxHashMap<DefinitionId, NodeNetwork>,
|
||||
#[serde(skip)]
|
||||
pub generated: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct NetworkLocation<'a> {
|
||||
pub definition: Option<NetworkId>,
|
||||
pub definition: Option<DefinitionId>,
|
||||
pub inline_path: &'a [NodeId],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DefinitionError {
|
||||
Missing(NetworkId),
|
||||
Cycle(Vec<NetworkId>),
|
||||
Missing(DefinitionId),
|
||||
Cycle(Vec<DefinitionId>),
|
||||
NestedTable,
|
||||
}
|
||||
|
||||
@@ -579,9 +581,9 @@ impl std::fmt::Display for DefinitionError {
|
||||
impl std::error::Error for DefinitionError {}
|
||||
|
||||
struct DefinitionInliner {
|
||||
definitions: FxHashMap<NetworkId, NodeNetwork>,
|
||||
inlined: FxHashMap<NetworkId, NodeNetwork>,
|
||||
visiting: Vec<NetworkId>,
|
||||
definitions: FxHashMap<DefinitionId, NodeNetwork>,
|
||||
inlined: FxHashMap<DefinitionId, NodeNetwork>,
|
||||
visiting: Vec<DefinitionId>,
|
||||
}
|
||||
|
||||
impl DefinitionInliner {
|
||||
@@ -601,7 +603,7 @@ impl DefinitionInliner {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inlined_definition(&mut self, id: NetworkId) -> Result<&NodeNetwork, DefinitionError> {
|
||||
fn inlined_definition(&mut self, id: DefinitionId) -> Result<&NodeNetwork, DefinitionError> {
|
||||
if !self.inlined.contains_key(&id) {
|
||||
if let Some(start) = self.visiting.iter().position(|&visiting| visiting == id) {
|
||||
return Err(DefinitionError::Cycle(self.visiting[start..].to_vec()));
|
||||
@@ -925,9 +927,6 @@ impl NodeNetwork {
|
||||
for node in self.nodes.values_mut() {
|
||||
node.normalize_stored_types();
|
||||
}
|
||||
for definition in self.definitions.values_mut() {
|
||||
definition.normalize_stored_types();
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
|
||||
@@ -1419,11 +1418,7 @@ impl NodeNetwork {
|
||||
/// Create a [`RecursiveNodeIter`] that iterates over all [`DocumentNode`]s, including ones that are deeply nested.
|
||||
pub fn recursive_nodes(&self) -> RecursiveNodeIter<'_> {
|
||||
let nodes = self.nodes.iter().map(|(id, node)| (id, node, Vec::new())).collect();
|
||||
RecursiveNodeIter {
|
||||
definitions: &self.definitions,
|
||||
visited_definitions: FxHashSet::default(),
|
||||
nodes,
|
||||
}
|
||||
RecursiveNodeIter { nodes }
|
||||
}
|
||||
|
||||
/// Ensure the cached list of dependants exactly matches the real list of dependants
|
||||
@@ -1460,10 +1455,7 @@ impl NodeNetwork {
|
||||
}
|
||||
|
||||
/// An iterator over all [`DocumentNode`]s, including ones that are deeply nested.
|
||||
/// Each definition body is visited once, under the path of the first instance reached.
|
||||
pub struct RecursiveNodeIter<'a> {
|
||||
definitions: &'a FxHashMap<NetworkId, NodeNetwork>,
|
||||
visited_definitions: FxHashSet<NetworkId>,
|
||||
nodes: Vec<(&'a NodeId, &'a DocumentNode, Vec<NodeId>)>,
|
||||
}
|
||||
|
||||
@@ -1471,12 +1463,7 @@ impl<'a> Iterator for RecursiveNodeIter<'a> {
|
||||
type Item = (&'a NodeId, &'a DocumentNode, Vec<NodeId>);
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let (current_id, node, path) = self.nodes.pop()?;
|
||||
let nested_network = match &node.implementation {
|
||||
DocumentNodeImplementation::Network(network) => Some(network),
|
||||
DocumentNodeImplementation::Definition(id) if self.visited_definitions.insert(*id) => self.definitions.get(id),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(network) = nested_network {
|
||||
if let DocumentNodeImplementation::Network(network) = &node.implementation {
|
||||
self.nodes.extend(network.nodes.iter().map(|(id, node)| {
|
||||
let mut nested_path = path.clone();
|
||||
nested_path.push(*current_id);
|
||||
@@ -2101,7 +2088,7 @@ mod test {
|
||||
DocumentNode { implementation, ..Default::default() }
|
||||
}
|
||||
|
||||
fn network_with(nodes: impl IntoIterator<Item = (NodeId, DocumentNodeImplementation)>, definitions: impl IntoIterator<Item = (NetworkId, NodeNetwork)>) -> NodeNetwork {
|
||||
fn network_with(nodes: impl IntoIterator<Item = (NodeId, DocumentNodeImplementation)>, definitions: impl IntoIterator<Item = (DefinitionId, NodeNetwork)>) -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: nodes.into_iter().map(|(id, implementation)| (id, node_with(implementation))).collect(),
|
||||
@@ -2110,7 +2097,7 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
const ADD: NetworkId = NetworkId(1);
|
||||
const ADD: DefinitionId = DefinitionId(1);
|
||||
|
||||
fn two_add_instances() -> NodeNetwork {
|
||||
network_with(
|
||||
@@ -2136,7 +2123,7 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn definitions_referencing_definitions_inline_transitively() {
|
||||
let outer = NetworkId(2);
|
||||
let outer = DefinitionId(2);
|
||||
let mut network = network_with(
|
||||
[(NodeId(10), DocumentNodeImplementation::Definition(outer))],
|
||||
[(ADD, add_network()), (outer, network_with([(NodeId(10), DocumentNodeImplementation::Definition(ADD))], []))],
|
||||
@@ -2149,7 +2136,7 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn invalid_definition_tables_are_rejected() {
|
||||
let (first, second) = (NetworkId(2), NetworkId(3));
|
||||
let (first, second) = (DefinitionId(2), DefinitionId(3));
|
||||
let mut cyclic = network_with(
|
||||
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
|
||||
[
|
||||
@@ -2191,22 +2178,4 @@ mod test {
|
||||
network.definitions.get_mut(&ADD).unwrap().exports.push(NodeInput::node(NodeId(0), 0));
|
||||
assert_ne!(network.current_hash(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_nodes_visit_each_definition_once() {
|
||||
let network = two_add_instances();
|
||||
let body_paths = network.recursive_nodes().map(|(_, _, path)| path).filter(|path| !path.is_empty()).collect::<Vec<_>>();
|
||||
assert_eq!(body_paths.len(), add_network().nodes.len());
|
||||
assert!(body_paths.windows(2).all(|pair| pair[0] == pair[1]));
|
||||
|
||||
let (first, second) = (NetworkId(2), NetworkId(3));
|
||||
let cyclic = network_with(
|
||||
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
|
||||
[
|
||||
(first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])),
|
||||
(second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])),
|
||||
],
|
||||
);
|
||||
assert_eq!(cyclic.recursive_nodes().count(), 3);
|
||||
}
|
||||
}
|
||||
@@ -579,9 +579,6 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -711,25 +708,6 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -748,7 +726,6 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use crate::TokioSpawner;
|
||||
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::{no_paths, paths_from_item_attributes};
|
||||
use graphene_std::{Cover, Coverage};
|
||||
use graphene_std::{NodeError, Poll};
|
||||
use image::ImageFormat;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -75,80 +73,6 @@ pub struct ExportSettings {
|
||||
pub size: (Option<u32>, Option<u32>),
|
||||
/// Whether raster formats that can keep transparency do so, instead of compositing onto white
|
||||
pub transparent: bool,
|
||||
/// The document region to render, which [`ExportSettings::framed`] fits to the artwork when no size is given
|
||||
pub framing: Option<Framing>,
|
||||
}
|
||||
|
||||
/// A document-space region mapped onto the output pixels.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Framing {
|
||||
pub transform: DAffine2,
|
||||
pub resolution: UVec2,
|
||||
}
|
||||
|
||||
impl ExportSettings {
|
||||
/// Frame the artwork as it is at time zero, unless a size was given.
|
||||
/// Every frame of an animation shares this framing, so they all have one size.
|
||||
pub async fn framed(mut self, executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
|
||||
if self.size.0.is_some() && self.size.1.is_some() {
|
||||
return Ok(self);
|
||||
}
|
||||
|
||||
let [min, max] = artwork_bounds(executor, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
|
||||
let resolution = ((max - min) * self.scale).round().max(DVec2::ONE).as_uvec2();
|
||||
self.framing = Some(Framing {
|
||||
transform: DAffine2::from_translation(min).inverse(),
|
||||
resolution,
|
||||
});
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document-space bounds of every layer including its stroke, artboards included, from the metadata of an SVG render.
|
||||
/// Content an artboard clips away still counts, since this has no layer tree to tell which artboard holds it.
|
||||
async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
|
||||
// An identity viewport, since the default one is degenerate and its transforms come out NaN
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
transform: DAffine2::IDENTITY,
|
||||
resolution: UVec2::ONE,
|
||||
..Default::default()
|
||||
},
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Svg,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, runtime, spawner, render_config).await? else {
|
||||
return Err("The document did not render".into());
|
||||
};
|
||||
|
||||
let metadata = &output.metadata;
|
||||
let layer_bounds = metadata.click_targets.iter().filter_map(|(layer, click_targets)| {
|
||||
let footprint = metadata.upstream_footprints.get(layer).map(|footprint| footprint.transform).unwrap_or_default();
|
||||
let local_transform = metadata.local_transforms.get(layer).copied().unwrap_or_default();
|
||||
let transform = footprint * local_transform;
|
||||
|
||||
// A stroke extends past the path a click target outlines, so a vector layer also measures its rendered geometry.
|
||||
// Metadata only records the first item of a layer, so the other items count through their click targets, without their strokes.
|
||||
let stroked = metadata.vector_data.get(layer).and_then(|item| {
|
||||
let appearance = metadata.appearance_attributes.get(layer);
|
||||
let stroke = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map(Coverage::stroke_params);
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, transform, stroke.as_ref())
|
||||
});
|
||||
|
||||
click_targets
|
||||
.iter()
|
||||
.filter_map(|click_target| click_target.bounding_box_with_transform(transform))
|
||||
.chain(stroked)
|
||||
.reduce(combine_bounds)
|
||||
});
|
||||
Ok(layer_bounds.reduce(combine_bounds))
|
||||
}
|
||||
|
||||
fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DVec2; 2] {
|
||||
[a_min.min(b_min), a_max.max(b_max)]
|
||||
}
|
||||
|
||||
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
|
||||
@@ -180,10 +104,8 @@ async fn render_frame(
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(framing) = settings.framing {
|
||||
render_config.viewport.transform = framing.transform;
|
||||
render_config.viewport.resolution = framing.resolution;
|
||||
} else if let (Some(w), Some(h)) = (width, height) {
|
||||
// Set viewport dimensions if specified
|
||||
if let (Some(w), Some(h)) = (width, height) {
|
||||
render_config.viewport.resolution = UVec2::new(w, h);
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
application_io: Some(application_io_for_api),
|
||||
});
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(std::time::Instant::now()));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
match app.command {
|
||||
@@ -237,10 +237,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
scale,
|
||||
size: (width, height),
|
||||
transparent,
|
||||
framing: None,
|
||||
}
|
||||
.framed(&executor, &runtime, &spawner)
|
||||
.await?;
|
||||
};
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
if file_type == export::FileType::Gif {
|
||||
export::export_gif(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?;
|
||||
|
||||
@@ -3,14 +3,14 @@ use criterion::measurement::Measurement;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task};
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let network = load_from_name(name);
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
@@ -33,10 +33,3 @@ struct DummySpawner;
|
||||
impl Spawn for DummySpawner {
|
||||
fn spawn(&self, _task: Task) {}
|
||||
}
|
||||
|
||||
struct NoClock;
|
||||
impl Clock for NoClock {
|
||||
fn now(&self) -> std::time::Duration {
|
||||
std::time::Duration::ZERO
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use dyn_any::StaticType;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_animation::AnimationCurve;
|
||||
@@ -27,7 +27,6 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -89,7 +88,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformApplicationIo>>, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>, Context => Item<graphene_std::ContextModification>]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextModification>]),
|
||||
@@ -138,7 +136,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformApplicationIo>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -334,9 +331,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -383,28 +377,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
|
||||
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
|
||||
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
|
||||
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
|
||||
#[cfg(feature = "gpu")]
|
||||
{
|
||||
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
|
||||
macro_rules! gpu_raster_input_adapter {
|
||||
($path:ty, $from:ty) => {
|
||||
async_node!(
|
||||
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
|
||||
$path,
|
||||
input: Context,
|
||||
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
|
||||
)
|
||||
};
|
||||
}
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
|
||||
node_types.push(item_to_list_node!(element: Raster<GPU>));
|
||||
}
|
||||
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
|
||||
@@ -58,7 +58,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
@@ -69,7 +69,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
|
||||
@@ -240,7 +240,7 @@ impl Pixel for Luma {}
|
||||
///
|
||||
/// Anything crossing the Wasm/JS boundary must go through [`SRGBA8`] instead.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, dyn_any::DynAny, graphene_hash::CacheHash)]
|
||||
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
|
||||
pub struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
|
||||
@@ -32,10 +32,9 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,11 +61,6 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -85,9 +80,6 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
use crate::poll::Poll;
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::WasmNotSend;
|
||||
pub use futures::future::AbortHandle;
|
||||
use futures::future::Abortable;
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::task::{Context, Waker};
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type Task = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
|
||||
@@ -21,36 +18,6 @@ pub trait Spawn {
|
||||
fn spawn(&self, task: Task);
|
||||
}
|
||||
|
||||
/// Monotonic time since an arbitrary origin.
|
||||
pub trait Clock: Send + Sync {
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Clock for std::time::Instant {
|
||||
fn now(&self) -> Duration {
|
||||
self.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Scheduling {
|
||||
/// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it.
|
||||
pub frame_budget: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Scheduling {
|
||||
pub const UNLIMITED: Self = Self { frame_budget: None };
|
||||
}
|
||||
|
||||
impl Default for Scheduling {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
frame_budget: Some(Duration::from_millis(16)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)]
|
||||
pub struct SourceId(pub u64);
|
||||
|
||||
@@ -66,22 +33,15 @@ impl SourceId {
|
||||
pub type Generations = Arc<[(SourceId, u64)]>;
|
||||
|
||||
pub trait Runtime {
|
||||
/// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first.
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
|
||||
fn spawn(&self, source: SourceId, task: Task);
|
||||
}
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RuntimeHandle(Arc<RuntimeInner>);
|
||||
|
||||
impl RuntimeHandle {
|
||||
pub fn clock(&self) -> &dyn Clock {
|
||||
&*self.0.clock
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime for RuntimeHandle {
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
|
||||
self.0.spawn(source, task)
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,43 +64,28 @@ impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
pub struct AsyncRuntime(Arc<RuntimeInner>);
|
||||
|
||||
impl AsyncRuntime {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>, clock: Arc<dyn Clock>) -> Self {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
|
||||
Self(Arc::new(RuntimeInner {
|
||||
sources: Mutex::default(),
|
||||
next_task: AtomicU64::new(0),
|
||||
bumped: AtomicBool::new(false),
|
||||
generations: Mutex::default(),
|
||||
spawner,
|
||||
clock,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Aborts the unfinished tasks of removed sources.
|
||||
pub fn retain_sources(&self, live: &[SourceId]) {
|
||||
let mut sources = self.0.lock();
|
||||
for (_, state) in sources.extract_if(|source, _| !live.contains(source)) {
|
||||
state.tasks.values().for_each(AbortHandle::abort);
|
||||
}
|
||||
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
for source in live {
|
||||
sources.entry(*source).or_default();
|
||||
generations.entry(*source).or_insert(0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Generations {
|
||||
let sources = self.0.lock();
|
||||
let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect();
|
||||
let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
|
||||
snapshot.sort_unstable();
|
||||
snapshot.into()
|
||||
}
|
||||
|
||||
/// Whether any generation was bumped since the last call.
|
||||
pub fn take_bumped(&self) -> bool {
|
||||
self.0.bumped.swap(false, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub fn clock(&self) -> &dyn Clock {
|
||||
&*self.0.clock
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn handle(&self) -> RuntimeHandle {
|
||||
RuntimeHandle(Arc::clone(&self.0))
|
||||
@@ -148,50 +93,25 @@ impl AsyncRuntime {
|
||||
}
|
||||
|
||||
impl Runtime for AsyncRuntime {
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
|
||||
self.0.spawn(source, task)
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
}
|
||||
}
|
||||
|
||||
/// A live source's generation and its unfinished tasks.
|
||||
#[derive(Default)]
|
||||
struct SourceState {
|
||||
generation: u64,
|
||||
tasks: HashMap<u64, AbortHandle>,
|
||||
}
|
||||
|
||||
struct RuntimeInner {
|
||||
sources: Mutex<HashMap<SourceId, SourceState>>,
|
||||
next_task: AtomicU64,
|
||||
bumped: AtomicBool,
|
||||
generations: Mutex<HashMap<SourceId, u64>>,
|
||||
spawner: Arc<dyn Spawn + Send + Sync>,
|
||||
clock: Arc<dyn Clock>,
|
||||
}
|
||||
|
||||
impl RuntimeInner {
|
||||
fn lock(&self) -> MutexGuard<'_, HashMap<SourceId, SourceState>> {
|
||||
self.sources.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) -> AbortHandle {
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let id = self.next_task.fetch_add(1, Ordering::Relaxed);
|
||||
if let Some(state) = self.lock().get_mut(&source) {
|
||||
state.tasks.insert(id, handle.clone());
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) {
|
||||
let inner = Arc::clone(self);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
let finished = Abortable::new(task, registration).await.is_ok();
|
||||
if let Some(state) = inner.lock().get_mut(&source)
|
||||
&& state.tasks.remove(&id).is_some()
|
||||
&& finished
|
||||
{
|
||||
state.generation += 1;
|
||||
inner.bumped.store(true, Ordering::Release);
|
||||
task.await;
|
||||
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
|
||||
*generation += 1;
|
||||
}
|
||||
}));
|
||||
handle
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,12 +167,14 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
return state;
|
||||
}
|
||||
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let slots = Arc::downgrade(&self.0);
|
||||
let handle = runtime.spawn(
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
let state = future.await;
|
||||
if let Some(slots) = slots.upgrade() {
|
||||
if let Ok(state) = Abortable::new(future, registration).await
|
||||
&& let Some(slots) = slots.upgrade()
|
||||
{
|
||||
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
|
||||
}
|
||||
}),
|
||||
@@ -271,14 +193,7 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct NoClock;
|
||||
|
||||
impl Clock for NoClock {
|
||||
fn now(&self) -> Duration {
|
||||
Duration::ZERO
|
||||
}
|
||||
}
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
fn poll_once(task: &mut Task) -> bool {
|
||||
task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready()
|
||||
@@ -331,7 +246,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_completion_bumps_its_generation() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
@@ -344,7 +259,7 @@ mod tests {
|
||||
#[test]
|
||||
fn retaining_sources_keeps_live_generations() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
spawner.drain();
|
||||
@@ -359,7 +274,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_inline_completion_and_a_dropped_source_bump_nothing() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
let slots = Slots::default();
|
||||
@@ -376,7 +291,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_slot_serves_the_placeholder_until_the_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
@@ -393,7 +308,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() {
|
||||
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
@@ -408,7 +323,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_clone_keeps_the_task_running() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
YieldOnce(false).await;
|
||||
@@ -425,7 +340,7 @@ mod tests {
|
||||
#[test]
|
||||
fn dropping_the_last_clone_aborts_the_task() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let slots = Slots::default();
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
let fetch = || {
|
||||
@@ -442,32 +357,4 @@ mod tests {
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert!(!finished.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_tasks_bump_once() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert!(runtime.take_bumped());
|
||||
assert!(!runtime.take_bumped());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aborted_tasks_bump_nothing() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE, SourceId(9)]);
|
||||
runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort();
|
||||
let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending()));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
assert!(removed.is_aborted());
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
|
||||
assert!(!runtime.take_bumped());
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ impl TransferCurveEvaluator {
|
||||
}
|
||||
|
||||
// O(log n) search for the segment holding x
|
||||
let upper = points.partition_point(|point| point.x <= x).clamp(1, points.len() - 1);
|
||||
let upper = points.partition_point(|point| point.x <= x).min(points.len() - 1);
|
||||
let lower = upper - 1;
|
||||
let (a, b) = (points[lower], points[upper]);
|
||||
let width = (b.x - a.x).max(f64::EPSILON);
|
||||
@@ -206,17 +206,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_survives_a_value_or_point_that_is_not_a_number() {
|
||||
assert!(TransferCurve::default().evaluate(f64::NAN).is_nan());
|
||||
|
||||
// A negative NaN sorts first, so every x between the points meets it
|
||||
let curve = TransferCurve::new(vec![DVec2::new(-f64::NAN, 0.), DVec2::new(0.5, 0.7), DVec2::ONE]);
|
||||
for x in (1..100).map(|i| i as f64 / 100.) {
|
||||
curve.evaluate(x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_point_may_pass_another_while_keeping_its_index() {
|
||||
let mut curve = TransferCurve::default();
|
||||
|
||||
@@ -191,10 +191,6 @@ impl Footprint {
|
||||
};
|
||||
|
||||
pub fn viewport_bounds_in_local_space(&self) -> AxisAlignedBbox {
|
||||
if self.transform.matrix2.determinant() == 0. {
|
||||
return AxisAlignedBbox::ZERO;
|
||||
}
|
||||
|
||||
let inverse = self.transform.inverse();
|
||||
let res = self.resolution.as_dvec2();
|
||||
let c0 = inverse.transform_point2(DVec2::ZERO);
|
||||
|
||||
@@ -21,7 +21,6 @@ wasm = [
|
||||
"core-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"raster-types/wasm",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -29,7 +28,6 @@ wasm = [
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
brush-types = { workspace = true }
|
||||
raster-types = { workspace = true, features = ["wgpu"] }
|
||||
vector-types = { workspace = true }
|
||||
@@ -38,10 +36,8 @@ node-macro = { workspace = true }
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -1,557 +0,0 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::{EffectKind, ParameterVisitor};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use graphene_resource::Resource;
|
||||
use num_enum::{FromPrimitive, IntoPrimitive};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// A color adjustment applied to each color on its own, with no regard for its neighbors.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub enum Adjustment {
|
||||
Desaturate {
|
||||
method: DesaturateMethod,
|
||||
},
|
||||
GammaCorrection {
|
||||
gamma: f64,
|
||||
inverse: bool,
|
||||
},
|
||||
MakeOpaque,
|
||||
BrightnessContrast {
|
||||
/// Percent.
|
||||
brightness: f64,
|
||||
/// Percent.
|
||||
contrast: f64,
|
||||
use_classic: bool,
|
||||
/// On a scale of 0 to 255.
|
||||
classic_pivot: f64,
|
||||
},
|
||||
Levels(Box<LevelsSettings>),
|
||||
Curves(Box<CurvesSettings>),
|
||||
BlackAndWhite(BlackAndWhiteSettings),
|
||||
HueSaturation(Box<HueSaturationSettings>),
|
||||
Invert,
|
||||
Threshold {
|
||||
/// Percent.
|
||||
min_luminance: f64,
|
||||
/// Percent.
|
||||
max_luminance: f64,
|
||||
},
|
||||
GradientMap {
|
||||
/// The gradient, with its whole-ramp settings as its attributes.
|
||||
gradient: Item<Gradient>,
|
||||
reverse: bool,
|
||||
},
|
||||
Vibrance {
|
||||
/// Percent.
|
||||
vibrance: f64,
|
||||
/// Percent.
|
||||
saturation: f64,
|
||||
},
|
||||
ChannelMixer(Box<ChannelMixerSettings>),
|
||||
SelectiveColor(Box<SelectiveColorSettings>),
|
||||
Posterize {
|
||||
levels: i64,
|
||||
},
|
||||
Exposure {
|
||||
exposure: f64,
|
||||
offset: f64,
|
||||
gamma_correction: f64,
|
||||
},
|
||||
ColorBalance(ColorBalanceSettings),
|
||||
PhotoFilter {
|
||||
color: Color,
|
||||
/// Percent.
|
||||
density: f64,
|
||||
preserve_luminosity: bool,
|
||||
},
|
||||
ColorLookup {
|
||||
/// The file the lookup table is read from.
|
||||
lut_file: Resource,
|
||||
},
|
||||
ColorOverlay {
|
||||
color: Color,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
|
||||
pub fn is_per_channel(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::GammaCorrection { .. }
|
||||
| Self::MakeOpaque
|
||||
| Self::BrightnessContrast { .. }
|
||||
| Self::Levels(_)
|
||||
| Self::Curves(_)
|
||||
| Self::Invert
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Desaturate { .. } => EffectKind::Desaturate,
|
||||
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
||||
Self::MakeOpaque => EffectKind::MakeOpaque,
|
||||
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
||||
Self::Levels(_) => EffectKind::Levels,
|
||||
Self::Curves(_) => EffectKind::Curves,
|
||||
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
|
||||
Self::HueSaturation(_) => EffectKind::HueSaturation,
|
||||
Self::Invert => EffectKind::Invert,
|
||||
Self::Threshold { .. } => EffectKind::Threshold,
|
||||
Self::GradientMap { .. } => EffectKind::GradientMap,
|
||||
Self::Vibrance { .. } => EffectKind::Vibrance,
|
||||
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
|
||||
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
|
||||
Self::Posterize { .. } => EffectKind::Posterize,
|
||||
Self::Exposure { .. } => EffectKind::Exposure,
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
|
||||
Self::GammaCorrection { gamma, inverse } => {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
use_classic,
|
||||
classic_pivot,
|
||||
} => {
|
||||
visitor.parameter("brightness", brightness, 0.);
|
||||
visitor.parameter("contrast", contrast, 0.);
|
||||
visitor.parameter("use_classic", use_classic, false);
|
||||
visitor.parameter("classic_pivot", classic_pivot, 127.);
|
||||
}
|
||||
Self::Levels(settings) => {
|
||||
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
composite.visit_parameters(visitor, "");
|
||||
red.visit_parameters(visitor, "red");
|
||||
green.visit_parameters(visitor, "green");
|
||||
blue.visit_parameters(visitor, "blue");
|
||||
alpha.visit_parameters(visitor, "alpha");
|
||||
}
|
||||
Self::Curves(settings) => {
|
||||
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
visitor.parameter("curve", composite, TransferCurve::default());
|
||||
visitor.parameter("red_curve", red, TransferCurve::default());
|
||||
visitor.parameter("green_curve", green, TransferCurve::default());
|
||||
visitor.parameter("blue_curve", blue, TransferCurve::default());
|
||||
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
|
||||
}
|
||||
Self::BlackAndWhite(settings) => {
|
||||
visitor.parameter("use_tint", &mut settings.use_tint, false);
|
||||
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
|
||||
visitor.parameter("reds", &mut settings.reds, 40.);
|
||||
visitor.parameter("yellows", &mut settings.yellows, 60.);
|
||||
visitor.parameter("greens", &mut settings.greens, 40.);
|
||||
visitor.parameter("cyans", &mut settings.cyans, 60.);
|
||||
visitor.parameter("blues", &mut settings.blues, 20.);
|
||||
visitor.parameter("magentas", &mut settings.magentas, 80.);
|
||||
}
|
||||
Self::HueSaturation(settings) => {
|
||||
let HueSaturationSettings {
|
||||
master,
|
||||
colorize,
|
||||
colorize_sliders,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
} = settings.as_mut();
|
||||
|
||||
master.visit_parameters(visitor, "", [0., 0., 0.]);
|
||||
visitor.parameter("colorize", colorize, false);
|
||||
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
|
||||
|
||||
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
|
||||
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
|
||||
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
|
||||
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
|
||||
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
|
||||
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
|
||||
}
|
||||
Self::Threshold { min_luminance, max_luminance } => {
|
||||
visitor.parameter("min_luminance", min_luminance, 50.);
|
||||
visitor.parameter("max_luminance", max_luminance, 100.);
|
||||
}
|
||||
Self::GradientMap { gradient, reverse } => {
|
||||
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
|
||||
visitor.parameter("reverse", reverse, false);
|
||||
}
|
||||
Self::Vibrance { vibrance, saturation } => {
|
||||
visitor.parameter("vibrance", vibrance, 0.);
|
||||
visitor.parameter("saturation", saturation, 0.);
|
||||
}
|
||||
Self::ChannelMixer(settings) => {
|
||||
let ChannelMixerSettings {
|
||||
monochrome,
|
||||
monochrome_mix,
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("monochrome", monochrome, false);
|
||||
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
|
||||
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
|
||||
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
|
||||
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
|
||||
}
|
||||
Self::SelectiveColor(settings) => {
|
||||
let SelectiveColorSettings {
|
||||
mode,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
whites,
|
||||
neutrals,
|
||||
blacks,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("mode", mode, RelativeAbsolute::default());
|
||||
let groups = [
|
||||
("reds", reds),
|
||||
("yellows", yellows),
|
||||
("greens", greens),
|
||||
("cyans", cyans),
|
||||
("blues", blues),
|
||||
("magentas", magentas),
|
||||
("whites", whites),
|
||||
("neutrals", neutrals),
|
||||
("blacks", blacks),
|
||||
];
|
||||
for (name, inks) in groups {
|
||||
inks.visit_parameters(visitor, name);
|
||||
}
|
||||
}
|
||||
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
|
||||
Self::Exposure { exposure, offset, gamma_correction } => {
|
||||
visitor.parameter("exposure", exposure, 0.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("gamma_correction", gamma_correction, 1.);
|
||||
}
|
||||
Self::ColorBalance(settings) => {
|
||||
settings.shadows.visit_parameters(visitor, "shadows");
|
||||
settings.midtones.visit_parameters(visitor, "midtones");
|
||||
settings.highlights.visit_parameters(visitor, "highlights");
|
||||
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
|
||||
}
|
||||
Self::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
|
||||
visitor.parameter("density", density, 25.);
|
||||
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Conversion from a color to grayscale.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
#[widget(Dropdown)]
|
||||
#[repr(u32)]
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
LuminanceRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// CSS filter functions such as `grayscale()` use this.
|
||||
#[label("Luma (Rec. 709)")]
|
||||
LumaRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`.
|
||||
///
|
||||
/// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`.
|
||||
#[label("Luma (Rec. 601)")]
|
||||
LumaRec601,
|
||||
/// Perceptually uniform scale from black to white, the L (lightness) of OkLab.
|
||||
#[label("Lightness (OkLab)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Perceptual"))]
|
||||
LightnessOkLab,
|
||||
/// Mean of the three linear-light RGB channels.
|
||||
#[menu_separator]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))]
|
||||
ChannelsAverage,
|
||||
/// Smallest of the three linear-light RGB channels.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))]
|
||||
ChannelsMinimum,
|
||||
/// Largest of the three linear-light RGB channels, the V (value) of HSV.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))]
|
||||
ChannelsMaximum,
|
||||
/// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL.
|
||||
///
|
||||
/// The classic "Desaturate" command of many image editors uses this.
|
||||
#[label("Lightness (HSL)")]
|
||||
LightnessHsl,
|
||||
}
|
||||
|
||||
#[repr(u32)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
#[widget(Radio)]
|
||||
pub enum RelativeAbsolute {
|
||||
#[default]
|
||||
Relative,
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// A group of colors whose inks the Selective Color adjustment offsets.
|
||||
#[repr(u32)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
pub enum SelectiveColorChoice {
|
||||
#[default]
|
||||
Reds,
|
||||
Yellows,
|
||||
Greens,
|
||||
Cyans,
|
||||
Blues,
|
||||
Magentas,
|
||||
|
||||
#[menu_separator]
|
||||
Whites,
|
||||
Neutrals,
|
||||
Blacks,
|
||||
}
|
||||
|
||||
/// One channel's Levels record: percentage input and output points and the midtones gamma.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsRecord {
|
||||
pub shadows: f64,
|
||||
pub midtones: f64,
|
||||
pub highlights: f64,
|
||||
pub output_minimums: f64,
|
||||
pub output_maximums: f64,
|
||||
}
|
||||
|
||||
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsSettings {
|
||||
pub composite: LevelsRecord,
|
||||
pub red: LevelsRecord,
|
||||
pub green: LevelsRecord,
|
||||
pub blue: LevelsRecord,
|
||||
pub alpha: LevelsRecord,
|
||||
}
|
||||
|
||||
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct CurvesSettings {
|
||||
pub composite: TransferCurve,
|
||||
pub red: TransferCurve,
|
||||
pub green: TransferCurve,
|
||||
pub blue: TransferCurve,
|
||||
pub alpha: TransferCurve,
|
||||
}
|
||||
|
||||
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlackAndWhiteSettings {
|
||||
pub use_tint: bool,
|
||||
pub tint: Color,
|
||||
pub reds: f64,
|
||||
pub yellows: f64,
|
||||
pub greens: f64,
|
||||
pub cyans: f64,
|
||||
pub blues: f64,
|
||||
pub magentas: f64,
|
||||
}
|
||||
|
||||
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSliders {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub lightness: f64,
|
||||
}
|
||||
|
||||
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueRangeSettings {
|
||||
pub sliders: HueSaturationSliders,
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSettings {
|
||||
pub master: HueSaturationSliders,
|
||||
pub colorize: bool,
|
||||
pub colorize_sliders: HueSaturationSliders,
|
||||
pub reds: HueRangeSettings,
|
||||
pub yellows: HueRangeSettings,
|
||||
pub greens: HueRangeSettings,
|
||||
pub cyans: HueRangeSettings,
|
||||
pub blues: HueRangeSettings,
|
||||
pub magentas: HueRangeSettings,
|
||||
}
|
||||
|
||||
/// The percentages of each source channel, plus a constant, that sum to one output channel.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerRow {
|
||||
pub red: f64,
|
||||
pub green: f64,
|
||||
pub blue: f64,
|
||||
pub constant: f64,
|
||||
}
|
||||
|
||||
/// A row for each output channel, or for the single gray channel when monochrome.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerSettings {
|
||||
pub monochrome: bool,
|
||||
pub monochrome_mix: ChannelMixerRow,
|
||||
pub red: ChannelMixerRow,
|
||||
pub green: ChannelMixerRow,
|
||||
pub blue: ChannelMixerRow,
|
||||
}
|
||||
|
||||
/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorInks {
|
||||
pub cyan: f64,
|
||||
pub magenta: f64,
|
||||
pub yellow: f64,
|
||||
pub black: f64,
|
||||
}
|
||||
|
||||
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorSettings {
|
||||
pub mode: RelativeAbsolute,
|
||||
pub reds: SelectiveColorInks,
|
||||
pub yellows: SelectiveColorInks,
|
||||
pub greens: SelectiveColorInks,
|
||||
pub cyans: SelectiveColorInks,
|
||||
pub blues: SelectiveColorInks,
|
||||
pub magentas: SelectiveColorInks,
|
||||
pub whites: SelectiveColorInks,
|
||||
pub neutrals: SelectiveColorInks,
|
||||
pub blacks: SelectiveColorInks,
|
||||
}
|
||||
|
||||
/// Percentage shifts along the three opponent color axes for one tonal range.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceShifts {
|
||||
pub cyan_red: f64,
|
||||
pub magenta_green: f64,
|
||||
pub yellow_blue: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceSettings {
|
||||
pub shadows: ColorBalanceShifts,
|
||||
pub midtones: ColorBalanceShifts,
|
||||
pub highlights: ColorBalanceShifts,
|
||||
pub preserve_luminosity: bool,
|
||||
}
|
||||
|
||||
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
|
||||
fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
|
||||
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
|
||||
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueSaturationSliders {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
|
||||
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
|
||||
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
|
||||
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueRangeSettings {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
|
||||
self.sliders.visit_parameters(visitor, group, [0.; 3]);
|
||||
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
|
||||
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
|
||||
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
|
||||
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
|
||||
}
|
||||
}
|
||||
|
||||
impl ChannelMixerRow {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
|
||||
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
|
||||
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
|
||||
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
|
||||
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectiveColorInks {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
|
||||
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorBalanceShifts {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
|
||||
}
|
||||
}
|
||||
@@ -1,712 +0,0 @@
|
||||
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
|
||||
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
|
||||
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use std::fmt::Debug;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
DropShadow,
|
||||
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
|
||||
InnerShadow,
|
||||
/// Surrounds the content with a soft glow of its silhouette.
|
||||
OuterGlow,
|
||||
/// Glows inward from the content's edges, or outward from its center.
|
||||
InnerGlow,
|
||||
/// Shades the content's interior with soft bands from its silhouette cast two ways.
|
||||
Satin,
|
||||
/// Draws a band of color along the content's silhouette.
|
||||
Outline,
|
||||
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
|
||||
BevelAndEmboss,
|
||||
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
|
||||
PaintOverlay,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Blur => "Blur",
|
||||
Self::DropShadow => "Drop Shadow",
|
||||
Self::InnerShadow => "Inner Shadow",
|
||||
Self::OuterGlow => "Outer Glow",
|
||||
Self::InnerGlow => "Inner Glow",
|
||||
Self::Satin => "Satin",
|
||||
Self::Outline => "Outline",
|
||||
Self::BevelAndEmboss => "Bevel & Emboss",
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
Self::BrightnessContrast => "Brightness/Contrast",
|
||||
Self::Levels => "Levels",
|
||||
Self::Curves => "Curves",
|
||||
Self::BlackAndWhite => "Black & White",
|
||||
Self::HueSaturation => "Hue/Saturation",
|
||||
Self::Invert => "Invert",
|
||||
Self::Threshold => "Threshold",
|
||||
Self::GradientMap => "Gradient Map",
|
||||
Self::Vibrance => "Vibrance",
|
||||
Self::ChannelMixer => "Channel Mixer",
|
||||
Self::SelectiveColor => "Selective Color",
|
||||
Self::Posterize => "Posterize",
|
||||
Self::Exposure => "Exposure",
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an inner glow starts from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum GlowSource {
|
||||
/// Glows inward from the edges.
|
||||
#[default]
|
||||
Edge,
|
||||
/// Glows outward from the center.
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which slopes a bevel shapes from the content's edges.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BevelStyle {
|
||||
/// Slopes up from the edges into the content.
|
||||
#[default]
|
||||
InnerBevel,
|
||||
/// Slopes down from the edges away from the content.
|
||||
OuterBevel,
|
||||
/// Slopes across the edges, half inside the content and half outside.
|
||||
Emboss,
|
||||
/// Slopes away from the edges both ways, as if pressed into the surface along them.
|
||||
PillowEmboss,
|
||||
}
|
||||
|
||||
/// Whether a bevel rises from the surface or sinks into it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum BevelDirection {
|
||||
/// Raised from the surface.
|
||||
#[default]
|
||||
Up,
|
||||
/// Pressed into the surface.
|
||||
Down,
|
||||
}
|
||||
|
||||
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
|
||||
pub fn bevel_smoothing(size: f64) -> f64 {
|
||||
size.max(0.) / 4.
|
||||
}
|
||||
|
||||
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
|
||||
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
|
||||
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
|
||||
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
|
||||
(across * altitude.cos()).extend(altitude.sin())
|
||||
}
|
||||
|
||||
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
let unplaced = match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
};
|
||||
if !unplaced {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
|
||||
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effect(pub Item<EffectKind>);
|
||||
|
||||
impl Effect {
|
||||
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
|
||||
pub fn new(operation: &EffectOperation) -> Self {
|
||||
let mut item = Item::new_from_element(operation.kind());
|
||||
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
|
||||
Self(item)
|
||||
}
|
||||
|
||||
/// This effect's kind.
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
*self.0.element()
|
||||
}
|
||||
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&self.0));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::Color(color),
|
||||
blend_mode,
|
||||
opacity,
|
||||
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: *color.element(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
}),
|
||||
operation => operation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effects(pub List<Effect>);
|
||||
|
||||
impl Effects {
|
||||
/// Creates the list of rows carrying out the given operations in order.
|
||||
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
|
||||
let mut effects = Self::default();
|
||||
for operation in operations {
|
||||
effects.0.push(Item::new_from_element(Effect::new(&operation)));
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// The effects in the order they're carried out.
|
||||
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
|
||||
self.0.iter_element_values()
|
||||
}
|
||||
|
||||
/// The effects after the first `count`.
|
||||
pub fn after(&self, count: usize) -> Self {
|
||||
let mut remaining = Self::default();
|
||||
for effect in self.effects().skip(count) {
|
||||
remaining.0.push(Item::new_from_element(effect.clone()));
|
||||
}
|
||||
remaining
|
||||
}
|
||||
|
||||
/// The effects decoded into the operations renderers carry out, in order.
|
||||
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.reach()).sum()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
|
||||
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
|
||||
match align {
|
||||
StrokeAlign::Outside => (weight, 0.),
|
||||
StrokeAlign::Inside => (0., weight),
|
||||
StrokeAlign::Center => (weight / 2., weight / 2.),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an effect to the item's list, after those already applied to it.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
|
||||
}
|
||||
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
DropShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
OuterGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
/// How far the glow grows into the content before it softens.
|
||||
choke: f64,
|
||||
source: GlowSource,
|
||||
},
|
||||
Satin {
|
||||
color: Color,
|
||||
/// How far each of the two casts of the silhouette is moved, in opposite directions.
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
invert: bool,
|
||||
},
|
||||
Outline {
|
||||
color: Color,
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
},
|
||||
BevelAndEmboss {
|
||||
style: BevelStyle,
|
||||
/// How steep the slopes are, as a percentage.
|
||||
depth: f64,
|
||||
direction: BevelDirection,
|
||||
/// How wide the slopes are.
|
||||
size: f64,
|
||||
/// How much the highlights and shadows are blurred.
|
||||
soften: f64,
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How high the light is above the surface, in degrees from flat to straight overhead.
|
||||
altitude: f64,
|
||||
highlight_color: Color,
|
||||
shadow_color: Color,
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
impl EffectOperation {
|
||||
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
|
||||
pub fn default_for(kind: EffectKind) -> Self {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
Self::DropShadow { .. } => EffectKind::DropShadow,
|
||||
Self::InnerShadow { .. } => EffectKind::InnerShadow,
|
||||
Self::OuterGlow { .. } => EffectKind::OuterGlow,
|
||||
Self::InnerGlow { .. } => EffectKind::InnerGlow,
|
||||
Self::Satin { .. } => EffectKind::Satin,
|
||||
Self::Outline { .. } => EffectKind::Outline,
|
||||
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
match self {
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
|
||||
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::Outline { weight, .. } => weight.max(0.),
|
||||
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::DropShadow => Self::DropShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerShadow => Self::InnerShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::OuterGlow => Self::OuterGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerGlow => Self::InnerGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
choke: 0.,
|
||||
source: GlowSource::default(),
|
||||
},
|
||||
EffectKind::Satin => Self::Satin {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Outline => Self::Outline {
|
||||
color: Color::TRANSPARENT,
|
||||
weight: 0.,
|
||||
align: StrokeAlign::default(),
|
||||
},
|
||||
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
|
||||
style: BevelStyle::default(),
|
||||
depth: 0.,
|
||||
direction: BevelDirection::default(),
|
||||
size: 0.,
|
||||
soften: 0.,
|
||||
angle: 0.,
|
||||
altitude: 0.,
|
||||
highlight_color: Color::TRANSPARENT,
|
||||
shadow_color: Color::TRANSPARENT,
|
||||
},
|
||||
EffectKind::PaintOverlay => Self::PaintOverlay {
|
||||
paint: Graphic::default(),
|
||||
blend_mode: BlendMode::default(),
|
||||
opacity: 0.,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
|
||||
brightness: 0.,
|
||||
contrast: 0.,
|
||||
use_classic: false,
|
||||
classic_pivot: 0.,
|
||||
}),
|
||||
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
|
||||
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
|
||||
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
|
||||
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
|
||||
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
|
||||
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
|
||||
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
|
||||
gradient: Default::default(),
|
||||
reverse: false,
|
||||
}),
|
||||
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
|
||||
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
|
||||
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
|
||||
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
|
||||
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
|
||||
exposure: 0.,
|
||||
offset: 0.,
|
||||
gamma_correction: 0.,
|
||||
}),
|
||||
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
|
||||
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
|
||||
color: Color::TRANSPARENT,
|
||||
density: 0.,
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::splat(4.));
|
||||
visitor.parameter("blur", blur, 4.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::OuterGlow { color, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::InnerGlow { color, blur, choke, source } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("choke", choke, 0.);
|
||||
visitor.parameter("source", source, GlowSource::default());
|
||||
}
|
||||
Self::Satin { color, offset, blur, invert } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::new(10., 4.));
|
||||
visitor.parameter("blur", blur, 14.);
|
||||
visitor.parameter("invert", invert, true);
|
||||
}
|
||||
Self::Outline { color, weight, align } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
visitor.parameter("weight", weight, 3.);
|
||||
visitor.parameter("align", align, StrokeAlign::Outside);
|
||||
}
|
||||
Self::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
visitor.parameter("style", style, BevelStyle::default());
|
||||
visitor.parameter("depth", depth, 100.);
|
||||
visitor.parameter("direction", direction, BevelDirection::default());
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("soften", soften, 0.);
|
||||
visitor.parameter("angle", angle, 120.);
|
||||
visitor.parameter("altitude", altitude, 30.);
|
||||
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
|
||||
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
|
||||
}
|
||||
Self::PaintOverlay { paint, blend_mode, opacity } => {
|
||||
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto a row.
|
||||
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for WriteParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from a row, or its default where the row lacks it.
|
||||
struct ReadParameters<'a>(&'a Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::DropShadow),
|
||||
EffectOperation::InnerShadow {
|
||||
color: Color::RED,
|
||||
offset: DVec2::new(-2., 3.),
|
||||
blur: 1.,
|
||||
spread: 5.,
|
||||
},
|
||||
EffectOperation::OuterGlow {
|
||||
color: Color::BLUE,
|
||||
blur: 8.,
|
||||
spread: 2.,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: Color::GREEN,
|
||||
blur: 3.,
|
||||
choke: 1.,
|
||||
source: GlowSource::Center,
|
||||
},
|
||||
EffectOperation::Satin {
|
||||
color: Color::BLACK,
|
||||
offset: DVec2::new(5., -6.),
|
||||
blur: 2.,
|
||||
invert: false,
|
||||
},
|
||||
EffectOperation::Outline {
|
||||
color: Color::RED,
|
||||
weight: 7.,
|
||||
align: StrokeAlign::Center,
|
||||
},
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style: BevelStyle::PillowEmboss,
|
||||
depth: 250.,
|
||||
direction: BevelDirection::Down,
|
||||
size: 12.,
|
||||
soften: 2.,
|
||||
angle: -45.,
|
||||
altitude: 60.,
|
||||
highlight_color: Color::YELLOW,
|
||||
shadow_color: Color::BLUE,
|
||||
},
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
|
||||
}))),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
opacity: 60.,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
let solid = EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Color::RED),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
};
|
||||
let solid_row = Effect::new(&solid);
|
||||
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
|
||||
assert_eq!(
|
||||
solid_row.operation(),
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
})
|
||||
);
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
let kinds = [
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
let operation = EffectOperation::default_for(kind);
|
||||
assert_eq!(operation.kind(), kind);
|
||||
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
|
||||
}
|
||||
|
||||
// A parameter in one of the node's groups rides the attribute named with the group's prefix
|
||||
let mut levels = EffectOperation::default_for(Levels);
|
||||
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
|
||||
settings.blue.midtones = 1.5;
|
||||
}
|
||||
let row = Effect::new(&levels);
|
||||
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
|
||||
assert_eq!(row.operation(), levels);
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum NoiseType {
|
||||
#[default]
|
||||
Perlin,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2S")]
|
||||
OpenSimplex2S,
|
||||
Cellular,
|
||||
ValueCubic,
|
||||
Value,
|
||||
WhiteNoise,
|
||||
}
|
||||
|
||||
/// Style of layered levels of the noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum FractalType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("Fractional Brownian Motion")]
|
||||
FBm,
|
||||
Ridged,
|
||||
PingPong,
|
||||
#[label("Progressive (Domain Warp Only)")]
|
||||
DomainWarpProgressive,
|
||||
#[label("Independent (Domain Warp Only)")]
|
||||
DomainWarpIndependent,
|
||||
}
|
||||
|
||||
/// Distance function used by the cellular noise.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum CellularDistanceFunction {
|
||||
#[default]
|
||||
Euclidean,
|
||||
#[label("Euclidean Squared (Faster)")]
|
||||
EuclideanSq,
|
||||
Manhattan,
|
||||
Hybrid,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum CellularReturnType {
|
||||
CellValue,
|
||||
#[default]
|
||||
#[label("Nearest (F1)")]
|
||||
Nearest,
|
||||
#[label("Next Nearest (F2)")]
|
||||
NextNearest,
|
||||
#[label("Average (F1 / 2 + F2 / 2)")]
|
||||
Average,
|
||||
#[label("Difference (F2 - F1)")]
|
||||
Difference,
|
||||
#[label("Product (F2 * F1 / 2)")]
|
||||
Product,
|
||||
#[label("Division (F1 / F2)")]
|
||||
Division,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum DomainWarpType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2 Reduced")]
|
||||
OpenSimplex2Reduced,
|
||||
BasicGrid,
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
pub noise_type: NoiseType,
|
||||
pub domain_warp_type: DomainWarpType,
|
||||
pub domain_warp_amplitude: f64,
|
||||
pub fractal_type: FractalType,
|
||||
pub fractal_octaves: i64,
|
||||
pub fractal_lacunarity: f64,
|
||||
pub fractal_gain: f64,
|
||||
pub fractal_weighted_strength: f64,
|
||||
pub fractal_ping_pong_strength: f64,
|
||||
pub cellular_distance_function: CellularDistanceFunction,
|
||||
pub cellular_return_type: CellularReturnType,
|
||||
pub cellular_jitter: f64,
|
||||
}
|
||||
|
||||
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub enum GeneratorPattern {
|
||||
Noise(NoiseSettings),
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
@@ -11,10 +8,8 @@ pub use raster_types;
|
||||
pub use vector_types;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
[package]
|
||||
name = "raster-kernels"
|
||||
description = "The GPU kernels of Graphene's raster operations, with the per-color CPU mapping of those that have one"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,29 +0,0 @@
|
||||
//! The kernels blending one color with another.
|
||||
|
||||
use crate::{MapColor, Wgsl, gpu_param_enum, gpu_params};
|
||||
use core_types::blending::{BlendMode, apply_blend_mode};
|
||||
use core_types::color::Color;
|
||||
|
||||
gpu_param_enum!(i32: BlendMode);
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ColorOverlay {
|
||||
pub(crate) color: Color,
|
||||
pub(crate) blend_mode: BlendMode,
|
||||
pub(crate) opacity: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
let overlay = apply_blend_mode(self.color, pixel, self.blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
}
|
||||
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/color_overlay.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
//! The passes of a Gaussian or box blur, which halve an image until its kernel fits one pass, blur it along each axis, and double it back.
|
||||
|
||||
use crate::{RasterKernel, ToGpuParams, Wgsl, gpu_param_enum, gpu_params};
|
||||
|
||||
/// The farthest texel from the center a blur pass weighs, beyond which the image is first halved until the kernel fits.
|
||||
pub const MAX_BLUR_REACH: i32 = 64;
|
||||
|
||||
/// The radius of a blur over texels `scale` image pixels wide, and the farthest texel from the center it weighs.
|
||||
///
|
||||
/// A box covers its whole texels and a fraction of the texel at each end, which keeps the window as wide as the whole pixel window of the unhalved image once halved,
|
||||
/// and a Gaussian leaves out the blur that halving and doubling the image add.
|
||||
pub fn blur_extent(radius: f64, box_blur: bool, scale: u32) -> (f32, i32) {
|
||||
let scale = scale as f64;
|
||||
if box_blur {
|
||||
let radius = ((radius as i32) as f64 + 0.5) / scale - 0.5;
|
||||
(radius as f32, radius.ceil() as i32)
|
||||
} else {
|
||||
let radius = (radius * radius - (scale * scale - 1.) / 3.).max(0.).sqrt() / scale;
|
||||
(radius as f32, (3. * radius).ceil() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors a blur pass reads from its input or writes to its output, around the premultiplied colors it sums.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(u32)]
|
||||
pub enum BlurSpace {
|
||||
/// Values summed as they are, such as premultiplied colors or coverage.
|
||||
Premultiplied,
|
||||
/// Straight-alpha linear-light colors, premultiplied for summing.
|
||||
Linear,
|
||||
/// Straight-alpha linear-light colors, gamma-encoded and premultiplied for summing.
|
||||
Gamma,
|
||||
}
|
||||
|
||||
impl From<BlurSpace> for u32 {
|
||||
fn from(space: BlurSpace) -> Self {
|
||||
space as u32
|
||||
}
|
||||
}
|
||||
|
||||
gpu_param_enum!(u32: BlurSpace);
|
||||
|
||||
gpu_params! {
|
||||
/// Averages each 2x2 block of texels `scale` image pixels wide, weighed by how much of the `full_size` image each covers.
|
||||
#[derive(Clone)]
|
||||
pub struct BlurHalve {
|
||||
pub space: BlurSpace,
|
||||
pub scale: i32,
|
||||
pub full_size: [i32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurHalve {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_halve.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// One axis of a blur over texels `scale` image pixels wide, each weighed by how much of the `full_size` image it covers.
|
||||
#[derive(Clone)]
|
||||
pub struct BlurPass {
|
||||
pub radius: f32,
|
||||
pub reach: i32,
|
||||
pub box_blur: bool,
|
||||
pub space: BlurSpace,
|
||||
pub scale: i32,
|
||||
pub full_size: [i32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlurHorizontal(pub BlurPass);
|
||||
|
||||
impl ToGpuParams for BlurHorizontal {
|
||||
type Params = BlurPass;
|
||||
fn to_params(&self) -> BlurPass {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurHorizontal {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_horizontal.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads its input in pairs of texels sampled bilinearly between them, so the input must be in a filterable format.
|
||||
pub struct BlurVertical(pub BlurPass);
|
||||
|
||||
impl ToGpuParams for BlurVertical {
|
||||
type Params = BlurPass;
|
||||
fn to_params(&self) -> BlurPass {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurVertical {
|
||||
const INPUTS: usize = 1;
|
||||
const FILTERED: bool = true;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_vertical.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
pub struct BlurUpsample {
|
||||
pub scale: f32,
|
||||
pub space: BlurSpace,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurUpsample {
|
||||
const INPUTS: usize = 1;
|
||||
const FILTERED: bool = true;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_upsample.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
//! The kernels of the passes that carry out an item's effects on the pixels of its content.
|
||||
//! They work on images of premultiplied gamma-encoded channels, as Vello GPU blends, and on coverage held in every channel.
|
||||
|
||||
use crate::{RasterKernel, Wgsl, gpu_params};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
|
||||
pub fn premultiplied_gamma_channels(color: Color) -> Color {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
Color::from_rgbaf32_unchecked(red * alpha, green * alpha, blue * alpha, alpha)
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The straight-alpha linear-light content, placed where its input lies, as the channels the passes work with, multiplied by `amount`.
|
||||
#[derive(Clone)]
|
||||
pub struct EffectEncode {
|
||||
pub amount: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for EffectEncode {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_encode.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The channels the passes work with, back into straight-alpha linear-light colors.
|
||||
#[derive(Clone)]
|
||||
pub struct EffectDecode {}
|
||||
}
|
||||
|
||||
impl RasterKernel for EffectDecode {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_decode.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of the content's silhouette, or of the area outside it if `inverse`, cast by its input's placement.
|
||||
#[derive(Clone)]
|
||||
pub struct CastSilhouette {
|
||||
pub inverse: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for CastSilhouette {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_cast_silhouette.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The most coverage of its three inputs, the same coverage placed at the pixel and a step to either side along an axis.
|
||||
#[derive(Clone)]
|
||||
pub struct Dilate {}
|
||||
}
|
||||
|
||||
impl RasterKernel for Dilate {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_dilate.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// A silhouette's coverage in `color`, given as [`premultiplied_gamma_channels`].
|
||||
#[derive(Clone)]
|
||||
pub struct Tint {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Tint {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_tint.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// Stacks a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), over the shadows and glows beneath the content.
|
||||
#[derive(Clone)]
|
||||
pub struct Accumulate {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Accumulate {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_accumulate.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image with a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), placed over it within the full-strength content.
|
||||
#[derive(Clone)]
|
||||
pub struct CompositeWithin {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for CompositeWithin {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_composite_within.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image with the shadows and glows beneath it, knocked out by the full-strength content.
|
||||
#[derive(Clone)]
|
||||
pub struct CompositeBeneath {}
|
||||
}
|
||||
|
||||
impl RasterKernel for CompositeBeneath {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_composite_beneath.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of everything a coverage doesn't cover.
|
||||
#[derive(Clone)]
|
||||
pub struct InvertCoverage {}
|
||||
}
|
||||
|
||||
impl RasterKernel for InvertCoverage {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_invert_coverage.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of satin's shading, from the two casts of the silhouette.
|
||||
#[derive(Clone)]
|
||||
pub struct SatinShading {
|
||||
pub invert: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for SatinShading {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_satin.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// Starts a jump flood from the texels inside the content's silhouette, or outside it if `inward`.
|
||||
#[derive(Clone)]
|
||||
pub struct JumpFloodSeed {
|
||||
pub inward: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for JumpFloodSeed {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_jump_flood_seed.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// One step of a jump flood, spreading the nearest seeds found so far by `step` texels.
|
||||
#[derive(Clone)]
|
||||
pub struct JumpFloodStep {
|
||||
pub step: i32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for JumpFloodStep {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_jump_flood_step.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of the band `width` texels wide along the silhouette's edge, from a finished jump flood.
|
||||
#[derive(Clone)]
|
||||
pub struct EdgeBand {
|
||||
pub width: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for EdgeBand {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_edge_band.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// A bevel's height from 0 to 1, from the two finished jump floods across the silhouette's edge. `style` is a [`graphic_types::BevelStyle`].
|
||||
#[derive(Clone)]
|
||||
pub struct BevelHeight {
|
||||
pub size: f32,
|
||||
pub style: u32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BevelHeight {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_bevel_height.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of a bevel's highlight, or if `shadow` of its shadow, from its height lit from the direction of the unit vector `light`.
|
||||
#[derive(Clone)]
|
||||
pub struct BevelShading {
|
||||
pub slope: f32,
|
||||
pub light_x: f32,
|
||||
pub light_y: f32,
|
||||
pub light_z: f32,
|
||||
pub shadow: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BevelShading {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_bevel_shading.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The first image, emptied wherever the second is empty, since an adjustment that changes alpha would otherwise conjure content from the empty space around it.
|
||||
#[derive(Clone)]
|
||||
pub struct KeepEmpty {}
|
||||
}
|
||||
|
||||
impl RasterKernel for KeepEmpty {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
|
||||
#[derive(Clone)]
|
||||
pub struct PaintOverlay {
|
||||
pub blend_mode: BlendMode,
|
||||
pub opacity: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for PaintOverlay {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||
|
||||
use crate::{RasterKernel, RasterKernelVisitor, Wgsl, gpu_params};
|
||||
use glam::{DVec2, UVec2, Vec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
|
||||
/// Hands `visitor` the kernel rendering `pattern` across `area` of its own space, from its minimum to its maximum corner, into a grid of `size` pixels.
|
||||
pub fn visit_generator_kernel<V: RasterKernelVisitor>(pattern: &GeneratorPattern, area: [DVec2; 2], size: UVec2, visitor: V) -> V::Output {
|
||||
let texel = ((area[1] - area[0]).as_vec2() / size.as_vec2()).to_array();
|
||||
let corner = area[0].as_vec2().to_array();
|
||||
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(settings) => visit_noise_kernel(settings, corner, texel, visitor),
|
||||
GeneratorPattern::Mandelbrot => visitor.visit(&Mandelbrot {
|
||||
corner: (Vec2::from(corner) * 3. - Vec2::new(2., 1.5)).to_array(),
|
||||
texel: (Vec2::from(texel) * 3.).to_array(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_noise_kernel<V: RasterKernelVisitor>(settings: &NoiseSettings, corner: [f32; 2], texel: [f32; 2], visitor: V) -> V::Output {
|
||||
let NoiseSettings {
|
||||
seed,
|
||||
scale,
|
||||
noise_type,
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude,
|
||||
fractal_type,
|
||||
fractal_octaves,
|
||||
fractal_lacunarity,
|
||||
fractal_gain,
|
||||
fractal_weighted_strength,
|
||||
fractal_ping_pong_strength,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
cellular_jitter,
|
||||
} = *settings;
|
||||
|
||||
if noise_type == NoiseType::WhiteNoise {
|
||||
return visitor.visit(&WhiteNoise { corner, texel, seed: seed as u32 });
|
||||
}
|
||||
|
||||
let domain_warp_type = match domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(0),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(1),
|
||||
DomainWarpType::BasicGrid => Some(2),
|
||||
};
|
||||
let noise = NoiseState {
|
||||
seed: seed as i32,
|
||||
frequency: 1. / (scale as f32).max(f32::EPSILON),
|
||||
noise_type: match noise_type {
|
||||
NoiseType::OpenSimplex2 | NoiseType::WhiteNoise => 0,
|
||||
NoiseType::OpenSimplex2S => 1,
|
||||
NoiseType::Cellular => 2,
|
||||
NoiseType::Perlin => 3,
|
||||
NoiseType::ValueCubic => 4,
|
||||
NoiseType::Value => 5,
|
||||
},
|
||||
rotation_type_3d: 0,
|
||||
fractal_type: match fractal_type {
|
||||
FractalType::None => 0,
|
||||
FractalType::FBm => 1,
|
||||
FractalType::Ridged => 2,
|
||||
FractalType::PingPong => 3,
|
||||
FractalType::DomainWarpProgressive => 4,
|
||||
FractalType::DomainWarpIndependent => 5,
|
||||
},
|
||||
octaves: fractal_octaves as i32,
|
||||
lacunarity: fractal_lacunarity as f32,
|
||||
gain: fractal_gain as f32,
|
||||
weighted_strength: fractal_weighted_strength as f32,
|
||||
ping_pong_strength: fractal_ping_pong_strength as f32,
|
||||
cellular_distance_func: match cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => 0,
|
||||
CellularDistanceFunction::EuclideanSq => 1,
|
||||
CellularDistanceFunction::Manhattan => 2,
|
||||
CellularDistanceFunction::Hybrid => 3,
|
||||
},
|
||||
cellular_return_type: match cellular_return_type {
|
||||
CellularReturnType::CellValue => 0,
|
||||
CellularReturnType::Nearest => 1,
|
||||
CellularReturnType::NextNearest => 2,
|
||||
CellularReturnType::Average => 3,
|
||||
CellularReturnType::Difference => 4,
|
||||
CellularReturnType::Product => 5,
|
||||
CellularReturnType::Division => 6,
|
||||
},
|
||||
cellular_jitter_mod: cellular_jitter as f32,
|
||||
domain_warp_type: domain_warp_type.unwrap_or(0),
|
||||
domain_warp_amp: domain_warp_amplitude as f32,
|
||||
};
|
||||
|
||||
visitor.visit(&NoisePattern {
|
||||
corner,
|
||||
texel,
|
||||
domain_warp: domain_warp_type.is_some() && domain_warp_amplitude > 0.,
|
||||
noise,
|
||||
})
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct NoiseState {
|
||||
seed: i32,
|
||||
frequency: f32,
|
||||
noise_type: i32,
|
||||
rotation_type_3d: i32,
|
||||
fractal_type: i32,
|
||||
octaves: i32,
|
||||
lacunarity: f32,
|
||||
gain: f32,
|
||||
weighted_strength: f32,
|
||||
ping_pong_strength: f32,
|
||||
cellular_distance_func: i32,
|
||||
cellular_return_type: i32,
|
||||
cellular_jitter_mod: f32,
|
||||
domain_warp_type: i32,
|
||||
domain_warp_amp: f32,
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct NoisePattern {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
domain_warp: bool,
|
||||
noise: NoiseState,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for NoisePattern {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/fast_noise_lite.wgsl"), "\n", include_str!("wgsl/noise_pattern.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct WhiteNoise {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
seed: u32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for WhiteNoise {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/white_noise.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct Mandelbrot {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Mandelbrot {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::body(
|
||||
r#"
|
||||
let c = vec2<f32>(coord) * vec2<f32>(texel[0], texel[1]) + vec2<f32>(corner[0], corner[1]);
|
||||
var z = vec2<f32>(0.);
|
||||
for (var iteration = 0u; iteration < 1024u; iteration++) {
|
||||
z = vec2<f32>(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
let magnitude_squared = dot(z, z);
|
||||
if magnitude_squared > 65536. {
|
||||
let smooth_iteration = f32(iteration) + 1. - log2(0.5 * log2(magnitude_squared));
|
||||
return vec4<f32>(vec3<f32>(clamp(smooth_iteration / 255., 0., 1.)), 1.);
|
||||
}
|
||||
}
|
||||
return vec4<f32>(1.);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
use core_types::color::Color;
|
||||
|
||||
/// The WGSL of a [`MapColor`] or [`RasterKernel`], which sees the shared prelude and the `Params` struct with its `params()` accessor.
|
||||
pub enum Wgsl {
|
||||
/// The body of the kernel's function, with every parameter bound as a local.
|
||||
Body(String),
|
||||
/// A source defining the kernel's function and any helpers it calls.
|
||||
Function(String),
|
||||
}
|
||||
|
||||
impl Wgsl {
|
||||
pub fn body(body: impl Into<String>) -> Self {
|
||||
Self::Body(body.into())
|
||||
}
|
||||
|
||||
pub fn function(source: impl Into<String>) -> Self {
|
||||
Self::Function(source.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter struct passed to a [`MapColor`] or [`RasterKernel`] shader, declared with [`gpu_params!`].
|
||||
pub trait GpuParams {
|
||||
fn write(&self, slots: &mut Vec<u32>);
|
||||
/// The WGSL declarations of the struct and its nested structs, aliased as `Params`, and the `params()` accessor, or nothing for a struct without fields.
|
||||
fn wgsl() -> String;
|
||||
/// The WGSL statements binding every field of `params()` as a local.
|
||||
fn wgsl_locals() -> String;
|
||||
/// The WGSL declaring the texture and accessors of each lookup field, bound in order from `binding`.
|
||||
fn wgsl_lookups(_binding: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
/// The tables of the lookup fields, in order.
|
||||
fn lookups(&self) -> Vec<RasterKernelLookup<'_>> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A field type of a [`gpu_params!`] struct, occupying `SLOTS` 32-bit uniform slots.
|
||||
pub trait GpuParamField {
|
||||
const SLOTS: usize;
|
||||
/// Whether the type is a lookup table, bound as its own texture rather than packed into slots, which only a top-level field may be.
|
||||
const LOOKUP: bool = false;
|
||||
fn wgsl_type() -> String;
|
||||
fn write(&self, slots: &mut Vec<u32>);
|
||||
fn wgsl_read(slot: usize) -> String;
|
||||
/// Appends the WGSL struct declarations this type needs, each only once.
|
||||
fn wgsl_declarations(_declarations: &mut Vec<String>) {}
|
||||
/// The WGSL declaring a lookup table's texture at `binding` and its accessors named after `field`.
|
||||
fn wgsl_lookup(_field: &str, _binding: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn lookup<'a>(&'a self, _lookups: &mut Vec<RasterKernelLookup<'a>>) {}
|
||||
}
|
||||
|
||||
fn wgsl_slot(slot: usize) -> String {
|
||||
format!("uniform_params[{}][{}]", slot / 4, slot % 4)
|
||||
}
|
||||
|
||||
impl GpuParamField for f32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"f32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(self.to_bits());
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("bitcast<f32>({})", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for u32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"u32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
wgsl_slot(slot)
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for i32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"i32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self as u32);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("bitcast<i32>({})", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for bool {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"bool".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self as u32);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("{} != 0u", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for Color {
|
||||
const SLOTS: usize = 4;
|
||||
fn wgsl_type() -> String {
|
||||
"vec4<f32>".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.extend(self.to_vec4().to_array().map(f32::to_bits));
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let channels = (slot..slot + 4).map(<f32 as GpuParamField>::wgsl_read).collect::<Vec<_>>();
|
||||
format!("vec4<f32>({})", channels.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GpuParamField, const N: usize> GpuParamField for [T; N] {
|
||||
const SLOTS: usize = N * T::SLOTS;
|
||||
fn wgsl_type() -> String {
|
||||
format!("array<{}, {N}>", T::wgsl_type())
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
self.iter().for_each(|element| element.write(slots));
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let elements = (0..N).map(|index| T::wgsl_read(slot + index * T::SLOTS)).collect::<Vec<_>>();
|
||||
format!("{}({})", Self::wgsl_type(), elements.join(", "))
|
||||
}
|
||||
fn wgsl_declarations(declarations: &mut Vec<String>) {
|
||||
T::wgsl_declarations(declarations);
|
||||
}
|
||||
}
|
||||
|
||||
/// A lookup field of entries spread evenly across 0 to 1, read in WGSL by `fn <field>(t: f32) -> vec4<f32>`, which clamps `t` and interpolates linearly between the nearest two entries.
|
||||
///
|
||||
/// Holds 1 to 4096 entries, the texture width every device supports.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Lut1d(pub Vec<Color>);
|
||||
|
||||
impl GpuParamField for Lut1d {
|
||||
const SLOTS: usize = 0;
|
||||
const LOOKUP: bool = true;
|
||||
fn wgsl_type() -> String {
|
||||
String::new()
|
||||
}
|
||||
fn write(&self, _: &mut Vec<u32>) {}
|
||||
fn wgsl_read(_: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn wgsl_lookup(field: &str, binding: usize) -> String {
|
||||
include_str!("wgsl/lut_1d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
|
||||
}
|
||||
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
|
||||
assert!((1..=4096).contains(&self.0.len()), "A 1D lookup table holds 1 to 4096 entries");
|
||||
lookups.push(RasterKernelLookup::Lut1d(&self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// A lookup field of a `size` cubed grid of entries, red fastest, then green, then blue, read in WGSL by `fn <field>_load(index: vec3<i32>) -> vec4<f32>`,
|
||||
/// which clamps the index to the grid, and `fn <field>_size() -> i32`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Lut3d {
|
||||
pub size: u32,
|
||||
pub data: Vec<Color>,
|
||||
}
|
||||
|
||||
impl GpuParamField for Lut3d {
|
||||
const SLOTS: usize = 0;
|
||||
const LOOKUP: bool = true;
|
||||
fn wgsl_type() -> String {
|
||||
String::new()
|
||||
}
|
||||
fn write(&self, _: &mut Vec<u32>) {}
|
||||
fn wgsl_read(_: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn wgsl_lookup(field: &str, binding: usize) -> String {
|
||||
include_str!("wgsl/lut_3d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
|
||||
}
|
||||
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
|
||||
assert_eq!(self.data.len(), self.size.pow(3) as usize, "A 3D lookup table holds `size` cubed entries");
|
||||
lookups.push(RasterKernelLookup::Lut3d { size: self.size, data: &self.data });
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares a struct usable as [`GpuParams`] and as a nested [`GpuParamField`], generating its packing and WGSL unpacking.
|
||||
///
|
||||
/// The WGSL struct takes the Rust struct's name, so it must not collide with other WGSL names in the kernel.
|
||||
/// Lookup fields such as [`Lut1d`] and [`Lut3d`] stay out of the WGSL struct, read instead through accessors named after the field.
|
||||
#[macro_export]
|
||||
macro_rules! gpu_params {
|
||||
($(#[$attribute:meta])* $vis:vis struct $name:ident { $($(#[$field_attribute:meta])* $field_vis:vis $field:ident: $ty:ty),* $(,)? }) => {
|
||||
$(#[$attribute])*
|
||||
$vis struct $name {
|
||||
$($(#[$field_attribute])* $field_vis $field: $ty),*
|
||||
}
|
||||
|
||||
impl $crate::GpuParamField for $name {
|
||||
const SLOTS: usize = 0 $(+ <$ty as $crate::GpuParamField>::SLOTS)*;
|
||||
fn wgsl_type() -> String {
|
||||
stringify!($name).into()
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
$(<$ty as $crate::GpuParamField>::write(&self.$field, slots);)*
|
||||
}
|
||||
|
||||
#[allow(unused_mut, unused_variables, unused_assignments)]
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let mut slot = slot;
|
||||
let reads: Vec<(bool, String)> = vec![$({
|
||||
let read = <$ty as $crate::GpuParamField>::wgsl_read(slot);
|
||||
slot += <$ty as $crate::GpuParamField>::SLOTS;
|
||||
(<$ty as $crate::GpuParamField>::LOOKUP, read)
|
||||
}),*];
|
||||
let reads: Vec<String> = reads.into_iter().filter(|(lookup, _)| !lookup).map(|(_, read)| read).collect();
|
||||
format!("{}({})", stringify!($name), reads.join(", "))
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn wgsl_declarations(declarations: &mut Vec<String>) {
|
||||
$(<$ty as $crate::GpuParamField>::wgsl_declarations(declarations);)*
|
||||
let fields: Vec<(bool, String)> = vec![$((
|
||||
<$ty as $crate::GpuParamField>::LOOKUP,
|
||||
format!("{}: {}", stringify!($field), <$ty as $crate::GpuParamField>::wgsl_type())
|
||||
)),*];
|
||||
let fields: Vec<String> = fields.into_iter().filter(|(lookup, _)| !lookup).map(|(_, field)| field).collect();
|
||||
if fields.is_empty() {
|
||||
return;
|
||||
}
|
||||
let declaration = format!("struct {} {{\n\t{},\n}}\n", stringify!($name), fields.join(",\n\t"));
|
||||
if !declarations.contains(&declaration) {
|
||||
declarations.push(declaration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl $crate::GpuParams for $name {
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
<Self as $crate::GpuParamField>::write(self, slots);
|
||||
}
|
||||
|
||||
fn wgsl() -> String {
|
||||
let mut declarations = Vec::new();
|
||||
<Self as $crate::GpuParamField>::wgsl_declarations(&mut declarations);
|
||||
if declarations.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!(
|
||||
"{}\nalias Params = {};\n\nfn params() -> Params {{\n\treturn {};\n}}\n",
|
||||
declarations.join("\n"),
|
||||
stringify!($name),
|
||||
<Self as $crate::GpuParamField>::wgsl_read(0)
|
||||
)
|
||||
}
|
||||
|
||||
fn wgsl_locals() -> String {
|
||||
let fields: &[(bool, &str)] = &[$((<$ty as $crate::GpuParamField>::LOOKUP, stringify!($field))),*];
|
||||
let fields: Vec<&str> = fields.iter().filter(|(lookup, _)| !lookup).map(|(_, field)| *field).collect();
|
||||
if fields.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let locals = fields.iter().map(|field| format!("\tlet {field} = parameters.{field};\n")).collect::<String>();
|
||||
format!("\tlet parameters = params();\n{locals}")
|
||||
}
|
||||
|
||||
#[allow(unused_mut, unused_variables, unused_assignments)]
|
||||
fn wgsl_lookups(binding: usize) -> String {
|
||||
let mut binding = binding;
|
||||
let mut source = String::new();
|
||||
$(if <$ty as $crate::GpuParamField>::LOOKUP {
|
||||
source += &<$ty as $crate::GpuParamField>::wgsl_lookup(stringify!($field), binding);
|
||||
binding += 1;
|
||||
})*
|
||||
source
|
||||
}
|
||||
|
||||
#[allow(unused_mut)]
|
||||
fn lookups(&self) -> Vec<$crate::RasterKernelLookup<'_>> {
|
||||
let mut lookups = Vec::new();
|
||||
$(<$ty as $crate::GpuParamField>::lookup(&self.$field, &mut lookups);)*
|
||||
lookups
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Implements [`GpuParamField`] for enums converting into the `u32` or `i32` primitive `$repr`, such as through `IntoPrimitive`.
|
||||
#[macro_export]
|
||||
macro_rules! gpu_param_enum {
|
||||
($repr:ident: $($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl $crate::GpuParamField for $ty {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
<$repr as $crate::GpuParamField>::wgsl_type()
|
||||
}
|
||||
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
<$repr as $crate::GpuParamField>::write(&$repr::from(*self), slots);
|
||||
}
|
||||
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
<$repr as $crate::GpuParamField>::wgsl_read(slot)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
/// The [`GpuParams`] a kernel passes to its shader, which is the kernel itself unless it implements this to flatten richer data.
|
||||
pub trait ToGpuParams {
|
||||
type Params: GpuParams;
|
||||
fn to_params(&self) -> Self::Params;
|
||||
}
|
||||
|
||||
impl<T: GpuParams + Clone> ToGpuParams for T {
|
||||
type Params = T;
|
||||
fn to_params(&self) -> T {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A per-pixel color mapping, run by `map_cpu` on the CPU and by its WGSL on the GPU, which must agree.
|
||||
///
|
||||
/// Its WGSL function is `fn map_color(color: vec4<f32>) -> vec4<f32>`.
|
||||
pub trait MapColor: ToGpuParams + 'static {
|
||||
fn map_cpu(&self, color: Color) -> Color;
|
||||
fn wgsl() -> Wgsl;
|
||||
}
|
||||
|
||||
/// A GPU-only kernel computing each output pixel from `INPUTS` input rasters, which a type implements instead of [`MapColor`], not alongside it.
|
||||
///
|
||||
/// Its WGSL function is `fn kernel(coord: vec2<i32>) -> vec4<f32>`, which may call `output_size()` and, for each input `i`,
|
||||
/// `input_i_size()`, `input_i_load(coord)` reading the input's own texel clamped to its edge,
|
||||
/// and `input_i_at(coord)` sampling the input bilinearly where the output pixel's center lies, transparent beyond the input.
|
||||
pub trait RasterKernel: ToGpuParams + 'static {
|
||||
const INPUTS: usize;
|
||||
/// Whether the inputs are bound filterable, adding `input_i_sample(texel)` sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge.
|
||||
/// Every input must then be in a filterable format such as `Rgba16Float`, which the executor's raster format isn't.
|
||||
const FILTERED: bool = false;
|
||||
fn wgsl() -> Wgsl;
|
||||
}
|
||||
|
||||
fn shader_module<Params: GpuParams>(signature: &str, wgsl: Wgsl, inputs: usize) -> String {
|
||||
let function = match wgsl {
|
||||
Wgsl::Body(body) => format!("{signature} {{\n{}{body}\n}}", Params::wgsl_locals()),
|
||||
Wgsl::Function(source) => source,
|
||||
};
|
||||
format!("{}\n{}\n{}\n{function}", include_str!("wgsl/prelude.wgsl"), Params::wgsl(), Params::wgsl_lookups(2 + inputs))
|
||||
}
|
||||
|
||||
/// The WGSL module running a [`MapColor`] on each texel of its one input.
|
||||
pub fn map_color_module<K: MapColor>() -> String {
|
||||
let module = shader_module::<K::Params>("fn map_color(color: vec4<f32>) -> vec4<f32>", K::wgsl(), 1);
|
||||
format!("{module}\nfn kernel(coord: vec2<i32>) -> vec4<f32> {{\n\treturn map_color(input_0_load(coord));\n}}\n")
|
||||
}
|
||||
|
||||
/// The WGSL module of a [`RasterKernel`].
|
||||
pub fn raster_kernel_module<K: RasterKernel>() -> String {
|
||||
shader_module::<K::Params>("fn kernel(coord: vec2<i32>) -> vec4<f32>", K::wgsl(), K::INPUTS)
|
||||
}
|
||||
|
||||
/// A lookup table of a kernel, bound as an `Rgba32Float` texture after its inputs.
|
||||
pub enum RasterKernelLookup<'a> {
|
||||
/// A `width x 1` 2D texture of at most 4096 entries.
|
||||
Lut1d(&'a [Color]),
|
||||
/// A `size x size x size` 3D texture, its entries ordered with x fastest, then y, then z.
|
||||
Lut3d { size: u32, data: &'a [Color] },
|
||||
}
|
||||
|
||||
/// Receives a [`RasterKernel`] whose type depends on what it was picked for, such as the pattern a generator renders.
|
||||
pub trait RasterKernelVisitor {
|
||||
type Output;
|
||||
fn visit<K: RasterKernel>(self, kernel: &K) -> Self::Output;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//! The kernels raster operations are carried out with: each a plain-data struct with the WGSL the GPU runs it by, and for those mapping each color alone, the CPU mapping that colors and gradients are adjusted by.
|
||||
//! Running them on rasters is the job of `wgpu-executor`.
|
||||
|
||||
pub mod adjustments;
|
||||
pub mod blending;
|
||||
pub mod blur;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effects;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
|
||||
pub use kernel::*;
|
||||
@@ -1,6 +0,0 @@
|
||||
// Stacks a tinted silhouette (input 1's coverage) over the shadows and glows beneath the content (input 0)
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let beneath = input_0_load(coord);
|
||||
let tinted = params().color * input_1_load(coord).a;
|
||||
return tinted + beneath * (1. - tinted.a);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// A bevel's height from 0 to 1, shaped by the style over a slope `size` texels wide, from the nearest texels inside (input 0) and outside (input 1)
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let to_inside = input_0_load(coord);
|
||||
let to_outside = input_1_load(coord);
|
||||
let size = parameters.size;
|
||||
|
||||
// Texels inside the silhouette are those at no distance from it, and the edge lies about half a texel short of the nearest texel across it
|
||||
let far = 4. * size + 4.;
|
||||
var signed_distance: f32;
|
||||
if to_inside.z > 0.5 && dot(to_inside.xy, to_inside.xy) == 0. {
|
||||
signed_distance = select(far, length(to_outside.xy) - 0.5, to_outside.z > 0.5);
|
||||
} else {
|
||||
signed_distance = select(-far, 0.5 - length(to_inside.xy), to_inside.z > 0.5);
|
||||
}
|
||||
|
||||
var progress: f32;
|
||||
switch parameters.style {
|
||||
case 0u: {
|
||||
progress = signed_distance / size;
|
||||
}
|
||||
case 1u: {
|
||||
progress = (signed_distance + size) / size;
|
||||
}
|
||||
case 2u: {
|
||||
progress = (signed_distance + size / 2.) / size;
|
||||
}
|
||||
default: {
|
||||
progress = abs(signed_distance) / (size / 2.);
|
||||
}
|
||||
}
|
||||
let height = clamp(progress, 0., 1.);
|
||||
return vec4<f32>(height * height * (3. - 2. * height));
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
// How far the light brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short.
|
||||
// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface.
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let gradient = vec2<f32>(
|
||||
input_0_load(coord + vec2<i32>(1, 0)).a - input_0_load(coord - vec2<i32>(1, 0)).a,
|
||||
input_0_load(coord + vec2<i32>(0, 1)).a - input_0_load(coord - vec2<i32>(0, 1)).a,
|
||||
) / 2.;
|
||||
let light = vec3<f32>(parameters.light_x, parameters.light_y, parameters.light_z);
|
||||
let shade = dot(normalize(vec3<f32>(-parameters.slope * gradient, 1.)), light);
|
||||
|
||||
if parameters.shadow {
|
||||
return vec4<f32>(clamp((light.z - shade) / max(light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
return vec4<f32>(clamp((shade - light.z) / max(1. - light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// The coverage of the content's silhouette, or of the area outside it if `inverse`, where the input's placement casts it
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let coverage = input_0_at(coord).a;
|
||||
return vec4<f32>(select(coverage, 1. - coverage, params().inverse));
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Places the shadows and glows (input 1) beneath the image (input 0), knocked out by the content at full strength (input 2) so a faded fill doesn't reveal them
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let image = input_0_load(coord);
|
||||
let beneath = input_1_load(coord);
|
||||
let full_content = input_2_load(coord);
|
||||
return image + beneath * (1. - full_content.a);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Places a tinted silhouette (input 1's coverage) over the image (input 0), within the content at full strength (input 2) so it stays visible over a faded fill
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let image = input_0_load(coord);
|
||||
let tinted = params().color * input_1_load(coord).a;
|
||||
let full_content = input_2_load(coord);
|
||||
return tinted * full_content.a + image * (1. - tinted.a);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Premultiplied gamma-encoded channels back into a straight-alpha linear-light color
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let color = input_0_load(coord);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(srgb_to_linear(max(color.rgb / color.a, vec3<f32>(0.))), color.a);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
// Grows the shapes by one step along an axis, from the coverage placed at the pixel and one step to either side, so steps that double each time grow them by any distance in a few passes
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
return vec4<f32>(max(input_0_at(coord).a, max(input_1_at(coord).a, input_2_at(coord).a)));
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Covers the texels within `width` texels of the edge, which lies about half a texel short of the nearest seed, fading out over one texel
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let nearest = input_0_load(coord);
|
||||
if nearest.z < 0.5 {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(clamp(params().width + 1. - length(nearest.xy), 0., 1.));
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// The straight-alpha linear-light content, sampled where the output pixel lies, as the premultiplied gamma-encoded channels the effects are carried out in, faded by `amount`
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let color = input_0_at(coord);
|
||||
return vec4<f32>(linear_to_srgb(max(color.rgb, vec3<f32>(0.))) * color.a, color.a) * params().amount;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
return vec4<f32>(1. - input_0_load(coord).a);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Jump flooding keeps each texel's offset to the nearest seed found so far (xy) and whether one is found (z).
|
||||
// The seeds are the texels inside the content's silhouette, or outside it if `inward`, and each is its own nearest.
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let inside = input_0_load(coord).a >= 0.5;
|
||||
let seed = inside != params().inward;
|
||||
return vec4<f32>(0., 0., select(0., 1., seed), 0.);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Takes the nearest of the seeds that the texel and its eight neighbors `step` texels away have found so far
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let step = params().step;
|
||||
|
||||
var best = input_0_load(coord);
|
||||
for (var neighbor_y = -1; neighbor_y <= 1; neighbor_y++) {
|
||||
for (var neighbor_x = -1; neighbor_x <= 1; neighbor_x++) {
|
||||
let direction = vec2<i32>(neighbor_x, neighbor_y);
|
||||
let neighbor = coord + direction * step;
|
||||
if any(neighbor < vec2<i32>(0)) || any(neighbor >= input_0_size()) {
|
||||
continue;
|
||||
}
|
||||
let found = input_0_load(neighbor);
|
||||
if found.z < 0.5 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let candidate = found.xy + vec2<f32>(direction * step);
|
||||
if best.z < 0.5 || dot(candidate, candidate) < dot(best.xy, best.xy) {
|
||||
best = vec4<f32>(candidate, 1., 0.);
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// The first image, emptied wherever the second is empty
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
if input_1_load(coord).a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return input_0_load(coord);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
// The blend modes work on straight linear colors, as they do for a solid color overlay
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let image = input_0_load(coord);
|
||||
let paint = input_1_load(coord);
|
||||
if image.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
if paint.a <= 0. {
|
||||
return image;
|
||||
}
|
||||
|
||||
let backdrop = vec4<f32>(srgb_to_linear(image.rgb / image.a), 1.);
|
||||
let blended = apply_blend_mode(vec4<f32>(paint.rgb, 1.), backdrop, parameters.blend_mode);
|
||||
let mixed = mix(backdrop.rgb, blended.rgb, parameters.opacity * paint.a);
|
||||
|
||||
return vec4<f32>(linear_to_srgb(mixed) * image.a, image.a);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Satin's shading from two casts of the silhouette: how much one covers without the other, or how much they agree if `invert`
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let difference = abs(input_0_load(coord).a - input_1_load(coord).a);
|
||||
return vec4<f32>(select(difference, 1. - difference, params().invert));
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
// A silhouette's coverage in its premultiplied gamma-encoded color
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
return params().color * input_0_load(coord).a;
|
||||
}
|
||||
@@ -33,7 +33,6 @@ base64 = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
@@ -127,14 +127,6 @@ impl<P: core_types::CacheHash + Pixel> core_types::CacheHash for Image<P> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ImageError {
|
||||
#[error("The {width}×{height} px image is too large")]
|
||||
TooLarge { width: u32, height: u32 },
|
||||
#[error("The file is not an image in a supported format, or it is damaged")]
|
||||
Undecodable(#[source] ::image::ImageError),
|
||||
}
|
||||
|
||||
impl<P: Pixel> Image<P> {
|
||||
pub fn new(width: u32, height: u32, color: P) -> Self {
|
||||
Self {
|
||||
@@ -143,18 +135,6 @@ impl<P: Pixel> Image<P> {
|
||||
data: vec![color; (width * height) as usize],
|
||||
}
|
||||
}
|
||||
|
||||
/// An image filled with `color`, failing where the pixel count overflows the `u32` pixel indices or can't be allocated.
|
||||
pub fn try_new(width: u32, height: u32, color: P) -> Result<Self, ImageError> {
|
||||
let too_large = || ImageError::TooLarge { width, height };
|
||||
let count = width.checked_mul(height).ok_or_else(too_large)? as usize;
|
||||
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(count).map_err(|_| too_large())?;
|
||||
data.resize(count, color);
|
||||
|
||||
Ok(Self { width, height, data })
|
||||
}
|
||||
}
|
||||
|
||||
impl Image<Color> {
|
||||
@@ -164,8 +144,8 @@ impl Image<Color> {
|
||||
Image { width, height, data }
|
||||
}
|
||||
|
||||
/// Decodes an image file of any supported format, or gives the reason it can't be.
|
||||
pub fn from_encoded(data: &[u8]) -> Result<Self, ImageError> {
|
||||
/// Decodes an image file of any supported format.
|
||||
pub fn from_encoded(data: &[u8]) -> Option<Self> {
|
||||
let image = decode(data)?;
|
||||
|
||||
// Most files hold eight-bit samples, which decode through a table of all 256 values rather than a power function for each
|
||||
@@ -179,7 +159,7 @@ impl Image<Color> {
|
||||
.map(|&[red, green, blue, alpha]| SRGBA8::new(red, green, blue, alpha).into())
|
||||
.collect();
|
||||
|
||||
return Ok(Image {
|
||||
return Some(Image {
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
data,
|
||||
@@ -207,7 +187,7 @@ impl Image<Color> {
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Image {
|
||||
Some(Image {
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
data,
|
||||
@@ -216,7 +196,7 @@ impl Image<Color> {
|
||||
|
||||
/// The pixel size of an image file, if it decodes in full as [`Image::from_encoded`] needs it to.
|
||||
pub fn encoded_size(data: &[u8]) -> Option<(u32, u32)> {
|
||||
decode(data).ok().map(|image| (image.width(), image.height()))
|
||||
decode(data).map(|image| (image.width(), image.height()))
|
||||
}
|
||||
|
||||
/// The image shrunk by half along each axis `times` times, averaging each block of pixels with their colors weighted by their alpha.
|
||||
@@ -266,17 +246,9 @@ impl Image<Color> {
|
||||
}
|
||||
|
||||
/// A TGA file has no signature to recognize it by, so a file of no recognized format is tried as one.
|
||||
fn decode(data: &[u8]) -> Result<::image::DynamicImage, ImageError> {
|
||||
fn decode(data: &[u8]) -> Option<::image::DynamicImage> {
|
||||
let format = ::image::guess_format(data).unwrap_or(::image::ImageFormat::Tga);
|
||||
::image::load_from_memory_with_format(data, format).map_err(|error| {
|
||||
// The memory limit error carries no size, which the header gives
|
||||
if let ::image::ImageError::Limits(_) = error
|
||||
&& let Ok((width, height)) = ::image::ImageReader::with_format(std::io::Cursor::new(data), format).into_dimensions()
|
||||
{
|
||||
return ImageError::TooLarge { width, height };
|
||||
}
|
||||
ImageError::Undecodable(error)
|
||||
})
|
||||
::image::load_from_memory_with_format(data, format).ok()
|
||||
}
|
||||
|
||||
use super::*;
|
||||
@@ -417,37 +389,12 @@ mod test {
|
||||
let mut encoded = Vec::new();
|
||||
pixels.write_to(&mut std::io::Cursor::new(&mut encoded), format).unwrap();
|
||||
|
||||
let image = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{format:?} should decode: {error}"));
|
||||
let image = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{format:?} should decode"));
|
||||
assert_eq!(Image::encoded_size(&encoded), Some((2, 1)), "{format:?}");
|
||||
assert_eq!(image.to_flat_u8().0, pixels.as_raw().as_slice(), "{format:?}");
|
||||
}
|
||||
|
||||
assert!(Image::from_encoded(b"not an image").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_decode_gives_its_reason() {
|
||||
use super::*;
|
||||
|
||||
assert!(matches!(Image::from_encoded(b"not an image"), Err(ImageError::Undecodable(_))));
|
||||
|
||||
// A BMP header for a 32-bit image of 30000×30000 pixels, which is far beyond the decoder's memory limit
|
||||
let mut file = b"BM".to_vec();
|
||||
for field in [54_u32, 0, 54, 40, 30000, 30000] {
|
||||
file.extend(field.to_le_bytes());
|
||||
}
|
||||
file.extend([1, 0, 32, 0]);
|
||||
file.extend([0; 24]);
|
||||
let error = Image::from_encoded(&file).unwrap_err();
|
||||
assert!(matches!(error, ImageError::TooLarge { width: 30000, height: 30000 }), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_too_large_for_its_pixel_indices_is_not_made() {
|
||||
use super::*;
|
||||
|
||||
assert!(matches!(Image::try_new(65536, 65536, Color::BLACK), Err(ImageError::TooLarge { width: 65536, height: 65536 })));
|
||||
assert_eq!(Image::try_new(3, 2, Color::BLACK).unwrap().data, vec![Color::BLACK; 6]);
|
||||
assert!(Image::from_encoded(b"not an image").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -506,7 +453,7 @@ mod test {
|
||||
file.extend([0, 255, 0, 0]);
|
||||
|
||||
assert!(::image::load_from_memory_with_format(&file, ::image::ImageFormat::Tga).is_ok());
|
||||
assert!(Image::from_encoded(&file).is_err());
|
||||
assert!(Image::from_encoded(&file).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,7 +2,7 @@ pub mod image;
|
||||
pub mod raster_types;
|
||||
|
||||
// Re-exports for convenience
|
||||
pub use image::{Image, ImageError};
|
||||
pub use image::Image;
|
||||
pub use raster_types::*;
|
||||
|
||||
// Re-export color types from core-types
|
||||
|
||||
@@ -80,7 +80,7 @@ mod cpu {
|
||||
use super::*;
|
||||
use crate::raster_types::__private::Sealed;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
|
||||
use std::sync::{Arc, OnceLock, Weak};
|
||||
|
||||
/// Pixels in CPU memory, shared between clones and identified by an ID that changes whenever they are modified.
|
||||
/// So cloning is a reference count increment, and hashing for caches reads the ID rather than every pixel.
|
||||
@@ -94,8 +94,6 @@ mod cpu {
|
||||
image: Image<Color>,
|
||||
/// The pixels encoded as a PNG data URL, made the first time an SVG embeds them.
|
||||
png_data_url: OnceLock<Arc<str>>,
|
||||
/// The pixels most recently derived from these, with the key they were derived for.
|
||||
derived: Mutex<Option<(u64, Raster<CPU>)>>,
|
||||
}
|
||||
|
||||
// A copy is made only to be modified, so it starts without an ID
|
||||
@@ -105,7 +103,6 @@ mod cpu {
|
||||
id: AtomicU64::new(0),
|
||||
image: self.image.clone(),
|
||||
png_data_url: OnceLock::new(),
|
||||
derived: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,21 +204,6 @@ mod cpu {
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Pixels derived from these by `derive` for `key`.
|
||||
/// The latest are kept with these pixels and shared by every clone, so deriving them again for the same key reuses them, ID and all.
|
||||
pub fn derived(&self, key: u64, derive: impl FnOnce(&Self) -> Raster<CPU>) -> Raster<CPU> {
|
||||
let mut derived = self.0.derived.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((derived_key, raster)) = &*derived
|
||||
&& *derived_key == key
|
||||
{
|
||||
return raster.clone();
|
||||
}
|
||||
|
||||
let raster = derive(self);
|
||||
*derived = Some((key, raster.clone()));
|
||||
raster
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for CPU {
|
||||
@@ -233,12 +215,11 @@ mod cpu {
|
||||
}
|
||||
|
||||
impl DerefMut for CPU {
|
||||
/// Copies the pixels if another clone shares them, and drops their ID, PNG encoding, and derived pixels since they may change.
|
||||
/// Copies the pixels if another clone shares them, and drops their ID and PNG encoding since they may change.
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
let buffer = Arc::make_mut(&mut self.0);
|
||||
*buffer.id.get_mut() = 0;
|
||||
buffer.png_data_url = OnceLock::new();
|
||||
*buffer.derived.get_mut().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
&mut buffer.image
|
||||
}
|
||||
}
|
||||
@@ -289,22 +270,6 @@ mod cpu {
|
||||
assert_eq!(raster.data().data.as_ptr(), pixels, "pixels nothing else shares are modified without a copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_pixels_are_reused_for_the_same_key_until_the_pixels_change() {
|
||||
let mut raster = Raster::new_cpu(Image::new(2, 2, Color::BLACK));
|
||||
let derive = |_: &Raster<CPU>| Raster::new_cpu(Image::new(1, 1, Color::WHITE));
|
||||
|
||||
let first = raster.derived(1, derive);
|
||||
let again = raster.clone().derived(1, |_| panic!("the pixels derived for this key are kept"));
|
||||
assert_eq!(again.buffer_id(), first.buffer_id(), "reused pixels keep their ID");
|
||||
|
||||
let second = raster.derived(2, derive);
|
||||
assert_ne!(second.buffer_id(), first.buffer_id(), "another key derives anew");
|
||||
|
||||
raster.data_mut().data[0] = Color::WHITE;
|
||||
assert_ne!(raster.derived(2, derive).buffer_id(), second.buffer_id(), "modified pixels derive anew");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_pixels_compare_equal_whatever_their_ids() {
|
||||
let first = Raster::new_cpu(Image::new(2, 2, Color::BLACK));
|
||||
|
||||
@@ -36,7 +36,6 @@ usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
@@ -1,541 +0,0 @@
|
||||
//! Gradients whose two ends are each a contour dialed between a line, a circle, and a point, with the contours between
|
||||
//! them filling in as the pencil of circles the two end contours span.
|
||||
//!
|
||||
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
|
||||
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its dial
|
||||
//! `α ∈ [-1, 1]`: 0 is the line perpendicular to the gradient line, ±1 is the endpoint itself, and in between is a circle
|
||||
//! bowing toward (positive) or away from (negative) the other endpoint.
|
||||
//!
|
||||
//! The contours between are the members of the pencil the end contours span. Each member is spaced by where it crosses
|
||||
//! the gradient line, so a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
|
||||
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
|
||||
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
pub use graphic_types::vector_types::gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
/// Stands in for a t of infinity, on the contours whose crossing with the gradient line is at infinity.
|
||||
const UNBOUNDED_T: f64 = 1e6;
|
||||
|
||||
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
|
||||
/// or a point where it has zero radius.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AxisCircle {
|
||||
pub a: f64,
|
||||
pub b: f64,
|
||||
pub c: f64,
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// The contour through the start point at the origin, dialed by `alpha` toward the end point.
|
||||
pub fn start(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self { a: sin, b: -2. * cos, c: 0. }
|
||||
}
|
||||
|
||||
/// The contour through the end point at (1, 0), dialed by `alpha` toward the start point.
|
||||
pub fn end(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self {
|
||||
a: sin,
|
||||
b: 2. * cos - 2. * sin,
|
||||
c: sin - 2. * cos,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, point: DVec2) -> f64 {
|
||||
self.a * point.length_squared() + self.b * point.x + self.c
|
||||
}
|
||||
|
||||
/// The points where it crosses the gradient line, in homogeneous form.
|
||||
fn crossings(&self) -> [Homogeneous; 2] {
|
||||
solve_quadratic(self.a, self.b, self.c)
|
||||
}
|
||||
|
||||
/// The member of the pencil `self·weight + other·other_weight`.
|
||||
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
|
||||
Self {
|
||||
a: self.a * weight + other.a * other_weight,
|
||||
b: self.b * weight + other.b * other_weight,
|
||||
c: self.c * weight + other.c * other_weight,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct Homogeneous {
|
||||
numerator: f64,
|
||||
denominator: f64,
|
||||
}
|
||||
|
||||
impl Homogeneous {
|
||||
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
|
||||
fn value(&self) -> Option<f64> {
|
||||
(self.denominator != 0.).then(|| self.numerator / self.denominator)
|
||||
}
|
||||
|
||||
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
|
||||
fn normalized(self) -> Self {
|
||||
let scale = self.numerator.abs().max(self.denominator.abs());
|
||||
if scale == 0. {
|
||||
return self;
|
||||
}
|
||||
Self {
|
||||
numerator: self.numerator / scale,
|
||||
denominator: self.denominator / scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
|
||||
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
|
||||
let discriminant = (b * b - 4. * a * c).max(0.);
|
||||
let sign = if b >= 0. { 1. } else { -1. };
|
||||
let q = -0.5 * (b + sign * discriminant.sqrt());
|
||||
|
||||
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
|
||||
}
|
||||
|
||||
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum CrossingSelection {
|
||||
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
|
||||
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
|
||||
/// on the same side of `radical_x` as the pixel.
|
||||
SameSideAs { radical_x: f64 },
|
||||
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
|
||||
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
|
||||
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
|
||||
OnArc { quadratic: [f64; 3] },
|
||||
}
|
||||
|
||||
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Wrap {
|
||||
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
|
||||
pub reference_x: f64,
|
||||
/// Which side of `reference_x` the band is on, `1` or `-1`.
|
||||
pub band_side: f64,
|
||||
/// The t of the crossings on the far side of infinity.
|
||||
pub t: f64,
|
||||
}
|
||||
|
||||
/// Everything needed to find the t of any pixel in a dialed gradient.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PencilParameters {
|
||||
pub start: AxisCircle,
|
||||
pub end: AxisCircle,
|
||||
pub selection: CrossingSelection,
|
||||
pub wrap: Option<Wrap>,
|
||||
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
|
||||
pub t_scale: f64,
|
||||
pub t_offset: f64,
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The parameters of the gradient with these two dials, which must be finite and within -1 to 1.
|
||||
pub fn new(start_dial: f64, end_dial: f64) -> Self {
|
||||
let start = AxisCircle::start(start_dial);
|
||||
let end = AxisCircle::end(end_dial);
|
||||
|
||||
// The members of the pencil that are points have a zero discriminant, which as a quadratic form in the two members'
|
||||
// weights has these coefficients. Its determinant says whether the pencil has two such points (it's hyperbolic), none
|
||||
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
|
||||
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
|
||||
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
|
||||
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
|
||||
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
|
||||
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
|
||||
|
||||
if determinant > 1e-12 * scale * scale {
|
||||
// The line through the two points where the end contours cross is the member with no curvature
|
||||
let line = start.combine(end.a, &end, -start.a);
|
||||
let radical_x = -line.c / line.b;
|
||||
|
||||
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1.);
|
||||
}
|
||||
|
||||
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
|
||||
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
|
||||
let member = start.combine(start_weight, &end, end_weight);
|
||||
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
|
||||
if member.a.abs() <= 1e-12 * magnitude {
|
||||
return Homogeneous::INFINITY;
|
||||
}
|
||||
|
||||
Homogeneous {
|
||||
numerator: -member.b,
|
||||
denominator: 2. * member.a,
|
||||
}
|
||||
.normalized()
|
||||
});
|
||||
|
||||
// Each crossing's place relative to the limit points, negative between them and positive beyond them
|
||||
let arc_quadratic = arc_quadratic(limit_points);
|
||||
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
|
||||
|
||||
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
|
||||
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
|
||||
crossings
|
||||
.into_iter()
|
||||
.min_by(|a, b| {
|
||||
let (a, b) = (arc_of(*a), arc_of(*b));
|
||||
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
|
||||
})
|
||||
.unwrap_or(Homogeneous::INFINITY)
|
||||
};
|
||||
let candidates = [true, false].map(|negative_arc| {
|
||||
let band_start = choose_on_arc(start.crossings(), negative_arc);
|
||||
let band_end = choose_on_arc(end.crossings(), negative_arc);
|
||||
(negative_arc, band_start, band_end)
|
||||
});
|
||||
|
||||
// A band through infinity would give a contour within it an infinite t, so it's unusable. Among the rest, prefer the
|
||||
// band that keeps the endpoints at t of 0 and 1.
|
||||
let limit_values = limit_points.map(|point| point.value());
|
||||
let usable = |band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
|
||||
return false;
|
||||
};
|
||||
match limit_values {
|
||||
[Some(first), Some(second)] => {
|
||||
let (low, high) = (first.min(second), first.max(second));
|
||||
let beyond = |y: f64| {
|
||||
if y > high {
|
||||
1
|
||||
} else if y < low {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
// On the outer arc, crossings on opposite sides of the limit points lie across infinity from each other
|
||||
beyond(band_start) * beyond(band_end) >= 0
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let truthfulness = |band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let is = |point: Homogeneous, target: f64| point.value().is_some_and(|value| (value - target).abs() < 1e-9);
|
||||
is(band_start, 0.) as u8 + is(band_end, 1.) as u8
|
||||
};
|
||||
let chosen = candidates
|
||||
.into_iter()
|
||||
.filter(|&(_, band_start, band_end)| usable(band_start, band_end))
|
||||
.max_by_key(|&(_, band_start, band_end)| truthfulness(band_start, band_end))
|
||||
.unwrap_or(candidates[1]);
|
||||
let (negative_arc, band_start, band_end) = chosen;
|
||||
|
||||
// Choosing the smallest value picks the crossing on the chosen arc
|
||||
let sign = if negative_arc { 1. } else { -1. };
|
||||
let selection = CrossingSelection::OnArc {
|
||||
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
|
||||
};
|
||||
|
||||
let band_start = band_start.value().unwrap_or(0.);
|
||||
let band_end = band_end.value().unwrap_or(1.);
|
||||
|
||||
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
|
||||
let wrap = match (negative_arc, limit_values) {
|
||||
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
|
||||
let reference_x = (first + second) / 2.;
|
||||
let band_side = if band_start > reference_x { 1. } else { -1. };
|
||||
let t_direction = (band_end - band_start).signum();
|
||||
Some(Wrap {
|
||||
reference_x,
|
||||
band_side,
|
||||
t: band_side * t_direction * UNBOUNDED_T,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Self::with_band(start, end, selection, wrap, band_start, band_end)
|
||||
}
|
||||
|
||||
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64) -> Self {
|
||||
let width = band_end - band_start;
|
||||
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
|
||||
|
||||
Self {
|
||||
start,
|
||||
end,
|
||||
selection,
|
||||
wrap,
|
||||
t_scale: 1. / width,
|
||||
t_offset: -band_start / width,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
|
||||
pub fn t(&self, point: DVec2) -> f64 {
|
||||
let start_value = self.start.value(point);
|
||||
let end_value = self.end.value(point);
|
||||
let scale = start_value.abs().max(end_value.abs());
|
||||
if scale == 0. {
|
||||
return 0.;
|
||||
}
|
||||
let (start_value, end_value) = (start_value / scale, end_value / scale);
|
||||
|
||||
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
|
||||
// roots of this quadratic
|
||||
let a = end_value * self.start.a - start_value * self.end.a;
|
||||
let b = end_value * self.start.b - start_value * self.end.b;
|
||||
let c = end_value * self.start.c - start_value * self.end.c;
|
||||
let roots = solve_quadratic(a, b, c);
|
||||
|
||||
let crossing = match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => {
|
||||
// A pixel on the dividing line itself is on the line member, whose crossing is the finite root
|
||||
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
|
||||
let (first, second) = (side(roots[0]), side(roots[1]));
|
||||
let first_wins = if first == second {
|
||||
roots[0].denominator.abs() >= roots[1].denominator.abs()
|
||||
} else {
|
||||
first > second
|
||||
};
|
||||
if first_wins { roots[0] } else { roots[1] }
|
||||
}
|
||||
CrossingSelection::OnArc { quadratic } => {
|
||||
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
|
||||
roots[0]
|
||||
} else {
|
||||
roots[1]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(wrap) = self.wrap
|
||||
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
|
||||
{
|
||||
return wrap.t;
|
||||
}
|
||||
|
||||
if crossing.denominator == 0. {
|
||||
let direction = crossing.numerator * self.t_scale;
|
||||
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
|
||||
}
|
||||
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
|
||||
}
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The same parameters for Vello GPU's pencil gradient paint.
|
||||
pub fn to_vello(&self) -> vello_gpu::PencilGeometry {
|
||||
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
|
||||
|
||||
vello_gpu::PencilGeometry {
|
||||
start: circle(&self.start),
|
||||
end: circle(&self.end),
|
||||
selection: match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
|
||||
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
|
||||
quadratic: quadratic.map(|coefficient| coefficient as f32),
|
||||
},
|
||||
},
|
||||
wrap: self.wrap.map(|wrap| vello_gpu::PencilWrap {
|
||||
reference_x: wrap.reference_x as f32,
|
||||
band_side: wrap.band_side as f32,
|
||||
t: wrap.t as f32,
|
||||
}),
|
||||
t_scale: self.t_scale as f32,
|
||||
t_offset: self.t_offset as f32,
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest gradient SVG can express: a radial gradient from the start circle to the end circle when one nests inside
|
||||
/// the other, or else the linear gradient along the gradient line.
|
||||
pub fn svg_approximation(&self) -> SvgApproximation {
|
||||
let (Some(start), Some(end)) = (self.start.center_and_radius(), self.end.center_and_radius()) else {
|
||||
return SvgApproximation::Linear;
|
||||
};
|
||||
|
||||
let distance = (start.0 - end.0).abs();
|
||||
let nested = distance <= (start.1 - end.1).abs();
|
||||
if !nested {
|
||||
return SvgApproximation::Linear;
|
||||
}
|
||||
|
||||
SvgApproximation::Radial {
|
||||
start_center: start.0,
|
||||
start_radius: start.1,
|
||||
end_center: end.0,
|
||||
end_radius: end.1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient SVG can draw in place of a dialed one, in gradient space.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum SvgApproximation {
|
||||
Linear,
|
||||
/// From the start circle, as SVG's focal circle, out to the end circle, both centered on the gradient line.
|
||||
Radial {
|
||||
start_center: f64,
|
||||
start_radius: f64,
|
||||
end_center: f64,
|
||||
end_radius: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// Where its center sits on the gradient line, and its radius, unless it's a line.
|
||||
fn center_and_radius(&self) -> Option<(f64, f64)> {
|
||||
if self.a.abs() < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let center = -self.b / (2. * self.a);
|
||||
let radius = (center * center - self.c / self.a).max(0.).sqrt();
|
||||
Some((center, radius))
|
||||
}
|
||||
}
|
||||
|
||||
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
|
||||
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
|
||||
let discriminant = (cross * cross - start * end).max(0.).sqrt();
|
||||
|
||||
if start.abs() < 1e-12 && end.abs() < 1e-12 {
|
||||
// Both end contours are points already
|
||||
[(1., 0.), (0., 1.)]
|
||||
} else if start.abs() >= end.abs() {
|
||||
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
|
||||
} else {
|
||||
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
|
||||
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
|
||||
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
|
||||
let orient = |point: Homogeneous| {
|
||||
if point.denominator < 0. {
|
||||
Homogeneous {
|
||||
numerator: -point.numerator,
|
||||
denominator: -point.denominator,
|
||||
}
|
||||
} else {
|
||||
point
|
||||
}
|
||||
};
|
||||
let (first, second) = (orient(first), orient(second));
|
||||
|
||||
[
|
||||
first.denominator * second.denominator,
|
||||
-(first.denominator * second.numerator + first.numerator * second.denominator),
|
||||
first.numerator * second.numerator,
|
||||
]
|
||||
}
|
||||
|
||||
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
|
||||
let Homogeneous { numerator, denominator } = point;
|
||||
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, context: &str) {
|
||||
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_dials_space_contours_by_radius() {
|
||||
let parameters = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
|
||||
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
|
||||
for angle in [0., 0.7, 2., 3.1, 4.5] {
|
||||
let point = DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_dials_space_contours_by_distance_along_the_line() {
|
||||
let parameters = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
|
||||
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
|
||||
assert_close(parameters.t(point), point.x, &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concentric_dials_space_contours_by_radius_between_the_ends() {
|
||||
// The donut: a hole of radius 1 centered 1 before the start, and an end circle of radius 2 around the same center
|
||||
let parameters = PencilParameters::new(-0.5, 0.5_f64.atan() / FRAC_PI_2);
|
||||
let center = DVec2::new(-1., 0.);
|
||||
for radius in [1., 1.25, 1.5, 2., 3.] {
|
||||
for angle in [0., 1., 2.5, 4.] {
|
||||
let point = center + DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius - 1., &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_dials_space_contours_by_distance_ratio() {
|
||||
let parameters = PencilParameters::new(1., 1.);
|
||||
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
|
||||
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
|
||||
let ratio = point.length() / (point - DVec2::X).length();
|
||||
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dials_near_a_preset_render_like_it() {
|
||||
let radial = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
|
||||
let near_radial = PencilParameters::new(RADIAL_DIALS[0] - 1e-7, RADIAL_DIALS[1] + 1e-7);
|
||||
let linear = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
|
||||
let near_linear = PencilParameters::new(LINEAR_DIALS[0] + 1e-7, LINEAR_DIALS[1] - 1e-7);
|
||||
|
||||
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
|
||||
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
|
||||
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
|
||||
// The start point sits inside the end circle, off its center
|
||||
let parameters = PencilParameters::new(1., 0.6);
|
||||
|
||||
assert_close(parameters.t(DVec2::X), 1., "end point");
|
||||
let inside = parameters.t(DVec2::new(0.5, 0.));
|
||||
assert!(inside > 0. && inside < 1., "inside: {inside}");
|
||||
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
|
||||
let t = parameters.t(point);
|
||||
assert!(t > 1., "outside at {point}: {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_contours_fan_through_their_lens() {
|
||||
let parameters = PencilParameters::new(0.6, 0.6);
|
||||
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
|
||||
|
||||
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
|
||||
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
|
||||
}
|
||||
// Mirrored across the gradient line
|
||||
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_dial_pair_gives_a_number_everywhere() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let parameters = PencilParameters::new(start_step as f64 / 10., end_step as f64 / 10.);
|
||||
for x in -8..=8 {
|
||||
for y in -8..=8 {
|
||||
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
|
||||
let t = parameters.t(point);
|
||||
assert!(!t.is_nan(), "dials ({start_step}, {end_step}) at {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod convert_usvg_path;
|
||||
pub mod dial_gradient;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
pub mod to_peniko;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::renderer::{
|
||||
GradientShape, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples,
|
||||
svg_gradient_definition, transform_is_invertible,
|
||||
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples, transform_is_invertible,
|
||||
};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_TRANSFORM, Color};
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientForm;
|
||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use std::fmt::Write;
|
||||
use vector_types::Gradient;
|
||||
@@ -88,11 +88,11 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
|
||||
let item = item?;
|
||||
let stops = item.element()?;
|
||||
let shape = GradientShape::of(item);
|
||||
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let settings = gradient_settings_from_item(item);
|
||||
|
||||
let mut samples = spread_adjusted_samples(stops, settings, shape.reaches_before_start());
|
||||
let mut samples = spread_adjusted_samples(stops, settings, gradient_form);
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
@@ -134,7 +134,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
|
||||
let document_transform = item_transform * local_gradient_transform;
|
||||
|
||||
let placement = gradient_placement(document_transform, shape);
|
||||
let placement = gradient_placement(document_transform, gradient_form);
|
||||
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||
let gradient_transform = if gradient_transform.is_empty() {
|
||||
String::new()
|
||||
@@ -149,7 +149,23 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
};
|
||||
|
||||
let gradient_id = generate_uuid();
|
||||
svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &format!("{gradient_spread}{gradient_transform}"), &stop));
|
||||
|
||||
match gradient_form {
|
||||
GradientForm::Linear => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
GradientForm::Radial => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Some(gradient_id)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,20 +1,16 @@
|
||||
use glam::{DMat2, UVec2};
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use vello_gpu::peniko::{self, BlendMode, Brush, Fill};
|
||||
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
|
||||
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
|
||||
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
|
||||
|
||||
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
||||
const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
|
||||
/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures.
|
||||
const EFFECTS_SIZE_CLASS: u32 = 64;
|
||||
|
||||
/// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time.
|
||||
pub struct VelloSceneBuilder<'a> {
|
||||
#[derive(Debug)]
|
||||
pub struct VelloSceneBuilder {
|
||||
scene: vello_gpu::Scene,
|
||||
/// Places the drawn content in the scene, applied on top of every transform it's drawn with.
|
||||
view: Affine,
|
||||
@@ -24,71 +20,6 @@ pub struct VelloSceneBuilder<'a> {
|
||||
/// The largest width or height an image's texture can have, beyond which images are drawn from a downscaled texture.
|
||||
max_texture_size: u32,
|
||||
pushed: Vec<Pushed>,
|
||||
/// Renders effects groups as they're drawn. A scene drawn ahead of its render has none, so it draws effects groups without their effects.
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
pub trait EffectsRenderer: Send {
|
||||
/// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill.
|
||||
fn renders_effects(&self) -> bool;
|
||||
|
||||
/// Renders the content `draw` draws, and each paint overlay's paint `draw_paint` draws by index, placed by `view` in textures of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
|
||||
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
&mut self,
|
||||
size: UVec2,
|
||||
view: Affine,
|
||||
effects: &Effects,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Texture;
|
||||
|
||||
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
|
||||
/// `None` if they can't be carried out.
|
||||
fn adjust_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture>;
|
||||
}
|
||||
|
||||
/// What a fill or stroke paints with.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SceneBrush {
|
||||
/// A solid color, gradient, or image.
|
||||
Peniko(Brush),
|
||||
/// A gradient whose contours are a pencil of circles, which only Vello GPU's fork can draw.
|
||||
PencilGradient(PencilGradient),
|
||||
}
|
||||
|
||||
impl From<Brush> for SceneBrush {
|
||||
fn from(brush: Brush) -> Self {
|
||||
Self::Peniko(brush)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Brush> for SceneBrush {
|
||||
fn from(brush: &Brush) -> Self {
|
||||
Self::Peniko(brush.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<peniko::Color> for SceneBrush {
|
||||
fn from(color: peniko::Color) -> Self {
|
||||
Self::Peniko(Brush::Solid(color))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&peniko::Gradient> for SceneBrush {
|
||||
fn from(gradient: &peniko::Gradient) -> Self {
|
||||
Self::Peniko(Brush::Gradient(gradient.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PencilGradient> for SceneBrush {
|
||||
fn from(gradient: PencilGradient) -> Self {
|
||||
Self::PencilGradient(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
@@ -98,15 +29,15 @@ pub enum SceneImage {
|
||||
Pixels(peniko::ImageData),
|
||||
/// A CPU raster's straight-alpha linear pixels, identified by their buffer's ID so the renderer uploads them once.
|
||||
Raster(Raster<CPU>),
|
||||
/// Straight-alpha pixels in a GPU texture, whose copy for sampling gets mipmaps if it's drawn `minified`.
|
||||
Texture { texture: Texture, minified: bool },
|
||||
/// Straight-alpha pixels in a GPU texture.
|
||||
Texture(Texture),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(Texture, bool),
|
||||
Texture(Texture),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -115,17 +46,7 @@ enum Pushed {
|
||||
Clip,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for VelloSceneBuilder<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("VelloSceneBuilder")
|
||||
.field("scene", &self.scene)
|
||||
.field("view", &self.view)
|
||||
.field("images", &self.images)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> VelloSceneBuilder<'a> {
|
||||
impl VelloSceneBuilder {
|
||||
pub fn new(width: u16, height: u16, view: Affine, max_texture_size: u32) -> Self {
|
||||
Self::from_vello(vello_gpu::Scene::new(width, height), view, max_texture_size)
|
||||
}
|
||||
@@ -140,16 +61,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
image_ids: HashMap::new(),
|
||||
max_texture_size,
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the effects groups drawn into the scene through `renderer`.
|
||||
pub fn with_effects_renderer(mut self, renderer: &'a mut dyn EffectsRenderer) -> Self {
|
||||
self.effects_renderer = Some(renderer);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u16 {
|
||||
self.scene.width()
|
||||
}
|
||||
@@ -188,32 +102,35 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
}
|
||||
|
||||
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn fill(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
|
||||
}
|
||||
|
||||
/// Like [`Self::fill`] for a path, which it draws without copying.
|
||||
pub fn fill_path(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_path(&finite_path(path));
|
||||
}
|
||||
|
||||
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn stroke(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
||||
}
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport(&mut self, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
|
||||
}
|
||||
@@ -268,71 +185,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Draws a GPU texture's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_texture(&mut self, texture: Texture, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
// Mipmaps only for a texture drawn smaller than its pixels, since they're made again at every render
|
||||
let [a, b, c, d, _, _] = (self.view * transform).as_coeffs();
|
||||
let minified = a.hypot(b) < 1. || c.hypot(d) < 1.;
|
||||
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture { texture, minified }) else {
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture(texture)) else {
|
||||
return;
|
||||
};
|
||||
self.draw_image_source(source, sampler, transform * texture_to_image, texture_size);
|
||||
}
|
||||
|
||||
/// A texture of the CPU `raster`'s pixels with `adjustments` carried out on them, to draw in place of it, if the GPU can carry them out and it fits in one.
|
||||
pub fn adjusted_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture> {
|
||||
if raster.width > self.max_texture_size || raster.height > self.max_texture_size {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
|
||||
}
|
||||
|
||||
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
|
||||
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
|
||||
self.push_viewport_layer(peniko::Mix::Normal, fill);
|
||||
draw(self);
|
||||
self.pop_layer();
|
||||
return;
|
||||
}
|
||||
|
||||
let [a, b, c, d, _, _] = self.view.as_coeffs();
|
||||
let lengths_to_device = DMat2::from_cols_array(&[a, b, c, d]);
|
||||
let reach = effects.reach() * lengths_to_device.determinant().abs().sqrt();
|
||||
|
||||
// The content reaching into the viewport, rounded out to whole pixels
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let content_bounds = bounds.map_or(viewport, |bounds| self.view.transform_rect_bbox(bounds));
|
||||
let region = content_bounds.inflate(reach, reach).intersect(viewport.inflate(reach, reach)).expand();
|
||||
if !(region.width() > 0. && region.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A region too large for one texture renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||
let max_size = self.max_texture_size.min(u16::MAX as u32);
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min(1.);
|
||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * self.view;
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw_paint, draw);
|
||||
|
||||
// Draw the result where the content was
|
||||
self.images.push(SceneImage::Texture { texture: result, minified: false });
|
||||
let id = TextureId(self.images.len() as u64 - 1);
|
||||
self.scene.set_transform(Affine::translate(origin) * Affine::scale(1. / resolution));
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(id, TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
self.scene.fill_rect(&Rect::new(0., 0., size.x as f64, size.y as f64));
|
||||
}
|
||||
|
||||
fn draw_image_source(&mut self, source: ImageSource, sampler: peniko::ImageSampler, transform: Affine, (width, height): (u32, u32)) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_paint(PaintType::Image(Image { image: source, sampler }));
|
||||
@@ -340,31 +198,22 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
|
||||
}
|
||||
|
||||
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn set_paint(&mut self, brush: SceneBrush) -> Option<Affine> {
|
||||
let brush = match brush {
|
||||
SceneBrush::Peniko(brush) => brush,
|
||||
SceneBrush::PencilGradient(gradient) => {
|
||||
self.scene.set_pencil_gradient_paint(gradient);
|
||||
return Some(Affine::IDENTITY);
|
||||
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
|
||||
match brush {
|
||||
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
|
||||
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
|
||||
BrushRef::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
|
||||
Some((
|
||||
PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
}),
|
||||
texture_to_image,
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let (paint, paint_to_brush) = match brush {
|
||||
Brush::Solid(color) => (PaintType::Solid(color), Affine::IDENTITY),
|
||||
Brush::Gradient(gradient) => (PaintType::Gradient(gradient), Affine::IDENTITY),
|
||||
Brush::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image))?;
|
||||
let paint = PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
});
|
||||
(paint, texture_to_image)
|
||||
}
|
||||
};
|
||||
self.scene.set_paint(paint);
|
||||
|
||||
Some(paint_to_brush)
|
||||
}
|
||||
}
|
||||
|
||||
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
|
||||
@@ -372,7 +221,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let (width, height) = match &image {
|
||||
SceneImage::Pixels(data) => (data.width, data.height),
|
||||
SceneImage::Raster(raster) => (raster.width, raster.height),
|
||||
SceneImage::Texture { texture, .. } => (texture.width(), texture.height()),
|
||||
SceneImage::Texture(texture) => (texture.width(), texture.height()),
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -381,7 +230,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let key = match &image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture { texture, minified } => ImageKey::Texture(texture.clone(), *minified),
|
||||
SceneImage::Texture(texture) => ImageKey::Texture(texture.clone()),
|
||||
};
|
||||
let id = *self.image_ids.entry(key).or_insert_with(|| {
|
||||
self.images.push(image);
|
||||
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user